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 CBlockIndex* pindexGenesisBlock = NULL;
40 CBigNum bnBestChainWork = 0;
41 CBigNum bnBestInvalidWork = 0;
42 uint256 hashBestChain = 0;
43 CBlockIndex* pindexBest = NULL;
44 int64 nTimeBestReceived = 0;
46 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
48 map<uint256, CBlock*> mapOrphanBlocks;
49 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
51 map<uint256, CDataStream*> mapOrphanTransactions;
52 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
59 int fGenerateBitcoins = false;
60 int64 nTransactionFee = 0;
61 int fLimitProcessors = false;
62 int nLimitProcessors = 1;
63 int fMinimizeToTray = true;
64 int fMinimizeOnClose = true;
72 //////////////////////////////////////////////////////////////////////////////
74 // dispatching functions
77 // These functions dispatch to one or all registered wallets
80 void RegisterWallet(CWallet* pwalletIn)
82 CRITICAL_BLOCK(cs_setpwalletRegistered)
84 setpwalletRegistered.insert(pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn)
90 CRITICAL_BLOCK(cs_setpwalletRegistered)
92 setpwalletRegistered.erase(pwalletIn);
96 // check whether the passed transaction is from us
97 bool static IsFromMe(CTransaction& tx)
99 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
100 if (pwallet->IsFromMe(tx))
105 // get the wallet transaction with the given hash (if it exists)
106 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
108 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
109 if (pwallet->GetTransaction(hashTx,wtx))
114 // erases transaction with the given hash from all wallets
115 void static EraseFromWallets(uint256 hash)
117 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
118 pwallet->EraseFromWallet(hash);
121 // make sure all wallets know about the given transaction, in the given block
122 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
124 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
128 // notify wallets about a new best chain
129 void static SetBestChain(const CBlockLocator& loc)
131 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132 pwallet->SetBestChain(loc);
135 // notify wallets about an updated transaction
136 void static UpdatedTransaction(const uint256& hashTx)
138 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139 pwallet->UpdatedTransaction(hashTx);
143 void static PrintWallets(const CBlock& block)
145 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146 pwallet->PrintWallet(block);
149 // notify wallets about an incoming inventory (for request counts)
150 void static Inventory(const uint256& hash)
152 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153 pwallet->Inventory(hash);
156 // ask wallets to resend their transactions
157 void static ResendWalletTransactions()
159 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160 pwallet->ResendWalletTransactions();
169 //////////////////////////////////////////////////////////////////////////////
171 // mapOrphanTransactions
174 void static AddOrphanTx(const CDataStream& vMsg)
177 CDataStream(vMsg) >> tx;
178 uint256 hash = tx.GetHash();
179 if (mapOrphanTransactions.count(hash))
181 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
182 BOOST_FOREACH(const CTxIn& txin, tx.vin)
183 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
186 void static EraseOrphanTx(uint256 hash)
188 if (!mapOrphanTransactions.count(hash))
190 const CDataStream* pvMsg = mapOrphanTransactions[hash];
192 CDataStream(*pvMsg) >> tx;
193 BOOST_FOREACH(const CTxIn& txin, tx.vin)
195 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
196 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
198 if ((*mi).second == pvMsg)
199 mapOrphanTransactionsByPrev.erase(mi++);
205 mapOrphanTransactions.erase(hash);
215 //////////////////////////////////////////////////////////////////////////////
217 // CTransaction and CTxIndex
220 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
223 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
225 if (!ReadFromDisk(txindexRet.pos))
227 if (prevout.n >= vout.size())
235 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
238 return ReadFromDisk(txdb, prevout, txindex);
241 bool CTransaction::ReadFromDisk(COutPoint prevout)
245 return ReadFromDisk(txdb, prevout, txindex);
248 bool CTransaction::IsStandard() const
250 BOOST_FOREACH(const CTxIn& txin, vin)
252 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
253 // in an OP_EVAL, which is 3 ~80-byte signatures, 3
254 // ~65-byte public keys, plus a few script ops.
255 if (txin.scriptSig.size() > 500)
256 return error("nonstandard txin, size %d is too large\n", txin.scriptSig.size());
257 if (!txin.scriptSig.IsPushOnly())
258 return error("nonstandard txin (opcodes other than PUSH): %s", txin.scriptSig.ToString().c_str());
260 BOOST_FOREACH(const CTxOut& txout, vout)
261 if (!::IsStandard(txout.scriptPubKey))
262 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
267 // Check transaction inputs, and make sure any
268 // OP_EVAL transactions are evaluating IsStandard scripts
270 // Why bother? To avoid denial-of-service attacks; an attacker
271 // can submit a standard DUP HASH... OP_EVAL transaction,
272 // which will get accepted into blocks. The script being
273 // EVAL'ed can be anything; an attacker could use a very
274 // expensive-to-check-upon-redemption script like:
275 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
277 bool CTransaction::AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const
280 return true; // Allow non-standard on testnet
282 for (int i = 0; i < vin.size(); i++)
284 COutPoint prevout = vin[i].prevout;
285 assert(mapInputs.count(prevout.hash) > 0);
286 CTransaction& txPrev = mapInputs[prevout.hash].second;
287 assert(prevout.n < txPrev.vout.size());
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 > std::numeric_limits<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, GMF_RELAY))
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())
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());
950 // Make sure all prevout.n's are valid:
951 for (int i = 0; i < vin.size(); i++)
953 const COutPoint prevout = vin[i].prevout;
954 const CTxIndex& txindex = inputsRet[prevout.hash].first;
955 const CTransaction& txPrev = inputsRet[prevout.hash].second;
956 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
957 return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
963 bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
964 map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
965 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee)
967 // Take over previous transactions' spent pointers
968 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
969 // fMiner is true when called from the internal bitcoin miner
970 // ... both are false when called from CTransaction::AcceptToMemoryPool
974 for (int i = 0; i < vin.size(); i++)
976 COutPoint prevout = vin[i].prevout;
977 assert(inputs.count(prevout.hash) > 0);
978 CTxIndex& txindex = inputs[prevout.hash].first;
979 CTransaction& txPrev = inputs[prevout.hash].second;
981 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
982 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()));
984 // If prev is coinbase, check that it's matured
985 if (txPrev.IsCoinBase())
986 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
987 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
988 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
990 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
991 // before the last blockchain checkpoint. This is safe because block merkle hashes are
992 // still computed and checked, and any change will be caught at the next checkpoint.
993 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
995 bool fStrictOpEval = true;
996 // This code should be removed when OP_EVAL has
997 // a majority of hashing power on the network.
1000 // To avoid being on the short end of a block-chain split,
1001 // interpret OP_EVAL as a NO_OP until blocks with timestamps
1002 // after opevaltime:
1003 int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400); // Feb 1, 2012
1004 fStrictOpEval = (pindexBlock->nTime >= nEvalSwitchTime);
1006 // if !fBlock, then always be strict-- don't accept
1007 // invalid-under-new-rules OP_EVAL transactions into
1008 // our memory pool (don't relay them, don't include them
1009 // in blocks we mine).
1012 if (!VerifySignature(txPrev, *this, i, nSigOpsRet, fStrictOpEval))
1013 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1016 // Check for conflicts (double-spend)
1017 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1018 // for an attacker to attempt to split the network.
1019 if (!txindex.vSpent[prevout.n].IsNull())
1020 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());
1022 // Check for negative or overflow input values
1023 nValueIn += txPrev.vout[prevout.n].nValue;
1024 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1025 return DoS(100, error("ConnectInputs() : txin values out of range"));
1027 // Mark outpoints as spent
1028 txindex.vSpent[prevout.n] = posThisTx;
1031 if (fBlock || fMiner)
1033 mapTestPool[prevout.hash] = txindex;
1037 if (nValueIn < GetValueOut())
1038 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1040 // Tally transaction fees
1041 int64 nTxFee = nValueIn - GetValueOut();
1043 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1044 if (nTxFee < nMinFee)
1047 if (!MoneyRange(nFees))
1048 return DoS(100, error("ConnectInputs() : nFees out of range"));
1053 // Add transaction to changes
1054 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
1058 // Add transaction to test pool
1059 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1066 bool CTransaction::ClientConnectInputs()
1071 // Take over previous transactions' spent pointers
1072 CRITICAL_BLOCK(cs_mapTransactions)
1075 for (int i = 0; i < vin.size(); i++)
1077 // Get prev tx from single transactions in memory
1078 COutPoint prevout = vin[i].prevout;
1079 if (!mapTransactions.count(prevout.hash))
1081 CTransaction& txPrev = mapTransactions[prevout.hash];
1083 if (prevout.n >= txPrev.vout.size())
1088 if (!VerifySignature(txPrev, *this, i, nUnused, false))
1089 return error("ConnectInputs() : VerifySignature failed");
1091 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1092 ///// this has to go away now that posNext is gone
1093 // // Check for conflicts
1094 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1095 // return error("ConnectInputs() : prev tx already used");
1097 // // Flag outpoints as used
1098 // txPrev.vout[prevout.n].posNext = posThisTx;
1100 nValueIn += txPrev.vout[prevout.n].nValue;
1102 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1103 return error("ClientConnectInputs() : txin values out of range");
1105 if (GetValueOut() > nValueIn)
1115 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1117 // Disconnect in reverse order
1118 for (int i = vtx.size()-1; i >= 0; i--)
1119 if (!vtx[i].DisconnectInputs(txdb))
1122 // Update block index on disk without changing it in memory.
1123 // The memory index structure will be changed after the db commits.
1126 CDiskBlockIndex blockindexPrev(pindex->pprev);
1127 blockindexPrev.hashNext = 0;
1128 if (!txdb.WriteBlockIndex(blockindexPrev))
1129 return error("DisconnectBlock() : WriteBlockIndex failed");
1135 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1137 // Check it again in case a previous version let a bad block in
1141 //// issue here: it doesn't know the version
1142 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1144 map<uint256, CTxIndex> mapQueuedChanges;
1147 BOOST_FOREACH(CTransaction& tx, vtx)
1149 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1150 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1152 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
1153 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
1155 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
1157 if (nSigOps > MAX_BLOCK_SIGOPS)
1158 return DoS(100, error("ConnectBlock() : too many sigops"));
1161 // Write queued txindex changes
1162 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1164 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1165 return error("ConnectBlock() : UpdateTxIndex failed");
1168 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1171 // Update block index on disk without changing it in memory.
1172 // The memory index structure will be changed after the db commits.
1175 CDiskBlockIndex blockindexPrev(pindex->pprev);
1176 blockindexPrev.hashNext = pindex->GetBlockHash();
1177 if (!txdb.WriteBlockIndex(blockindexPrev))
1178 return error("ConnectBlock() : WriteBlockIndex failed");
1181 // Watch for transactions paying to me
1182 BOOST_FOREACH(CTransaction& tx, vtx)
1183 SyncWithWallets(tx, this, true);
1188 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1190 printf("REORGANIZE\n");
1193 CBlockIndex* pfork = pindexBest;
1194 CBlockIndex* plonger = pindexNew;
1195 while (pfork != plonger)
1197 while (plonger->nHeight > pfork->nHeight)
1198 if (!(plonger = plonger->pprev))
1199 return error("Reorganize() : plonger->pprev is null");
1200 if (pfork == plonger)
1202 if (!(pfork = pfork->pprev))
1203 return error("Reorganize() : pfork->pprev is null");
1206 // List of what to disconnect
1207 vector<CBlockIndex*> vDisconnect;
1208 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1209 vDisconnect.push_back(pindex);
1211 // List of what to connect
1212 vector<CBlockIndex*> vConnect;
1213 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1214 vConnect.push_back(pindex);
1215 reverse(vConnect.begin(), vConnect.end());
1217 // Disconnect shorter branch
1218 vector<CTransaction> vResurrect;
1219 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1222 if (!block.ReadFromDisk(pindex))
1223 return error("Reorganize() : ReadFromDisk for disconnect failed");
1224 if (!block.DisconnectBlock(txdb, pindex))
1225 return error("Reorganize() : DisconnectBlock failed");
1227 // Queue memory transactions to resurrect
1228 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1229 if (!tx.IsCoinBase())
1230 vResurrect.push_back(tx);
1233 // Connect longer branch
1234 vector<CTransaction> vDelete;
1235 for (int i = 0; i < vConnect.size(); i++)
1237 CBlockIndex* pindex = vConnect[i];
1239 if (!block.ReadFromDisk(pindex))
1240 return error("Reorganize() : ReadFromDisk for connect failed");
1241 if (!block.ConnectBlock(txdb, pindex))
1245 return error("Reorganize() : ConnectBlock failed");
1248 // Queue memory transactions to delete
1249 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1250 vDelete.push_back(tx);
1252 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1253 return error("Reorganize() : WriteHashBestChain failed");
1255 // Make sure it's successfully written to disk before changing memory structure
1256 if (!txdb.TxnCommit())
1257 return error("Reorganize() : TxnCommit failed");
1259 // Disconnect shorter branch
1260 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1262 pindex->pprev->pnext = NULL;
1264 // Connect longer branch
1265 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1267 pindex->pprev->pnext = pindex;
1269 // Resurrect memory transactions that were in the disconnected branch
1270 BOOST_FOREACH(CTransaction& tx, vResurrect)
1271 tx.AcceptToMemoryPool(txdb, false);
1273 // Delete redundant memory transactions that are in the connected branch
1274 BOOST_FOREACH(CTransaction& tx, vDelete)
1275 tx.RemoveFromMemoryPool();
1281 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1283 uint256 hash = GetHash();
1286 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1288 txdb.WriteHashBestChain(hash);
1289 if (!txdb.TxnCommit())
1290 return error("SetBestChain() : TxnCommit failed");
1291 pindexGenesisBlock = pindexNew;
1293 else if (hashPrevBlock == hashBestChain)
1295 // Adding to current best branch
1296 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1299 InvalidChainFound(pindexNew);
1300 return error("SetBestChain() : ConnectBlock failed");
1302 if (!txdb.TxnCommit())
1303 return error("SetBestChain() : TxnCommit failed");
1305 // Add to current best branch
1306 pindexNew->pprev->pnext = pindexNew;
1308 // Delete redundant memory transactions
1309 BOOST_FOREACH(CTransaction& tx, vtx)
1310 tx.RemoveFromMemoryPool();
1315 if (!Reorganize(txdb, pindexNew))
1318 InvalidChainFound(pindexNew);
1319 return error("SetBestChain() : Reorganize failed");
1323 // Update best block in wallet (so we can detect restored wallets)
1324 if (!IsInitialBlockDownload())
1326 const CBlockLocator locator(pindexNew);
1327 ::SetBestChain(locator);
1331 hashBestChain = hash;
1332 pindexBest = pindexNew;
1333 nBestHeight = pindexBest->nHeight;
1334 bnBestChainWork = pindexNew->bnChainWork;
1335 nTimeBestReceived = GetTime();
1336 nTransactionsUpdated++;
1337 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1343 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1345 // Check for duplicate
1346 uint256 hash = GetHash();
1347 if (mapBlockIndex.count(hash))
1348 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1350 // Construct new block index object
1351 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1353 return error("AddToBlockIndex() : new CBlockIndex failed");
1354 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1355 pindexNew->phashBlock = &((*mi).first);
1356 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1357 if (miPrev != mapBlockIndex.end())
1359 pindexNew->pprev = (*miPrev).second;
1360 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1362 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1366 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1367 if (!txdb.TxnCommit())
1371 if (pindexNew->bnChainWork > bnBestChainWork)
1372 if (!SetBestChain(txdb, pindexNew))
1377 if (pindexNew == pindexBest)
1379 // Notify UI to display prev block's coinbase if it was ours
1380 static uint256 hashPrevBestCoinBase;
1381 UpdatedTransaction(hashPrevBestCoinBase);
1382 hashPrevBestCoinBase = vtx[0].GetHash();
1392 bool CBlock::CheckBlock() const
1394 // These are checks that are independent of context
1395 // that can be verified before saving an orphan block.
1398 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1399 return DoS(100, error("CheckBlock() : size limits failed"));
1401 // Check proof of work matches claimed amount
1402 if (!CheckProofOfWork(GetHash(), nBits))
1403 return DoS(50, error("CheckBlock() : proof of work failed"));
1406 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1407 return error("CheckBlock() : block timestamp too far in the future");
1409 // First transaction must be coinbase, the rest must not be
1410 if (vtx.empty() || !vtx[0].IsCoinBase())
1411 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1412 for (int i = 1; i < vtx.size(); i++)
1413 if (vtx[i].IsCoinBase())
1414 return DoS(100, error("CheckBlock() : more than one coinbase"));
1416 // Check transactions
1417 BOOST_FOREACH(const CTransaction& tx, vtx)
1418 if (!tx.CheckTransaction())
1419 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1421 // This code should be removed when a compatibility-breaking block chain split has passed.
1422 // Compatibility check for old clients that counted sigops differently:
1424 BOOST_FOREACH(const CTransaction& tx, vtx)
1426 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1428 nSigOps += txin.scriptSig.GetSigOpCount();
1430 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1432 nSigOps += txout.scriptPubKey.GetSigOpCount();
1435 if (nSigOps > MAX_BLOCK_SIGOPS)
1436 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1439 if (hashMerkleRoot != BuildMerkleTree())
1440 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1445 bool CBlock::AcceptBlock()
1447 // Check for duplicate
1448 uint256 hash = GetHash();
1449 if (mapBlockIndex.count(hash))
1450 return error("AcceptBlock() : block already in mapBlockIndex");
1452 // Get prev block index
1453 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1454 if (mi == mapBlockIndex.end())
1455 return DoS(10, error("AcceptBlock() : prev block not found"));
1456 CBlockIndex* pindexPrev = (*mi).second;
1457 int nHeight = pindexPrev->nHeight+1;
1459 // Check proof of work
1460 if (nBits != GetNextWorkRequired(pindexPrev))
1461 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1463 // Check timestamp against prev
1464 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1465 return error("AcceptBlock() : block's timestamp is too early");
1467 // Check that all transactions are finalized
1468 BOOST_FOREACH(const CTransaction& tx, vtx)
1469 if (!tx.IsFinal(nHeight, GetBlockTime()))
1470 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1472 // Check that the block chain matches the known block chain up to a checkpoint
1473 if (!Checkpoints::CheckBlock(nHeight, hash))
1474 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1476 // Write block to history file
1477 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1478 return error("AcceptBlock() : out of disk space");
1479 unsigned int nFile = -1;
1480 unsigned int nBlockPos = 0;
1481 if (!WriteToDisk(nFile, nBlockPos))
1482 return error("AcceptBlock() : WriteToDisk failed");
1483 if (!AddToBlockIndex(nFile, nBlockPos))
1484 return error("AcceptBlock() : AddToBlockIndex failed");
1486 // Relay inventory, but don't relay old inventory during initial block download
1487 if (hashBestChain == hash)
1488 CRITICAL_BLOCK(cs_vNodes)
1489 BOOST_FOREACH(CNode* pnode, vNodes)
1490 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1491 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1496 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1498 // Check for duplicate
1499 uint256 hash = pblock->GetHash();
1500 if (mapBlockIndex.count(hash))
1501 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1502 if (mapOrphanBlocks.count(hash))
1503 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1505 // Preliminary checks
1506 if (!pblock->CheckBlock())
1507 return error("ProcessBlock() : CheckBlock FAILED");
1509 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1510 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1512 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1513 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1516 pfrom->Misbehaving(100);
1517 return error("ProcessBlock() : block with timestamp before last checkpoint");
1520 bnNewBlock.SetCompact(pblock->nBits);
1522 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1523 if (bnNewBlock > bnRequired)
1525 pfrom->Misbehaving(100);
1526 return error("ProcessBlock() : block with too little proof-of-work");
1531 // If don't already have its previous block, shunt it off to holding area until we get it
1532 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1534 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1535 CBlock* pblock2 = new CBlock(*pblock);
1536 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1537 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1539 // Ask this guy to fill in what we're missing
1541 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1546 if (!pblock->AcceptBlock())
1547 return error("ProcessBlock() : AcceptBlock FAILED");
1549 // Recursively process any orphan blocks that depended on this one
1550 vector<uint256> vWorkQueue;
1551 vWorkQueue.push_back(hash);
1552 for (int i = 0; i < vWorkQueue.size(); i++)
1554 uint256 hashPrev = vWorkQueue[i];
1555 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1556 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1559 CBlock* pblockOrphan = (*mi).second;
1560 if (pblockOrphan->AcceptBlock())
1561 vWorkQueue.push_back(pblockOrphan->GetHash());
1562 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1563 delete pblockOrphan;
1565 mapOrphanBlocksByPrev.erase(hashPrev);
1568 printf("ProcessBlock: ACCEPTED\n");
1579 bool CheckDiskSpace(uint64 nAdditionalBytes)
1581 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1583 // Check for 15MB because database could create another 10MB log file at any time
1584 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1587 string strMessage = _("Warning: Disk space is low ");
1588 strMiscWarning = strMessage;
1589 printf("*** %s\n", strMessage.c_str());
1590 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1591 CreateThread(Shutdown, NULL);
1597 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1601 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1604 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1606 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1615 static unsigned int nCurrentBlockFile = 1;
1617 FILE* AppendBlockFile(unsigned int& nFileRet)
1622 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1625 if (fseek(file, 0, SEEK_END) != 0)
1627 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1628 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1630 nFileRet = nCurrentBlockFile;
1634 nCurrentBlockFile++;
1638 bool LoadBlockIndex(bool fAllowNew)
1642 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1643 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1644 pchMessageStart[0] = 0xfa;
1645 pchMessageStart[1] = 0xbf;
1646 pchMessageStart[2] = 0xb5;
1647 pchMessageStart[3] = 0xda;
1654 if (!txdb.LoadBlockIndex())
1659 // Init with genesis block
1661 if (mapBlockIndex.empty())
1667 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1668 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1669 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1670 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1671 // vMerkleTree: 4a5e1e
1674 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1676 txNew.vin.resize(1);
1677 txNew.vout.resize(1);
1678 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1679 txNew.vout[0].nValue = 50 * COIN;
1680 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1682 block.vtx.push_back(txNew);
1683 block.hashPrevBlock = 0;
1684 block.hashMerkleRoot = block.BuildMerkleTree();
1686 block.nTime = 1231006505;
1687 block.nBits = 0x1d00ffff;
1688 block.nNonce = 2083236893;
1692 block.nTime = 1296688602;
1693 block.nBits = 0x1d07fff8;
1694 block.nNonce = 384568319;
1698 printf("%s\n", block.GetHash().ToString().c_str());
1699 printf("%s\n", hashGenesisBlock.ToString().c_str());
1700 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1701 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1703 assert(block.GetHash() == hashGenesisBlock);
1705 // Start new block file
1707 unsigned int nBlockPos;
1708 if (!block.WriteToDisk(nFile, nBlockPos))
1709 return error("LoadBlockIndex() : writing genesis block to disk failed");
1710 if (!block.AddToBlockIndex(nFile, nBlockPos))
1711 return error("LoadBlockIndex() : genesis block not accepted");
1719 void PrintBlockTree()
1721 // precompute tree structure
1722 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1723 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1725 CBlockIndex* pindex = (*mi).second;
1726 mapNext[pindex->pprev].push_back(pindex);
1728 //while (rand() % 3 == 0)
1729 // mapNext[pindex->pprev].push_back(pindex);
1732 vector<pair<int, CBlockIndex*> > vStack;
1733 vStack.push_back(make_pair(0, pindexGenesisBlock));
1736 while (!vStack.empty())
1738 int nCol = vStack.back().first;
1739 CBlockIndex* pindex = vStack.back().second;
1742 // print split or gap
1743 if (nCol > nPrevCol)
1745 for (int i = 0; i < nCol-1; i++)
1749 else if (nCol < nPrevCol)
1751 for (int i = 0; i < nCol; i++)
1758 for (int i = 0; i < nCol; i++)
1763 block.ReadFromDisk(pindex);
1764 printf("%d (%u,%u) %s %s tx %d",
1768 block.GetHash().ToString().substr(0,20).c_str(),
1769 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1772 PrintWallets(block);
1774 // put the main timechain first
1775 vector<CBlockIndex*>& vNext = mapNext[pindex];
1776 for (int i = 0; i < vNext.size(); i++)
1778 if (vNext[i]->pnext)
1780 swap(vNext[0], vNext[i]);
1786 for (int i = 0; i < vNext.size(); i++)
1787 vStack.push_back(make_pair(nCol+i, vNext[i]));
1800 //////////////////////////////////////////////////////////////////////////////
1805 map<uint256, CAlert> mapAlerts;
1806 CCriticalSection cs_mapAlerts;
1808 string GetWarnings(string strFor)
1811 string strStatusBar;
1813 if (GetBoolArg("-testsafemode"))
1816 // Misc warnings like out of disk space and clock is wrong
1817 if (strMiscWarning != "")
1820 strStatusBar = strMiscWarning;
1823 // Longer invalid proof-of-work chain
1824 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1827 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1831 CRITICAL_BLOCK(cs_mapAlerts)
1833 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1835 const CAlert& alert = item.second;
1836 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1838 nPriority = alert.nPriority;
1839 strStatusBar = alert.strStatusBar;
1844 if (strFor == "statusbar")
1845 return strStatusBar;
1846 else if (strFor == "rpc")
1848 assert(!"GetWarnings() : invalid parameter");
1852 bool CAlert::ProcessAlert()
1854 if (!CheckSignature())
1859 CRITICAL_BLOCK(cs_mapAlerts)
1861 // Cancel previous alerts
1862 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1864 const CAlert& alert = (*mi).second;
1867 printf("cancelling alert %d\n", alert.nID);
1868 mapAlerts.erase(mi++);
1870 else if (!alert.IsInEffect())
1872 printf("expiring alert %d\n", alert.nID);
1873 mapAlerts.erase(mi++);
1879 // Check if this alert has been cancelled
1880 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1882 const CAlert& alert = item.second;
1883 if (alert.Cancels(*this))
1885 printf("alert already cancelled by %d\n", alert.nID);
1891 mapAlerts.insert(make_pair(GetHash(), *this));
1894 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1906 //////////////////////////////////////////////////////////////////////////////
1912 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1916 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1917 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1919 // Don't know what it is, just say we already got one
1926 // The message start string is designed to be unlikely to occur in normal data.
1927 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1928 // a large 4-byte int at any alignment.
1929 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1932 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1934 static map<CService, vector<unsigned char> > mapReuseKey;
1935 RandAddSeedPerfmon();
1937 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1938 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1940 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1942 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1950 if (strCommand == "version")
1952 // Each connection can only send one version message
1953 if (pfrom->nVersion != 0)
1955 pfrom->Misbehaving(1);
1963 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1964 if (pfrom->nVersion == 10300)
1965 pfrom->nVersion = 300;
1966 if (pfrom->nVersion >= 106 && !vRecv.empty())
1967 vRecv >> addrFrom >> nNonce;
1968 if (pfrom->nVersion >= 106 && !vRecv.empty())
1969 vRecv >> pfrom->strSubVer;
1970 if (pfrom->nVersion >= 209 && !vRecv.empty())
1971 vRecv >> pfrom->nStartingHeight;
1973 if (pfrom->nVersion == 0)
1976 // Disconnect if we connected to ourself
1977 if (nNonce == nLocalHostNonce && nNonce > 1)
1979 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1980 pfrom->fDisconnect = true;
1984 // Be shy and don't send version until we hear
1985 if (pfrom->fInbound)
1986 pfrom->PushVersion();
1988 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1990 AddTimeData(pfrom->addr, nTime);
1993 if (pfrom->nVersion >= 209)
1994 pfrom->PushMessage("verack");
1995 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1996 if (pfrom->nVersion < 209)
1997 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1999 if (!pfrom->fInbound)
2001 // Advertise our address
2002 if (addrLocalHost.IsRoutable() && !fUseProxy)
2004 CAddress addr(addrLocalHost);
2005 addr.nTime = GetAdjustedTime();
2006 pfrom->PushAddress(addr);
2009 // Get recent addresses
2010 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2012 pfrom->PushMessage("getaddr");
2013 pfrom->fGetAddr = true;
2017 // Ask the first connected node for block updates
2018 static int nAskedForBlocks = 0;
2019 if (!pfrom->fClient &&
2020 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2021 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2024 pfrom->PushGetBlocks(pindexBest, uint256(0));
2028 CRITICAL_BLOCK(cs_mapAlerts)
2029 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2030 item.second.RelayTo(pfrom);
2032 pfrom->fSuccessfullyConnected = true;
2034 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2036 cPeerBlockCounts.input(pfrom->nStartingHeight);
2040 else if (pfrom->nVersion == 0)
2042 // Must have a version message before anything else
2043 pfrom->Misbehaving(1);
2048 else if (strCommand == "verack")
2050 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2054 else if (strCommand == "addr")
2056 vector<CAddress> vAddr;
2059 // Don't want addr from older versions unless seeding
2060 if (pfrom->nVersion < 209)
2062 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2064 if (vAddr.size() > 1000)
2066 pfrom->Misbehaving(20);
2067 return error("message addr size() = %d", vAddr.size());
2070 // Store the new addresses
2073 int64 nNow = GetAdjustedTime();
2074 int64 nSince = nNow - 10 * 60;
2075 BOOST_FOREACH(CAddress& addr, vAddr)
2079 // ignore IPv6 for now, since it isn't implemented anyway
2082 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2083 addr.nTime = nNow - 5 * 24 * 60 * 60;
2084 AddAddress(addr, 2 * 60 * 60, &addrDB);
2085 pfrom->AddAddressKnown(addr);
2086 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2088 // Relay to a limited number of other nodes
2089 CRITICAL_BLOCK(cs_vNodes)
2091 // Use deterministic randomness to send to the same nodes for 24 hours
2092 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2093 static uint256 hashSalt;
2095 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2096 int64 hashAddr = addr.GetHash();
2097 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2098 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2099 multimap<uint256, CNode*> mapMix;
2100 BOOST_FOREACH(CNode* pnode, vNodes)
2102 if (pnode->nVersion < 31402)
2104 unsigned int nPointer;
2105 memcpy(&nPointer, &pnode, sizeof(nPointer));
2106 uint256 hashKey = hashRand ^ nPointer;
2107 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2108 mapMix.insert(make_pair(hashKey, pnode));
2110 int nRelayNodes = 2;
2111 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2112 ((*mi).second)->PushAddress(addr);
2116 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2117 if (vAddr.size() < 1000)
2118 pfrom->fGetAddr = false;
2122 else if (strCommand == "inv")
2126 if (vInv.size() > 50000)
2128 pfrom->Misbehaving(20);
2129 return error("message inv size() = %d", vInv.size());
2133 BOOST_FOREACH(const CInv& inv, vInv)
2137 pfrom->AddInventoryKnown(inv);
2139 bool fAlreadyHave = AlreadyHave(txdb, inv);
2141 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2145 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2146 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2148 // Track requests for our stuff
2149 Inventory(inv.hash);
2154 else if (strCommand == "getdata")
2158 if (vInv.size() > 50000)
2160 pfrom->Misbehaving(20);
2161 return error("message getdata size() = %d", vInv.size());
2164 BOOST_FOREACH(const CInv& inv, vInv)
2168 printf("received getdata for: %s\n", inv.ToString().c_str());
2170 if (inv.type == MSG_BLOCK)
2172 // Send block from disk
2173 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2174 if (mi != mapBlockIndex.end())
2177 block.ReadFromDisk((*mi).second);
2178 pfrom->PushMessage("block", block);
2180 // Trigger them to send a getblocks request for the next batch of inventory
2181 if (inv.hash == pfrom->hashContinue)
2183 // Bypass PushInventory, this must send even if redundant,
2184 // and we want it right after the last block so they don't
2185 // wait for other stuff first.
2187 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2188 pfrom->PushMessage("inv", vInv);
2189 pfrom->hashContinue = 0;
2193 else if (inv.IsKnownType())
2195 // Send stream from relay memory
2196 CRITICAL_BLOCK(cs_mapRelay)
2198 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2199 if (mi != mapRelay.end())
2200 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2204 // Track requests for our stuff
2205 Inventory(inv.hash);
2210 else if (strCommand == "getblocks")
2212 CBlockLocator locator;
2214 vRecv >> locator >> hashStop;
2216 // Find the last block the caller has in the main chain
2217 CBlockIndex* pindex = locator.GetBlockIndex();
2219 // Send the rest of the chain
2221 pindex = pindex->pnext;
2222 int nLimit = 500 + locator.GetDistanceBack();
2223 unsigned int nBytes = 0;
2224 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2225 for (; pindex; pindex = pindex->pnext)
2227 if (pindex->GetBlockHash() == hashStop)
2229 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2232 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2234 block.ReadFromDisk(pindex, true);
2235 nBytes += block.GetSerializeSize(SER_NETWORK);
2236 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2238 // When this block is requested, we'll send an inv that'll make them
2239 // getblocks the next batch of inventory.
2240 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2241 pfrom->hashContinue = pindex->GetBlockHash();
2248 else if (strCommand == "getheaders")
2250 CBlockLocator locator;
2252 vRecv >> locator >> hashStop;
2254 CBlockIndex* pindex = NULL;
2255 if (locator.IsNull())
2257 // If locator is null, return the hashStop block
2258 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2259 if (mi == mapBlockIndex.end())
2261 pindex = (*mi).second;
2265 // Find the last block the caller has in the main chain
2266 pindex = locator.GetBlockIndex();
2268 pindex = pindex->pnext;
2271 vector<CBlock> vHeaders;
2272 int nLimit = 2000 + locator.GetDistanceBack();
2273 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2274 for (; pindex; pindex = pindex->pnext)
2276 vHeaders.push_back(pindex->GetBlockHeader());
2277 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2280 pfrom->PushMessage("headers", vHeaders);
2284 else if (strCommand == "tx")
2286 vector<uint256> vWorkQueue;
2287 CDataStream vMsg(vRecv);
2291 CInv inv(MSG_TX, tx.GetHash());
2292 pfrom->AddInventoryKnown(inv);
2294 bool fMissingInputs = false;
2295 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2297 SyncWithWallets(tx, NULL, true);
2298 RelayMessage(inv, vMsg);
2299 mapAlreadyAskedFor.erase(inv);
2300 vWorkQueue.push_back(inv.hash);
2302 // Recursively process any orphan transactions that depended on this one
2303 for (int i = 0; i < vWorkQueue.size(); i++)
2305 uint256 hashPrev = vWorkQueue[i];
2306 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2307 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2310 const CDataStream& vMsg = *((*mi).second);
2312 CDataStream(vMsg) >> tx;
2313 CInv inv(MSG_TX, tx.GetHash());
2315 if (tx.AcceptToMemoryPool(true))
2317 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2318 SyncWithWallets(tx, NULL, true);
2319 RelayMessage(inv, vMsg);
2320 mapAlreadyAskedFor.erase(inv);
2321 vWorkQueue.push_back(inv.hash);
2326 BOOST_FOREACH(uint256 hash, vWorkQueue)
2327 EraseOrphanTx(hash);
2329 else if (fMissingInputs)
2331 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2334 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2338 else if (strCommand == "block")
2343 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2346 CInv inv(MSG_BLOCK, block.GetHash());
2347 pfrom->AddInventoryKnown(inv);
2349 if (ProcessBlock(pfrom, &block))
2350 mapAlreadyAskedFor.erase(inv);
2351 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2355 else if (strCommand == "getaddr")
2357 // Nodes rebroadcast an addr every 24 hours
2358 pfrom->vAddrToSend.clear();
2359 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2360 CRITICAL_BLOCK(cs_mapAddresses)
2362 unsigned int nCount = 0;
2363 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2365 const CAddress& addr = item.second;
2366 if (addr.nTime > nSince)
2369 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2371 const CAddress& addr = item.second;
2372 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2373 pfrom->PushAddress(addr);
2379 else if (strCommand == "checkorder")
2384 if (!GetBoolArg("-allowreceivebyip"))
2386 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2393 /// we have a chance to check the order here
2395 // Keep giving the same key to the same ip until they use it
2396 if (!mapReuseKey.count(pfrom->addr))
2397 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2399 // Send back approval of order and pubkey to use
2400 CScript scriptPubKey;
2401 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2402 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2406 else if (strCommand == "reply")
2411 CRequestTracker tracker;
2412 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2414 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2415 if (mi != pfrom->mapRequests.end())
2417 tracker = (*mi).second;
2418 pfrom->mapRequests.erase(mi);
2421 if (!tracker.IsNull())
2422 tracker.fn(tracker.param1, vRecv);
2426 else if (strCommand == "ping")
2431 else if (strCommand == "alert")
2436 if (alert.ProcessAlert())
2439 pfrom->setKnown.insert(alert.GetHash());
2440 CRITICAL_BLOCK(cs_vNodes)
2441 BOOST_FOREACH(CNode* pnode, vNodes)
2442 alert.RelayTo(pnode);
2449 // Ignore unknown commands for extensibility
2453 // Update the last seen time for this node's address
2454 if (pfrom->fNetworkNode)
2455 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2456 AddressCurrentlyConnected(pfrom->addr);
2462 bool ProcessMessages(CNode* pfrom)
2464 CDataStream& vRecv = pfrom->vRecv;
2468 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2472 // (4) message start
2481 // Scan for message start
2482 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2483 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2484 if (vRecv.end() - pstart < nHeaderSize)
2486 if (vRecv.size() > nHeaderSize)
2488 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2489 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2493 if (pstart - vRecv.begin() > 0)
2494 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2495 vRecv.erase(vRecv.begin(), pstart);
2498 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2503 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2506 string strCommand = hdr.GetCommand();
2509 unsigned int nMessageSize = hdr.nMessageSize;
2510 if (nMessageSize > MAX_SIZE)
2512 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2515 if (nMessageSize > vRecv.size())
2517 // Rewind and wait for rest of message
2518 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2523 if (vRecv.GetVersion() >= 209)
2525 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2526 unsigned int nChecksum = 0;
2527 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2528 if (nChecksum != hdr.nChecksum)
2530 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2531 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2536 // Copy message to its own buffer
2537 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2538 vRecv.ignore(nMessageSize);
2544 CRITICAL_BLOCK(cs_main)
2545 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2549 catch (std::ios_base::failure& e)
2551 if (strstr(e.what(), "end of data"))
2553 // Allow exceptions from underlength message on vRecv
2554 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());
2556 else if (strstr(e.what(), "size too large"))
2558 // Allow exceptions from overlong size
2559 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2563 PrintExceptionContinue(&e, "ProcessMessage()");
2566 catch (std::exception& e) {
2567 PrintExceptionContinue(&e, "ProcessMessage()");
2569 PrintExceptionContinue(NULL, "ProcessMessage()");
2573 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2581 bool SendMessages(CNode* pto, bool fSendTrickle)
2583 CRITICAL_BLOCK(cs_main)
2585 // Don't send anything until we get their version message
2586 if (pto->nVersion == 0)
2590 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2591 pto->PushMessage("ping");
2593 // Resend wallet transactions that haven't gotten in a block yet
2594 ResendWalletTransactions();
2596 // Address refresh broadcast
2597 static int64 nLastRebroadcast;
2598 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2600 nLastRebroadcast = GetTime();
2601 CRITICAL_BLOCK(cs_vNodes)
2603 BOOST_FOREACH(CNode* pnode, vNodes)
2605 // Periodically clear setAddrKnown to allow refresh broadcasts
2606 pnode->setAddrKnown.clear();
2608 // Rebroadcast our address
2609 if (addrLocalHost.IsRoutable() && !fUseProxy)
2611 CAddress addr(addrLocalHost);
2612 addr.nTime = GetAdjustedTime();
2613 pnode->PushAddress(addr);
2619 // Clear out old addresses periodically so it's not too much work at once
2620 static int64 nLastClear;
2621 if (nLastClear == 0)
2622 nLastClear = GetTime();
2623 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2625 nLastClear = GetTime();
2626 CRITICAL_BLOCK(cs_mapAddresses)
2629 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2630 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2631 mi != mapAddresses.end();)
2633 const CAddress& addr = (*mi).second;
2634 if (addr.nTime < nSince)
2636 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2638 addrdb.EraseAddress(addr);
2639 mapAddresses.erase(mi++);
2653 vector<CAddress> vAddr;
2654 vAddr.reserve(pto->vAddrToSend.size());
2655 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2657 // returns true if wasn't already contained in the set
2658 if (pto->setAddrKnown.insert(addr).second)
2660 vAddr.push_back(addr);
2661 // receiver rejects addr messages larger than 1000
2662 if (vAddr.size() >= 1000)
2664 pto->PushMessage("addr", vAddr);
2669 pto->vAddrToSend.clear();
2671 pto->PushMessage("addr", vAddr);
2676 // Message: inventory
2679 vector<CInv> vInvWait;
2680 CRITICAL_BLOCK(pto->cs_inventory)
2682 vInv.reserve(pto->vInventoryToSend.size());
2683 vInvWait.reserve(pto->vInventoryToSend.size());
2684 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2686 if (pto->setInventoryKnown.count(inv))
2689 // trickle out tx inv to protect privacy
2690 if (inv.type == MSG_TX && !fSendTrickle)
2692 // 1/4 of tx invs blast to all immediately
2693 static uint256 hashSalt;
2695 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2696 uint256 hashRand = inv.hash ^ hashSalt;
2697 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2698 bool fTrickleWait = ((hashRand & 3) != 0);
2700 // always trickle our own transactions
2704 if (GetTransaction(inv.hash, wtx))
2706 fTrickleWait = true;
2711 vInvWait.push_back(inv);
2716 // returns true if wasn't already contained in the set
2717 if (pto->setInventoryKnown.insert(inv).second)
2719 vInv.push_back(inv);
2720 if (vInv.size() >= 1000)
2722 pto->PushMessage("inv", vInv);
2727 pto->vInventoryToSend = vInvWait;
2730 pto->PushMessage("inv", vInv);
2736 vector<CInv> vGetData;
2737 int64 nNow = GetTime() * 1000000;
2739 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2741 const CInv& inv = (*pto->mapAskFor.begin()).second;
2742 if (!AlreadyHave(txdb, inv))
2744 printf("sending getdata: %s\n", inv.ToString().c_str());
2745 vGetData.push_back(inv);
2746 if (vGetData.size() >= 1000)
2748 pto->PushMessage("getdata", vGetData);
2752 mapAlreadyAskedFor[inv] = nNow;
2753 pto->mapAskFor.erase(pto->mapAskFor.begin());
2755 if (!vGetData.empty())
2756 pto->PushMessage("getdata", vGetData);
2775 //////////////////////////////////////////////////////////////////////////////
2780 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2782 unsigned char* pdata = (unsigned char*)pbuffer;
2783 unsigned int blocks = 1 + ((len + 8) / 64);
2784 unsigned char* pend = pdata + 64 * blocks;
2785 memset(pdata + len, 0, 64 * blocks - len);
2787 unsigned int bits = len * 8;
2788 pend[-1] = (bits >> 0) & 0xff;
2789 pend[-2] = (bits >> 8) & 0xff;
2790 pend[-3] = (bits >> 16) & 0xff;
2791 pend[-4] = (bits >> 24) & 0xff;
2795 static const unsigned int pSHA256InitState[8] =
2796 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2798 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2801 unsigned char data[64];
2805 for (int i = 0; i < 16; i++)
2806 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2808 for (int i = 0; i < 8; i++)
2809 ctx.h[i] = ((uint32_t*)pinit)[i];
2811 SHA256_Update(&ctx, data, sizeof(data));
2812 for (int i = 0; i < 8; i++)
2813 ((uint32_t*)pstate)[i] = ctx.h[i];
2817 // ScanHash scans nonces looking for a hash with at least some zero bits.
2818 // It operates on big endian data. Caller does the byte reversing.
2819 // All input buffers are 16-byte aligned. nNonce is usually preserved
2820 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2821 // the block is rebuilt and nNonce starts over at zero.
2823 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2825 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2829 // Hash pdata using pmidstate as the starting state into
2830 // preformatted buffer phash1, then hash phash1 into phash
2832 SHA256Transform(phash1, pdata, pmidstate);
2833 SHA256Transform(phash, phash1, pSHA256InitState);
2835 // Return the nonce if the hash has at least some zero bits,
2836 // caller will check if it has enough to reach the target
2837 if (((unsigned short*)phash)[14] == 0)
2840 // If nothing found after trying for a while, return -1
2841 if ((nNonce & 0xffff) == 0)
2843 nHashesDone = 0xffff+1;
2849 // Some explaining would be appreciated
2854 set<uint256> setDependsOn;
2857 COrphan(CTransaction* ptxIn)
2865 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2866 BOOST_FOREACH(uint256 hash, setDependsOn)
2867 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2872 CBlock* CreateNewBlock(CReserveKey& reservekey)
2874 CBlockIndex* pindexPrev = pindexBest;
2877 auto_ptr<CBlock> pblock(new CBlock());
2881 // Create coinbase tx
2883 txNew.vin.resize(1);
2884 txNew.vin[0].prevout.SetNull();
2885 txNew.vout.resize(1);
2886 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2888 // Add our coinbase tx as first transaction
2889 pblock->vtx.push_back(txNew);
2891 // Collect memory pool transactions into the block
2893 CRITICAL_BLOCK(cs_main)
2894 CRITICAL_BLOCK(cs_mapTransactions)
2898 // Priority order to process transactions
2899 list<COrphan> vOrphan; // list memory doesn't move
2900 map<uint256, vector<COrphan*> > mapDependers;
2901 multimap<double, CTransaction*> mapPriority;
2902 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2904 CTransaction& tx = (*mi).second;
2905 if (tx.IsCoinBase() || !tx.IsFinal())
2908 COrphan* porphan = NULL;
2909 double dPriority = 0;
2910 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2912 // Read prev transaction
2913 CTransaction txPrev;
2915 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2917 // Has to wait for dependencies
2920 // Use list for automatic deletion
2921 vOrphan.push_back(COrphan(&tx));
2922 porphan = &vOrphan.back();
2924 mapDependers[txin.prevout.hash].push_back(porphan);
2925 porphan->setDependsOn.insert(txin.prevout.hash);
2928 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2930 // Read block header
2931 int nConf = txindex.GetDepthInMainChain();
2933 dPriority += (double)nValueIn * nConf;
2935 if (fDebug && GetBoolArg("-printpriority"))
2936 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2939 // Priority is sum(valuein * age) / txsize
2940 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2943 porphan->dPriority = dPriority;
2945 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2947 if (fDebug && GetBoolArg("-printpriority"))
2949 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2956 // Collect transactions into block
2957 map<uint256, CTxIndex> mapTestPool;
2958 uint64 nBlockSize = 1000;
2959 int nBlockSigOps = 100;
2960 while (!mapPriority.empty())
2962 // Take highest priority transaction off priority queue
2963 double dPriority = -(*mapPriority.begin()).first;
2964 CTransaction& tx = *(*mapPriority.begin()).second;
2965 mapPriority.erase(mapPriority.begin());
2968 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2969 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2972 // Transaction fee required depends on block size
2973 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2974 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
2976 // Connecting shouldn't fail due to dependency on other memory pool transactions
2977 // because we're already processing them in order of dependency
2978 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2979 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
2980 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
2983 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
2985 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2987 swap(mapTestPool, mapTestPoolTmp);
2990 pblock->vtx.push_back(tx);
2991 nBlockSize += nTxSize;
2992 nBlockSigOps += nTxSigOps;
2994 // Add transactions that depend on this one to the priority queue
2995 uint256 hash = tx.GetHash();
2996 if (mapDependers.count(hash))
2998 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3000 if (!porphan->setDependsOn.empty())
3002 porphan->setDependsOn.erase(hash);
3003 if (porphan->setDependsOn.empty())
3004 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3010 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3013 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3014 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3015 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3016 pblock->nBits = GetNextWorkRequired(pindexPrev);
3019 return pblock.release();
3023 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3025 // Update nExtraNonce
3026 static uint256 hashPrevBlock;
3027 if (hashPrevBlock != pblock->hashPrevBlock)
3030 hashPrevBlock = pblock->hashPrevBlock;
3033 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3035 // Put "OP_EVAL" in the coinbase so everybody can tell when
3036 // a majority of miners support it
3037 const char* pOpEvalName = GetOpName(OP_EVAL);
3038 pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
3039 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3041 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3045 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3048 // Prebuild hash buffers
3055 uint256 hashPrevBlock;
3056 uint256 hashMerkleRoot;
3059 unsigned int nNonce;
3062 unsigned char pchPadding0[64];
3064 unsigned char pchPadding1[64];
3067 memset(&tmp, 0, sizeof(tmp));
3069 tmp.block.nVersion = pblock->nVersion;
3070 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3071 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3072 tmp.block.nTime = pblock->nTime;
3073 tmp.block.nBits = pblock->nBits;
3074 tmp.block.nNonce = pblock->nNonce;
3076 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3077 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3079 // Byte swap all the input buffer
3080 for (int i = 0; i < sizeof(tmp)/4; i++)
3081 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3083 // Precalc the first half of the first hash, which stays constant
3084 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3086 memcpy(pdata, &tmp.block, 128);
3087 memcpy(phash1, &tmp.hash1, 64);
3091 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3093 uint256 hash = pblock->GetHash();
3094 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3096 if (hash > hashTarget)
3100 printf("BitcoinMiner:\n");
3101 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3103 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3104 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3107 CRITICAL_BLOCK(cs_main)
3109 if (pblock->hashPrevBlock != hashBestChain)
3110 return error("BitcoinMiner : generated block is stale");
3112 // Remove key from key pool
3113 reservekey.KeepKey();
3115 // Track how many getdata requests this block gets
3116 CRITICAL_BLOCK(wallet.cs_wallet)
3117 wallet.mapRequestCount[pblock->GetHash()] = 0;
3119 // Process this block the same as if we had received it from another node
3120 if (!ProcessBlock(NULL, pblock))
3121 return error("BitcoinMiner : ProcessBlock, block not accepted");
3127 void static ThreadBitcoinMiner(void* parg);
3129 void static BitcoinMiner(CWallet *pwallet)
3131 printf("BitcoinMiner started\n");
3132 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3134 // Each thread has its own key and counter
3135 CReserveKey reservekey(pwallet);
3136 unsigned int nExtraNonce = 0;
3138 while (fGenerateBitcoins)
3140 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3144 while (vNodes.empty() || IsInitialBlockDownload())
3149 if (!fGenerateBitcoins)
3157 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3158 CBlockIndex* pindexPrev = pindexBest;
3160 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3163 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3165 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3169 // Prebuild hash buffers
3171 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3172 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3173 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3175 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3177 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3178 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3184 int64 nStart = GetTime();
3185 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3187 uint256& hash = *alignup<16>(hashbuf);
3190 unsigned int nHashesDone = 0;
3191 unsigned int nNonceFound;
3194 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3195 (char*)&hash, nHashesDone);
3197 // Check if something found
3198 if (nNonceFound != -1)
3200 for (int i = 0; i < sizeof(hash)/4; i++)
3201 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3203 if (hash <= hashTarget)
3206 pblock->nNonce = ByteReverse(nNonceFound);
3207 assert(hash == pblock->GetHash());
3209 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3210 CheckWork(pblock.get(), *pwalletMain, reservekey);
3211 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3217 static int64 nHashCounter;
3218 if (nHPSTimerStart == 0)
3220 nHPSTimerStart = GetTimeMillis();
3224 nHashCounter += nHashesDone;
3225 if (GetTimeMillis() - nHPSTimerStart > 4000)
3227 static CCriticalSection cs;
3230 if (GetTimeMillis() - nHPSTimerStart > 4000)
3232 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3233 nHPSTimerStart = GetTimeMillis();
3235 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3236 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3237 static int64 nLogTime;
3238 if (GetTime() - nLogTime > 30 * 60)
3240 nLogTime = GetTime();
3241 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3242 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3248 // Check for stop or if block needs to be rebuilt
3251 if (!fGenerateBitcoins)
3253 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3257 if (nBlockNonce >= 0xffff0000)
3259 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3261 if (pindexPrev != pindexBest)
3264 // Update nTime every few seconds
3265 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3266 nBlockTime = ByteReverse(pblock->nTime);
3271 void static ThreadBitcoinMiner(void* parg)
3273 CWallet* pwallet = (CWallet*)parg;
3276 vnThreadsRunning[3]++;
3277 BitcoinMiner(pwallet);
3278 vnThreadsRunning[3]--;
3280 catch (std::exception& e) {
3281 vnThreadsRunning[3]--;
3282 PrintException(&e, "ThreadBitcoinMiner()");
3284 vnThreadsRunning[3]--;
3285 PrintException(NULL, "ThreadBitcoinMiner()");
3287 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3289 if (vnThreadsRunning[3] == 0)
3291 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3295 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3297 if (fGenerateBitcoins != fGenerate)
3299 fGenerateBitcoins = fGenerate;
3300 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3303 if (fGenerateBitcoins)
3305 int nProcessors = boost::thread::hardware_concurrency();
3306 printf("%d processors\n", nProcessors);
3307 if (nProcessors < 1)
3309 if (fLimitProcessors && nProcessors > nLimitProcessors)
3310 nProcessors = nLimitProcessors;
3311 int nAddThreads = nProcessors - vnThreadsRunning[3];
3312 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3313 for (int i = 0; i < nAddThreads; i++)
3315 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3316 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");