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 2-signature 2-of-3 escrow
254 // in an OP_EVAL, which is 2 ~80-byte signatures, 3
255 // ~65-byte public keys, plus a few script ops.
256 if (txin.scriptSig.size() > 400)
257 return error("nonstandard txin, size %d\n", txin.scriptSig.size());
258 if (!txin.scriptSig.IsPushOnly())
259 return error("nonstandard txin: %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::IsStandardInputs(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;
291 if (!Solver(txPrev.vout[vin[i].prevout.n].scriptPubKey, whichType, vSolutions))
293 if (whichType == TX_SCRIPTHASH)
295 vector<vector<unsigned char> > stack;
297 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0, nUnused))
299 const vector<unsigned char>& subscript = stack.back();
300 if (!::IsStandard(CScript(subscript.begin(), subscript.end())))
310 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
322 // Load the block this tx is in
324 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
326 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
331 // Update the tx's hashBlock
332 hashBlock = pblock->GetHash();
334 // Locate the transaction
335 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
336 if (pblock->vtx[nIndex] == *(CTransaction*)this)
338 if (nIndex == pblock->vtx.size())
340 vMerkleBranch.clear();
342 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
346 // Fill in merkle branch
347 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
350 // Is the tx in a block that's in the main chain
351 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
352 if (mi == mapBlockIndex.end())
354 CBlockIndex* pindex = (*mi).second;
355 if (!pindex || !pindex->IsInMainChain())
358 return pindexBest->nHeight - pindex->nHeight + 1;
367 bool CTransaction::CheckTransaction() const
369 // Basic checks that don't depend on any context
371 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
373 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
375 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
376 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
378 // Check for negative or overflow output values
380 BOOST_FOREACH(const CTxOut& txout, vout)
382 if (txout.nValue < 0)
383 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
384 if (txout.nValue > MAX_MONEY)
385 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
386 nValueOut += txout.nValue;
387 if (!MoneyRange(nValueOut))
388 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
391 // Check for duplicate inputs
392 set<COutPoint> vInOutPoints;
393 BOOST_FOREACH(const CTxIn& txin, vin)
395 if (vInOutPoints.count(txin.prevout))
397 vInOutPoints.insert(txin.prevout);
402 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
403 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
407 BOOST_FOREACH(const CTxIn& txin, vin)
408 if (txin.prevout.IsNull())
409 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
415 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
418 *pfMissingInputs = false;
420 if (!CheckTransaction())
421 return error("AcceptToMemoryPool() : CheckTransaction failed");
423 // Coinbase is only valid in a block, not as a loose transaction
425 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
427 // To help v0.1.5 clients who would see it as a negative number
428 if ((int64)nLockTime > INT_MAX)
429 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
431 // Rather not work on nonstandard transactions (unless -testnet)
432 if (!fTestNet && !IsStandard())
433 return error("AcceptToMemoryPool() : nonstandard transaction type");
435 // Do we already have it?
436 uint256 hash = GetHash();
437 CRITICAL_BLOCK(cs_mapTransactions)
438 if (mapTransactions.count(hash))
441 if (txdb.ContainsTx(hash))
444 // Check for conflicts with in-memory transactions
445 CTransaction* ptxOld = NULL;
446 for (int i = 0; i < vin.size(); i++)
448 COutPoint outpoint = vin[i].prevout;
449 if (mapNextTx.count(outpoint))
451 // Disable replacement feature for now
454 // Allow replacing with a newer version of the same transaction
457 ptxOld = mapNextTx[outpoint].ptx;
458 if (ptxOld->IsFinal())
460 if (!IsNewerThan(*ptxOld))
462 for (int i = 0; i < vin.size(); i++)
464 COutPoint outpoint = vin[i].prevout;
465 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
474 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
475 map<uint256, CTxIndex> mapUnused;
476 if (!FetchInputs(txdb, mapUnused, false, false, mapInputs))
479 *pfMissingInputs = true;
480 return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
483 // Check for non-standard OP_EVALs in inputs
484 if (!IsStandardInputs(mapInputs))
485 return error("AcceptToMemoryPool() : nonstandard transaction input");
487 // Check against previous transactions
490 if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, nSigOps))
493 *pfMissingInputs = true;
494 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
496 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
497 // attacks disallow transactions with more than one SigOp per 65 bytes.
498 // 65 bytes because that is the minimum size of an ECDSA signature
499 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
500 if (nSigOps > nSize / 65 || nSize < 100)
501 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
503 // Don't accept it if it can't get into a block
504 if (nFees < GetMinFee(1000, true, true))
505 return error("AcceptToMemoryPool() : not enough fees");
507 // Continuously rate-limit free transactions
508 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
509 // be annoying or make other's transactions take longer to confirm.
510 if (nFees < MIN_RELAY_TX_FEE)
512 static CCriticalSection cs;
513 static double dFreeCount;
514 static int64 nLastTime;
515 int64 nNow = GetTime();
519 // Use an exponentially decaying ~10-minute window:
520 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
522 // -limitfreerelay unit is thousand-bytes-per-minute
523 // At default rate it would take over a month to fill 1GB
524 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
525 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
527 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
533 // Store transaction in memory
534 CRITICAL_BLOCK(cs_mapTransactions)
538 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
539 ptxOld->RemoveFromMemoryPool();
541 AddToMemoryPoolUnchecked();
544 ///// are we sure this is ok when loading transactions or restoring block txes
545 // If updated, erase old tx from wallet
547 EraseFromWallets(ptxOld->GetHash());
549 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
553 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
556 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
559 bool CTransaction::AddToMemoryPoolUnchecked()
561 // Add to memory pool without checking anything. Don't call this directly,
562 // call AcceptToMemoryPool to properly check the transaction first.
563 CRITICAL_BLOCK(cs_mapTransactions)
565 uint256 hash = GetHash();
566 mapTransactions[hash] = *this;
567 for (int i = 0; i < vin.size(); i++)
568 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
569 nTransactionsUpdated++;
575 bool CTransaction::RemoveFromMemoryPool()
577 // Remove transaction from memory pool
578 CRITICAL_BLOCK(cs_mapTransactions)
580 BOOST_FOREACH(const CTxIn& txin, vin)
581 mapNextTx.erase(txin.prevout);
582 mapTransactions.erase(GetHash());
583 nTransactionsUpdated++;
593 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
595 if (hashBlock == 0 || nIndex == -1)
598 // Find the block it claims to be in
599 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
600 if (mi == mapBlockIndex.end())
602 CBlockIndex* pindex = (*mi).second;
603 if (!pindex || !pindex->IsInMainChain())
606 // Make sure the merkle branch connects to this block
607 if (!fMerkleVerified)
609 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
611 fMerkleVerified = true;
615 return pindexBest->nHeight - pindex->nHeight + 1;
619 int CMerkleTx::GetBlocksToMaturity() const
623 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
627 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
631 if (!IsInMainChain() && !ClientConnectInputs())
633 return CTransaction::AcceptToMemoryPool(txdb, false);
637 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
641 bool CMerkleTx::AcceptToMemoryPool()
644 return AcceptToMemoryPool(txdb);
649 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
651 CRITICAL_BLOCK(cs_mapTransactions)
653 // Add previous supporting transactions first
654 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
656 if (!tx.IsCoinBase())
658 uint256 hash = tx.GetHash();
659 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
660 tx.AcceptToMemoryPool(txdb, fCheckInputs);
663 return AcceptToMemoryPool(txdb, fCheckInputs);
668 bool CWalletTx::AcceptWalletTransaction()
671 return AcceptWalletTransaction(txdb);
674 int CTxIndex::GetDepthInMainChain() const
678 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
680 // Find the block in the index
681 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
682 if (mi == mapBlockIndex.end())
684 CBlockIndex* pindex = (*mi).second;
685 if (!pindex || !pindex->IsInMainChain())
687 return 1 + nBestHeight - pindex->nHeight;
699 //////////////////////////////////////////////////////////////////////////////
701 // CBlock and CBlockIndex
704 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
706 if (!fReadTransactions)
708 *this = pindex->GetBlockHeader();
711 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
713 if (GetHash() != pindex->GetBlockHash())
714 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
718 uint256 static GetOrphanRoot(const CBlock* pblock)
720 // Work back to the first block in the orphan chain
721 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
722 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
723 return pblock->GetHash();
726 int64 static GetBlockValue(int nHeight, int64 nFees)
728 int64 nSubsidy = 50 * COIN;
730 // Subsidy is cut in half every 4 years
731 nSubsidy >>= (nHeight / 210000);
733 return nSubsidy + nFees;
736 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
737 static const int64 nTargetSpacing = 10 * 60;
738 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
741 // minimum amount of work that could possibly be required nTime after
742 // minimum work required was nBase
744 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
747 bnResult.SetCompact(nBase);
748 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
750 // Maximum 400% adjustment...
752 // ... in best-case exactly 4-times-normal target time
753 nTime -= nTargetTimespan*4;
755 if (bnResult > bnProofOfWorkLimit)
756 bnResult = bnProofOfWorkLimit;
757 return bnResult.GetCompact();
760 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
764 if (pindexLast == NULL)
765 return bnProofOfWorkLimit.GetCompact();
767 // Only change once per interval
768 if ((pindexLast->nHeight+1) % nInterval != 0)
769 return pindexLast->nBits;
771 // Go back by what we want to be 14 days worth of blocks
772 const CBlockIndex* pindexFirst = pindexLast;
773 for (int i = 0; pindexFirst && i < nInterval-1; i++)
774 pindexFirst = pindexFirst->pprev;
777 // Limit adjustment step
778 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
779 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
780 if (nActualTimespan < nTargetTimespan/4)
781 nActualTimespan = nTargetTimespan/4;
782 if (nActualTimespan > nTargetTimespan*4)
783 nActualTimespan = nTargetTimespan*4;
787 bnNew.SetCompact(pindexLast->nBits);
788 bnNew *= nActualTimespan;
789 bnNew /= nTargetTimespan;
791 if (bnNew > bnProofOfWorkLimit)
792 bnNew = bnProofOfWorkLimit;
795 printf("GetNextWorkRequired RETARGET\n");
796 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
797 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
798 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
800 return bnNew.GetCompact();
803 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
806 bnTarget.SetCompact(nBits);
809 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
810 return error("CheckProofOfWork() : nBits below minimum work");
812 // Check proof of work matches claimed amount
813 if (hash > bnTarget.getuint256())
814 return error("CheckProofOfWork() : hash doesn't match nBits");
819 // Return maximum amount of blocks that other nodes claim to have
820 int GetNumBlocksOfPeers()
822 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
825 bool IsInitialBlockDownload()
827 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
829 static int64 nLastUpdate;
830 static CBlockIndex* pindexLastBest;
831 if (pindexBest != pindexLastBest)
833 pindexLastBest = pindexBest;
834 nLastUpdate = GetTime();
836 return (GetTime() - nLastUpdate < 10 &&
837 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
840 void static InvalidChainFound(CBlockIndex* pindexNew)
842 if (pindexNew->bnChainWork > bnBestInvalidWork)
844 bnBestInvalidWork = pindexNew->bnChainWork;
845 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
848 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());
849 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
850 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
851 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
864 bool CTransaction::DisconnectInputs(CTxDB& txdb)
866 // Relinquish previous transactions' spent pointers
869 BOOST_FOREACH(const CTxIn& txin, vin)
871 COutPoint prevout = txin.prevout;
873 // Get prev txindex from disk
875 if (!txdb.ReadTxIndex(prevout.hash, txindex))
876 return error("DisconnectInputs() : ReadTxIndex failed");
878 if (prevout.n >= txindex.vSpent.size())
879 return error("DisconnectInputs() : prevout.n out of range");
881 // Mark outpoint as not spent
882 txindex.vSpent[prevout.n].SetNull();
885 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
886 return error("DisconnectInputs() : UpdateTxIndex failed");
890 // Remove transaction from index
891 if (!txdb.EraseTxIndex(*this))
892 return error("DisconnectInputs() : EraseTxPos failed");
898 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
899 bool fBlock, bool fMiner, map<uint256, pair<CTxIndex, CTransaction> >& inputsRet)
902 return true; // Coinbase transactions have no inputs to fetch.
904 for (int i = 0; i < vin.size(); i++)
906 COutPoint prevout = vin[i].prevout;
907 if (inputsRet.count(prevout.hash))
908 continue; // Got it already
911 CTxIndex& txindex = inputsRet[prevout.hash].first;
913 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
915 // Get txindex from current proposed changes
916 txindex = mapTestPool.find(prevout.hash)->second;
920 // Read txindex from txdb
921 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
923 if (!fFound && (fBlock || fMiner))
924 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());
927 CTransaction& txPrev = inputsRet[prevout.hash].second;
928 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
930 // Get prev tx from single transactions in memory
931 CRITICAL_BLOCK(cs_mapTransactions)
933 if (!mapTransactions.count(prevout.hash))
934 return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
935 txPrev = mapTransactions[prevout.hash];
938 txindex.vSpent.resize(txPrev.vout.size());
942 // Get prev tx from disk
943 if (!txPrev.ReadFromDisk(txindex.pos))
944 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 bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
951 map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
952 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee)
954 // Take over previous transactions' spent pointers
955 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
956 // fMiner is true when called from the internal bitcoin miner
957 // ... both are false when called from CTransaction::AcceptToMemoryPool
961 for (int i = 0; i < vin.size(); i++)
963 COutPoint prevout = vin[i].prevout;
964 assert(inputs.count(prevout.hash) > 0);
965 CTxIndex& txindex = inputs[prevout.hash].first;
966 CTransaction& txPrev = inputs[prevout.hash].second;
968 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
969 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()));
971 // If prev is coinbase, check that it's matured
972 if (txPrev.IsCoinBase())
973 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
974 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
975 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
977 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
978 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
979 // still computed and checked, and any change will be caught at the next checkpoint.
980 if (!(fBlock && IsInitialBlockDownload()))
982 if (!VerifySignature(txPrev, *this, i, nSigOpsRet))
983 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
985 // Check for conflicts (double-spend)
986 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
987 // for an attacker to attempt to split the network.
988 if (!txindex.vSpent[prevout.n].IsNull())
989 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());
991 // Check for negative or overflow input values
992 nValueIn += txPrev.vout[prevout.n].nValue;
993 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
994 return DoS(100, error("ConnectInputs() : txin values out of range"));
996 // Mark outpoints as spent
997 txindex.vSpent[prevout.n] = posThisTx;
1000 if (fBlock || fMiner)
1002 mapTestPool[prevout.hash] = txindex;
1006 if (nValueIn < GetValueOut())
1007 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1009 // Tally transaction fees
1010 int64 nTxFee = nValueIn - GetValueOut();
1012 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1013 if (nTxFee < nMinFee)
1016 if (!MoneyRange(nFees))
1017 return DoS(100, error("ConnectInputs() : nFees out of range"));
1022 // Add transaction to changes
1023 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
1027 // Add transaction to test pool
1028 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1035 bool CTransaction::ClientConnectInputs()
1040 // Take over previous transactions' spent pointers
1041 CRITICAL_BLOCK(cs_mapTransactions)
1044 for (int i = 0; i < vin.size(); i++)
1046 // Get prev tx from single transactions in memory
1047 COutPoint prevout = vin[i].prevout;
1048 if (!mapTransactions.count(prevout.hash))
1050 CTransaction& txPrev = mapTransactions[prevout.hash];
1052 if (prevout.n >= txPrev.vout.size())
1057 if (!VerifySignature(txPrev, *this, i, nUnused))
1058 return error("ConnectInputs() : VerifySignature failed");
1060 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1061 ///// this has to go away now that posNext is gone
1062 // // Check for conflicts
1063 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1064 // return error("ConnectInputs() : prev tx already used");
1066 // // Flag outpoints as used
1067 // txPrev.vout[prevout.n].posNext = posThisTx;
1069 nValueIn += txPrev.vout[prevout.n].nValue;
1071 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1072 return error("ClientConnectInputs() : txin values out of range");
1074 if (GetValueOut() > nValueIn)
1084 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1086 // Disconnect in reverse order
1087 for (int i = vtx.size()-1; i >= 0; i--)
1088 if (!vtx[i].DisconnectInputs(txdb))
1091 // Update block index on disk without changing it in memory.
1092 // The memory index structure will be changed after the db commits.
1095 CDiskBlockIndex blockindexPrev(pindex->pprev);
1096 blockindexPrev.hashNext = 0;
1097 if (!txdb.WriteBlockIndex(blockindexPrev))
1098 return error("DisconnectBlock() : WriteBlockIndex failed");
1104 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1106 // Check it again in case a previous version let a bad block in
1110 //// issue here: it doesn't know the version
1111 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1113 map<uint256, CTxIndex> mapQueuedChanges;
1116 BOOST_FOREACH(CTransaction& tx, vtx)
1118 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1119 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1121 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
1122 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
1124 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
1126 if (nSigOps > MAX_BLOCK_SIGOPS)
1127 return DoS(100, error("ConnectBlock() : too many sigops"));
1130 // Write queued txindex changes
1131 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1133 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1134 return error("ConnectBlock() : UpdateTxIndex failed");
1137 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1140 // Update block index on disk without changing it in memory.
1141 // The memory index structure will be changed after the db commits.
1144 CDiskBlockIndex blockindexPrev(pindex->pprev);
1145 blockindexPrev.hashNext = pindex->GetBlockHash();
1146 if (!txdb.WriteBlockIndex(blockindexPrev))
1147 return error("ConnectBlock() : WriteBlockIndex failed");
1150 // Watch for transactions paying to me
1151 BOOST_FOREACH(CTransaction& tx, vtx)
1152 SyncWithWallets(tx, this, true);
1157 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1159 printf("REORGANIZE\n");
1162 CBlockIndex* pfork = pindexBest;
1163 CBlockIndex* plonger = pindexNew;
1164 while (pfork != plonger)
1166 while (plonger->nHeight > pfork->nHeight)
1167 if (!(plonger = plonger->pprev))
1168 return error("Reorganize() : plonger->pprev is null");
1169 if (pfork == plonger)
1171 if (!(pfork = pfork->pprev))
1172 return error("Reorganize() : pfork->pprev is null");
1175 // List of what to disconnect
1176 vector<CBlockIndex*> vDisconnect;
1177 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1178 vDisconnect.push_back(pindex);
1180 // List of what to connect
1181 vector<CBlockIndex*> vConnect;
1182 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1183 vConnect.push_back(pindex);
1184 reverse(vConnect.begin(), vConnect.end());
1186 // Disconnect shorter branch
1187 vector<CTransaction> vResurrect;
1188 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1191 if (!block.ReadFromDisk(pindex))
1192 return error("Reorganize() : ReadFromDisk for disconnect failed");
1193 if (!block.DisconnectBlock(txdb, pindex))
1194 return error("Reorganize() : DisconnectBlock failed");
1196 // Queue memory transactions to resurrect
1197 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1198 if (!tx.IsCoinBase())
1199 vResurrect.push_back(tx);
1202 // Connect longer branch
1203 vector<CTransaction> vDelete;
1204 for (int i = 0; i < vConnect.size(); i++)
1206 CBlockIndex* pindex = vConnect[i];
1208 if (!block.ReadFromDisk(pindex))
1209 return error("Reorganize() : ReadFromDisk for connect failed");
1210 if (!block.ConnectBlock(txdb, pindex))
1214 return error("Reorganize() : ConnectBlock failed");
1217 // Queue memory transactions to delete
1218 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1219 vDelete.push_back(tx);
1221 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1222 return error("Reorganize() : WriteHashBestChain failed");
1224 // Make sure it's successfully written to disk before changing memory structure
1225 if (!txdb.TxnCommit())
1226 return error("Reorganize() : TxnCommit failed");
1228 // Disconnect shorter branch
1229 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1231 pindex->pprev->pnext = NULL;
1233 // Connect longer branch
1234 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1236 pindex->pprev->pnext = pindex;
1238 // Resurrect memory transactions that were in the disconnected branch
1239 BOOST_FOREACH(CTransaction& tx, vResurrect)
1240 tx.AcceptToMemoryPool(txdb, false);
1242 // Delete redundant memory transactions that are in the connected branch
1243 BOOST_FOREACH(CTransaction& tx, vDelete)
1244 tx.RemoveFromMemoryPool();
1250 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1252 uint256 hash = GetHash();
1255 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1257 txdb.WriteHashBestChain(hash);
1258 if (!txdb.TxnCommit())
1259 return error("SetBestChain() : TxnCommit failed");
1260 pindexGenesisBlock = pindexNew;
1262 else if (hashPrevBlock == hashBestChain)
1264 // Adding to current best branch
1265 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1268 InvalidChainFound(pindexNew);
1269 return error("SetBestChain() : ConnectBlock failed");
1271 if (!txdb.TxnCommit())
1272 return error("SetBestChain() : TxnCommit failed");
1274 // Add to current best branch
1275 pindexNew->pprev->pnext = pindexNew;
1277 // Delete redundant memory transactions
1278 BOOST_FOREACH(CTransaction& tx, vtx)
1279 tx.RemoveFromMemoryPool();
1284 if (!Reorganize(txdb, pindexNew))
1287 InvalidChainFound(pindexNew);
1288 return error("SetBestChain() : Reorganize failed");
1292 // Update best block in wallet (so we can detect restored wallets)
1293 if (!IsInitialBlockDownload())
1295 const CBlockLocator locator(pindexNew);
1296 ::SetBestChain(locator);
1300 hashBestChain = hash;
1301 pindexBest = pindexNew;
1302 nBestHeight = pindexBest->nHeight;
1303 bnBestChainWork = pindexNew->bnChainWork;
1304 nTimeBestReceived = GetTime();
1305 nTransactionsUpdated++;
1306 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1312 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1314 // Check for duplicate
1315 uint256 hash = GetHash();
1316 if (mapBlockIndex.count(hash))
1317 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1319 // Construct new block index object
1320 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1322 return error("AddToBlockIndex() : new CBlockIndex failed");
1323 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1324 pindexNew->phashBlock = &((*mi).first);
1325 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1326 if (miPrev != mapBlockIndex.end())
1328 pindexNew->pprev = (*miPrev).second;
1329 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1331 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1335 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1336 if (!txdb.TxnCommit())
1340 if (pindexNew->bnChainWork > bnBestChainWork)
1341 if (!SetBestChain(txdb, pindexNew))
1346 if (pindexNew == pindexBest)
1348 // Notify UI to display prev block's coinbase if it was ours
1349 static uint256 hashPrevBestCoinBase;
1350 UpdatedTransaction(hashPrevBestCoinBase);
1351 hashPrevBestCoinBase = vtx[0].GetHash();
1361 bool CBlock::CheckBlock() const
1363 // These are checks that are independent of context
1364 // that can be verified before saving an orphan block.
1367 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1368 return DoS(100, error("CheckBlock() : size limits failed"));
1370 // Check proof of work matches claimed amount
1371 if (!CheckProofOfWork(GetHash(), nBits))
1372 return DoS(50, error("CheckBlock() : proof of work failed"));
1375 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1376 return error("CheckBlock() : block timestamp too far in the future");
1378 // First transaction must be coinbase, the rest must not be
1379 if (vtx.empty() || !vtx[0].IsCoinBase())
1380 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1381 for (int i = 1; i < vtx.size(); i++)
1382 if (vtx[i].IsCoinBase())
1383 return DoS(100, error("CheckBlock() : more than one coinbase"));
1385 // Check transactions
1386 BOOST_FOREACH(const CTransaction& tx, vtx)
1387 if (!tx.CheckTransaction())
1388 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1390 // This code should be removed when a compatibility-breaking block chain split has passed.
1391 // Compatibility check for old clients that counted sigops differently:
1393 BOOST_FOREACH(const CTransaction& tx, vtx)
1395 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1397 nSigOps += txin.scriptSig.GetSigOpCount();
1399 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1401 nSigOps += txout.scriptPubKey.GetSigOpCount();
1404 if (nSigOps > MAX_BLOCK_SIGOPS)
1405 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1408 if (hashMerkleRoot != BuildMerkleTree())
1409 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1414 bool CBlock::AcceptBlock()
1416 // Check for duplicate
1417 uint256 hash = GetHash();
1418 if (mapBlockIndex.count(hash))
1419 return error("AcceptBlock() : block already in mapBlockIndex");
1421 // Get prev block index
1422 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1423 if (mi == mapBlockIndex.end())
1424 return DoS(10, error("AcceptBlock() : prev block not found"));
1425 CBlockIndex* pindexPrev = (*mi).second;
1426 int nHeight = pindexPrev->nHeight+1;
1428 // Check proof of work
1429 if (nBits != GetNextWorkRequired(pindexPrev))
1430 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1432 // Check timestamp against prev
1433 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1434 return error("AcceptBlock() : block's timestamp is too early");
1436 // Check that all transactions are finalized
1437 BOOST_FOREACH(const CTransaction& tx, vtx)
1438 if (!tx.IsFinal(nHeight, GetBlockTime()))
1439 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1441 // Check that the block chain matches the known block chain up to a checkpoint
1442 if (!Checkpoints::CheckBlock(nHeight, hash))
1443 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1445 // Write block to history file
1446 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1447 return error("AcceptBlock() : out of disk space");
1448 unsigned int nFile = -1;
1449 unsigned int nBlockPos = 0;
1450 if (!WriteToDisk(nFile, nBlockPos))
1451 return error("AcceptBlock() : WriteToDisk failed");
1452 if (!AddToBlockIndex(nFile, nBlockPos))
1453 return error("AcceptBlock() : AddToBlockIndex failed");
1455 // Relay inventory, but don't relay old inventory during initial block download
1456 if (hashBestChain == hash)
1457 CRITICAL_BLOCK(cs_vNodes)
1458 BOOST_FOREACH(CNode* pnode, vNodes)
1459 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1460 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1465 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1467 // Check for duplicate
1468 uint256 hash = pblock->GetHash();
1469 if (mapBlockIndex.count(hash))
1470 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1471 if (mapOrphanBlocks.count(hash))
1472 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1474 // Preliminary checks
1475 if (!pblock->CheckBlock())
1476 return error("ProcessBlock() : CheckBlock FAILED");
1478 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1479 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1481 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1482 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1485 pfrom->Misbehaving(100);
1486 return error("ProcessBlock() : block with timestamp before last checkpoint");
1489 bnNewBlock.SetCompact(pblock->nBits);
1491 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1492 if (bnNewBlock > bnRequired)
1494 pfrom->Misbehaving(100);
1495 return error("ProcessBlock() : block with too little proof-of-work");
1500 // If don't already have its previous block, shunt it off to holding area until we get it
1501 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1503 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1504 CBlock* pblock2 = new CBlock(*pblock);
1505 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1506 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1508 // Ask this guy to fill in what we're missing
1510 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1515 if (!pblock->AcceptBlock())
1516 return error("ProcessBlock() : AcceptBlock FAILED");
1518 // Recursively process any orphan blocks that depended on this one
1519 vector<uint256> vWorkQueue;
1520 vWorkQueue.push_back(hash);
1521 for (int i = 0; i < vWorkQueue.size(); i++)
1523 uint256 hashPrev = vWorkQueue[i];
1524 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1525 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1528 CBlock* pblockOrphan = (*mi).second;
1529 if (pblockOrphan->AcceptBlock())
1530 vWorkQueue.push_back(pblockOrphan->GetHash());
1531 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1532 delete pblockOrphan;
1534 mapOrphanBlocksByPrev.erase(hashPrev);
1537 printf("ProcessBlock: ACCEPTED\n");
1548 bool CheckDiskSpace(uint64 nAdditionalBytes)
1550 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1552 // Check for 15MB because database could create another 10MB log file at any time
1553 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1556 string strMessage = _("Warning: Disk space is low ");
1557 strMiscWarning = strMessage;
1558 printf("*** %s\n", strMessage.c_str());
1559 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1560 CreateThread(Shutdown, NULL);
1566 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1570 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1573 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1575 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1584 static unsigned int nCurrentBlockFile = 1;
1586 FILE* AppendBlockFile(unsigned int& nFileRet)
1591 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1594 if (fseek(file, 0, SEEK_END) != 0)
1596 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1597 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1599 nFileRet = nCurrentBlockFile;
1603 nCurrentBlockFile++;
1607 bool LoadBlockIndex(bool fAllowNew)
1611 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1612 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1613 pchMessageStart[0] = 0xfa;
1614 pchMessageStart[1] = 0xbf;
1615 pchMessageStart[2] = 0xb5;
1616 pchMessageStart[3] = 0xda;
1623 if (!txdb.LoadBlockIndex())
1628 // Init with genesis block
1630 if (mapBlockIndex.empty())
1636 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1637 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1638 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1639 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1640 // vMerkleTree: 4a5e1e
1643 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1645 txNew.vin.resize(1);
1646 txNew.vout.resize(1);
1647 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1648 txNew.vout[0].nValue = 50 * COIN;
1649 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1651 block.vtx.push_back(txNew);
1652 block.hashPrevBlock = 0;
1653 block.hashMerkleRoot = block.BuildMerkleTree();
1655 block.nTime = 1231006505;
1656 block.nBits = 0x1d00ffff;
1657 block.nNonce = 2083236893;
1661 block.nTime = 1296688602;
1662 block.nBits = 0x1d07fff8;
1663 block.nNonce = 384568319;
1667 printf("%s\n", block.GetHash().ToString().c_str());
1668 printf("%s\n", hashGenesisBlock.ToString().c_str());
1669 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1670 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1672 assert(block.GetHash() == hashGenesisBlock);
1674 // Start new block file
1676 unsigned int nBlockPos;
1677 if (!block.WriteToDisk(nFile, nBlockPos))
1678 return error("LoadBlockIndex() : writing genesis block to disk failed");
1679 if (!block.AddToBlockIndex(nFile, nBlockPos))
1680 return error("LoadBlockIndex() : genesis block not accepted");
1688 void PrintBlockTree()
1690 // precompute tree structure
1691 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1692 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1694 CBlockIndex* pindex = (*mi).second;
1695 mapNext[pindex->pprev].push_back(pindex);
1697 //while (rand() % 3 == 0)
1698 // mapNext[pindex->pprev].push_back(pindex);
1701 vector<pair<int, CBlockIndex*> > vStack;
1702 vStack.push_back(make_pair(0, pindexGenesisBlock));
1705 while (!vStack.empty())
1707 int nCol = vStack.back().first;
1708 CBlockIndex* pindex = vStack.back().second;
1711 // print split or gap
1712 if (nCol > nPrevCol)
1714 for (int i = 0; i < nCol-1; i++)
1718 else if (nCol < nPrevCol)
1720 for (int i = 0; i < nCol; i++)
1727 for (int i = 0; i < nCol; i++)
1732 block.ReadFromDisk(pindex);
1733 printf("%d (%u,%u) %s %s tx %d",
1737 block.GetHash().ToString().substr(0,20).c_str(),
1738 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1741 PrintWallets(block);
1743 // put the main timechain first
1744 vector<CBlockIndex*>& vNext = mapNext[pindex];
1745 for (int i = 0; i < vNext.size(); i++)
1747 if (vNext[i]->pnext)
1749 swap(vNext[0], vNext[i]);
1755 for (int i = 0; i < vNext.size(); i++)
1756 vStack.push_back(make_pair(nCol+i, vNext[i]));
1769 //////////////////////////////////////////////////////////////////////////////
1774 map<uint256, CAlert> mapAlerts;
1775 CCriticalSection cs_mapAlerts;
1777 string GetWarnings(string strFor)
1780 string strStatusBar;
1782 if (GetBoolArg("-testsafemode"))
1785 // Misc warnings like out of disk space and clock is wrong
1786 if (strMiscWarning != "")
1789 strStatusBar = strMiscWarning;
1792 // Longer invalid proof-of-work chain
1793 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1796 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1800 CRITICAL_BLOCK(cs_mapAlerts)
1802 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1804 const CAlert& alert = item.second;
1805 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1807 nPriority = alert.nPriority;
1808 strStatusBar = alert.strStatusBar;
1813 if (strFor == "statusbar")
1814 return strStatusBar;
1815 else if (strFor == "rpc")
1817 assert(!"GetWarnings() : invalid parameter");
1821 bool CAlert::ProcessAlert()
1823 if (!CheckSignature())
1828 CRITICAL_BLOCK(cs_mapAlerts)
1830 // Cancel previous alerts
1831 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1833 const CAlert& alert = (*mi).second;
1836 printf("cancelling alert %d\n", alert.nID);
1837 mapAlerts.erase(mi++);
1839 else if (!alert.IsInEffect())
1841 printf("expiring alert %d\n", alert.nID);
1842 mapAlerts.erase(mi++);
1848 // Check if this alert has been cancelled
1849 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1851 const CAlert& alert = item.second;
1852 if (alert.Cancels(*this))
1854 printf("alert already cancelled by %d\n", alert.nID);
1860 mapAlerts.insert(make_pair(GetHash(), *this));
1863 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1875 //////////////////////////////////////////////////////////////////////////////
1881 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1885 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1886 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1888 // Don't know what it is, just say we already got one
1895 // The message start string is designed to be unlikely to occur in normal data.
1896 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1897 // a large 4-byte int at any alignment.
1898 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1901 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1903 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1904 RandAddSeedPerfmon();
1906 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1907 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1909 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1911 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1919 if (strCommand == "version")
1921 // Each connection can only send one version message
1922 if (pfrom->nVersion != 0)
1924 pfrom->Misbehaving(1);
1932 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1933 if (pfrom->nVersion == 10300)
1934 pfrom->nVersion = 300;
1935 if (pfrom->nVersion >= 106 && !vRecv.empty())
1936 vRecv >> addrFrom >> nNonce;
1937 if (pfrom->nVersion >= 106 && !vRecv.empty())
1938 vRecv >> pfrom->strSubVer;
1939 if (pfrom->nVersion >= 209 && !vRecv.empty())
1940 vRecv >> pfrom->nStartingHeight;
1942 if (pfrom->nVersion == 0)
1945 // Disconnect if we connected to ourself
1946 if (nNonce == nLocalHostNonce && nNonce > 1)
1948 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1949 pfrom->fDisconnect = true;
1953 // Be shy and don't send version until we hear
1954 if (pfrom->fInbound)
1955 pfrom->PushVersion();
1957 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1959 AddTimeData(pfrom->addr.ip, nTime);
1962 if (pfrom->nVersion >= 209)
1963 pfrom->PushMessage("verack");
1964 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1965 if (pfrom->nVersion < 209)
1966 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1968 if (!pfrom->fInbound)
1970 // Advertise our address
1971 if (addrLocalHost.IsRoutable() && !fUseProxy)
1973 CAddress addr(addrLocalHost);
1974 addr.nTime = GetAdjustedTime();
1975 pfrom->PushAddress(addr);
1978 // Get recent addresses
1979 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1981 pfrom->PushMessage("getaddr");
1982 pfrom->fGetAddr = true;
1986 // Ask the first connected node for block updates
1987 static int nAskedForBlocks;
1988 if (!pfrom->fClient &&
1989 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1990 (nAskedForBlocks < 1 || vNodes.size() <= 1))
1993 pfrom->PushGetBlocks(pindexBest, uint256(0));
1997 CRITICAL_BLOCK(cs_mapAlerts)
1998 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1999 item.second.RelayTo(pfrom);
2001 pfrom->fSuccessfullyConnected = true;
2003 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2005 cPeerBlockCounts.input(pfrom->nStartingHeight);
2009 else if (pfrom->nVersion == 0)
2011 // Must have a version message before anything else
2012 pfrom->Misbehaving(1);
2017 else if (strCommand == "verack")
2019 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2023 else if (strCommand == "addr")
2025 vector<CAddress> vAddr;
2028 // Don't want addr from older versions unless seeding
2029 if (pfrom->nVersion < 209)
2031 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2033 if (vAddr.size() > 1000)
2035 pfrom->Misbehaving(20);
2036 return error("message addr size() = %d", vAddr.size());
2039 // Store the new addresses
2042 int64 nNow = GetAdjustedTime();
2043 int64 nSince = nNow - 10 * 60;
2044 BOOST_FOREACH(CAddress& addr, vAddr)
2048 // ignore IPv6 for now, since it isn't implemented anyway
2051 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2052 addr.nTime = nNow - 5 * 24 * 60 * 60;
2053 AddAddress(addr, 2 * 60 * 60, &addrDB);
2054 pfrom->AddAddressKnown(addr);
2055 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2057 // Relay to a limited number of other nodes
2058 CRITICAL_BLOCK(cs_vNodes)
2060 // Use deterministic randomness to send to the same nodes for 24 hours
2061 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2062 static uint256 hashSalt;
2064 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2065 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2066 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2067 multimap<uint256, CNode*> mapMix;
2068 BOOST_FOREACH(CNode* pnode, vNodes)
2070 if (pnode->nVersion < 31402)
2072 unsigned int nPointer;
2073 memcpy(&nPointer, &pnode, sizeof(nPointer));
2074 uint256 hashKey = hashRand ^ nPointer;
2075 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2076 mapMix.insert(make_pair(hashKey, pnode));
2078 int nRelayNodes = 2;
2079 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2080 ((*mi).second)->PushAddress(addr);
2084 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2085 if (vAddr.size() < 1000)
2086 pfrom->fGetAddr = false;
2090 else if (strCommand == "inv")
2094 if (vInv.size() > 50000)
2096 pfrom->Misbehaving(20);
2097 return error("message inv size() = %d", vInv.size());
2101 BOOST_FOREACH(const CInv& inv, vInv)
2105 pfrom->AddInventoryKnown(inv);
2107 bool fAlreadyHave = AlreadyHave(txdb, inv);
2109 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2113 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2114 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2116 // Track requests for our stuff
2117 Inventory(inv.hash);
2122 else if (strCommand == "getdata")
2126 if (vInv.size() > 50000)
2128 pfrom->Misbehaving(20);
2129 return error("message getdata size() = %d", vInv.size());
2132 BOOST_FOREACH(const CInv& inv, vInv)
2136 printf("received getdata for: %s\n", inv.ToString().c_str());
2138 if (inv.type == MSG_BLOCK)
2140 // Send block from disk
2141 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2142 if (mi != mapBlockIndex.end())
2145 block.ReadFromDisk((*mi).second);
2146 pfrom->PushMessage("block", block);
2148 // Trigger them to send a getblocks request for the next batch of inventory
2149 if (inv.hash == pfrom->hashContinue)
2151 // Bypass PushInventory, this must send even if redundant,
2152 // and we want it right after the last block so they don't
2153 // wait for other stuff first.
2155 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2156 pfrom->PushMessage("inv", vInv);
2157 pfrom->hashContinue = 0;
2161 else if (inv.IsKnownType())
2163 // Send stream from relay memory
2164 CRITICAL_BLOCK(cs_mapRelay)
2166 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2167 if (mi != mapRelay.end())
2168 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2172 // Track requests for our stuff
2173 Inventory(inv.hash);
2178 else if (strCommand == "getblocks")
2180 CBlockLocator locator;
2182 vRecv >> locator >> hashStop;
2184 // Find the last block the caller has in the main chain
2185 CBlockIndex* pindex = locator.GetBlockIndex();
2187 // Send the rest of the chain
2189 pindex = pindex->pnext;
2190 int nLimit = 500 + locator.GetDistanceBack();
2191 unsigned int nBytes = 0;
2192 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2193 for (; pindex; pindex = pindex->pnext)
2195 if (pindex->GetBlockHash() == hashStop)
2197 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2200 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2202 block.ReadFromDisk(pindex, true);
2203 nBytes += block.GetSerializeSize(SER_NETWORK);
2204 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2206 // When this block is requested, we'll send an inv that'll make them
2207 // getblocks the next batch of inventory.
2208 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2209 pfrom->hashContinue = pindex->GetBlockHash();
2216 else if (strCommand == "getheaders")
2218 CBlockLocator locator;
2220 vRecv >> locator >> hashStop;
2222 CBlockIndex* pindex = NULL;
2223 if (locator.IsNull())
2225 // If locator is null, return the hashStop block
2226 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2227 if (mi == mapBlockIndex.end())
2229 pindex = (*mi).second;
2233 // Find the last block the caller has in the main chain
2234 pindex = locator.GetBlockIndex();
2236 pindex = pindex->pnext;
2239 vector<CBlock> vHeaders;
2240 int nLimit = 2000 + locator.GetDistanceBack();
2241 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2242 for (; pindex; pindex = pindex->pnext)
2244 vHeaders.push_back(pindex->GetBlockHeader());
2245 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2248 pfrom->PushMessage("headers", vHeaders);
2252 else if (strCommand == "tx")
2254 vector<uint256> vWorkQueue;
2255 CDataStream vMsg(vRecv);
2259 CInv inv(MSG_TX, tx.GetHash());
2260 pfrom->AddInventoryKnown(inv);
2262 bool fMissingInputs = false;
2263 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2265 SyncWithWallets(tx, NULL, true);
2266 RelayMessage(inv, vMsg);
2267 mapAlreadyAskedFor.erase(inv);
2268 vWorkQueue.push_back(inv.hash);
2270 // Recursively process any orphan transactions that depended on this one
2271 for (int i = 0; i < vWorkQueue.size(); i++)
2273 uint256 hashPrev = vWorkQueue[i];
2274 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2275 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2278 const CDataStream& vMsg = *((*mi).second);
2280 CDataStream(vMsg) >> tx;
2281 CInv inv(MSG_TX, tx.GetHash());
2283 if (tx.AcceptToMemoryPool(true))
2285 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2286 SyncWithWallets(tx, NULL, true);
2287 RelayMessage(inv, vMsg);
2288 mapAlreadyAskedFor.erase(inv);
2289 vWorkQueue.push_back(inv.hash);
2294 BOOST_FOREACH(uint256 hash, vWorkQueue)
2295 EraseOrphanTx(hash);
2297 else if (fMissingInputs)
2299 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2302 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2306 else if (strCommand == "block")
2311 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2314 CInv inv(MSG_BLOCK, block.GetHash());
2315 pfrom->AddInventoryKnown(inv);
2317 if (ProcessBlock(pfrom, &block))
2318 mapAlreadyAskedFor.erase(inv);
2319 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2323 else if (strCommand == "getaddr")
2325 // Nodes rebroadcast an addr every 24 hours
2326 pfrom->vAddrToSend.clear();
2327 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2328 CRITICAL_BLOCK(cs_mapAddresses)
2330 unsigned int nCount = 0;
2331 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2333 const CAddress& addr = item.second;
2334 if (addr.nTime > nSince)
2337 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2339 const CAddress& addr = item.second;
2340 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2341 pfrom->PushAddress(addr);
2347 else if (strCommand == "checkorder")
2352 if (!GetBoolArg("-allowreceivebyip"))
2354 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2361 /// we have a chance to check the order here
2363 // Keep giving the same key to the same ip until they use it
2364 if (!mapReuseKey.count(pfrom->addr.ip))
2365 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2367 // Send back approval of order and pubkey to use
2368 CScript scriptPubKey;
2369 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2370 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2374 else if (strCommand == "reply")
2379 CRequestTracker tracker;
2380 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2382 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2383 if (mi != pfrom->mapRequests.end())
2385 tracker = (*mi).second;
2386 pfrom->mapRequests.erase(mi);
2389 if (!tracker.IsNull())
2390 tracker.fn(tracker.param1, vRecv);
2394 else if (strCommand == "ping")
2399 else if (strCommand == "alert")
2404 if (alert.ProcessAlert())
2407 pfrom->setKnown.insert(alert.GetHash());
2408 CRITICAL_BLOCK(cs_vNodes)
2409 BOOST_FOREACH(CNode* pnode, vNodes)
2410 alert.RelayTo(pnode);
2417 // Ignore unknown commands for extensibility
2421 // Update the last seen time for this node's address
2422 if (pfrom->fNetworkNode)
2423 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2424 AddressCurrentlyConnected(pfrom->addr);
2430 bool ProcessMessages(CNode* pfrom)
2432 CDataStream& vRecv = pfrom->vRecv;
2436 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2440 // (4) message start
2449 // Scan for message start
2450 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2451 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2452 if (vRecv.end() - pstart < nHeaderSize)
2454 if (vRecv.size() > nHeaderSize)
2456 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2457 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2461 if (pstart - vRecv.begin() > 0)
2462 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2463 vRecv.erase(vRecv.begin(), pstart);
2466 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2471 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2474 string strCommand = hdr.GetCommand();
2477 unsigned int nMessageSize = hdr.nMessageSize;
2478 if (nMessageSize > MAX_SIZE)
2480 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2483 if (nMessageSize > vRecv.size())
2485 // Rewind and wait for rest of message
2486 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2491 if (vRecv.GetVersion() >= 209)
2493 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2494 unsigned int nChecksum = 0;
2495 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2496 if (nChecksum != hdr.nChecksum)
2498 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2499 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2504 // Copy message to its own buffer
2505 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2506 vRecv.ignore(nMessageSize);
2512 CRITICAL_BLOCK(cs_main)
2513 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2517 catch (std::ios_base::failure& e)
2519 if (strstr(e.what(), "end of data"))
2521 // Allow exceptions from underlength message on vRecv
2522 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());
2524 else if (strstr(e.what(), "size too large"))
2526 // Allow exceptions from overlong size
2527 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2531 PrintExceptionContinue(&e, "ProcessMessage()");
2534 catch (std::exception& e) {
2535 PrintExceptionContinue(&e, "ProcessMessage()");
2537 PrintExceptionContinue(NULL, "ProcessMessage()");
2541 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2549 bool SendMessages(CNode* pto, bool fSendTrickle)
2551 CRITICAL_BLOCK(cs_main)
2553 // Don't send anything until we get their version message
2554 if (pto->nVersion == 0)
2558 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2559 pto->PushMessage("ping");
2561 // Resend wallet transactions that haven't gotten in a block yet
2562 ResendWalletTransactions();
2564 // Address refresh broadcast
2565 static int64 nLastRebroadcast;
2566 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2568 nLastRebroadcast = GetTime();
2569 CRITICAL_BLOCK(cs_vNodes)
2571 BOOST_FOREACH(CNode* pnode, vNodes)
2573 // Periodically clear setAddrKnown to allow refresh broadcasts
2574 pnode->setAddrKnown.clear();
2576 // Rebroadcast our address
2577 if (addrLocalHost.IsRoutable() && !fUseProxy)
2579 CAddress addr(addrLocalHost);
2580 addr.nTime = GetAdjustedTime();
2581 pnode->PushAddress(addr);
2587 // Clear out old addresses periodically so it's not too much work at once
2588 static int64 nLastClear;
2589 if (nLastClear == 0)
2590 nLastClear = GetTime();
2591 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2593 nLastClear = GetTime();
2594 CRITICAL_BLOCK(cs_mapAddresses)
2597 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2598 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2599 mi != mapAddresses.end();)
2601 const CAddress& addr = (*mi).second;
2602 if (addr.nTime < nSince)
2604 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2606 addrdb.EraseAddress(addr);
2607 mapAddresses.erase(mi++);
2621 vector<CAddress> vAddr;
2622 vAddr.reserve(pto->vAddrToSend.size());
2623 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2625 // returns true if wasn't already contained in the set
2626 if (pto->setAddrKnown.insert(addr).second)
2628 vAddr.push_back(addr);
2629 // receiver rejects addr messages larger than 1000
2630 if (vAddr.size() >= 1000)
2632 pto->PushMessage("addr", vAddr);
2637 pto->vAddrToSend.clear();
2639 pto->PushMessage("addr", vAddr);
2644 // Message: inventory
2647 vector<CInv> vInvWait;
2648 CRITICAL_BLOCK(pto->cs_inventory)
2650 vInv.reserve(pto->vInventoryToSend.size());
2651 vInvWait.reserve(pto->vInventoryToSend.size());
2652 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2654 if (pto->setInventoryKnown.count(inv))
2657 // trickle out tx inv to protect privacy
2658 if (inv.type == MSG_TX && !fSendTrickle)
2660 // 1/4 of tx invs blast to all immediately
2661 static uint256 hashSalt;
2663 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2664 uint256 hashRand = inv.hash ^ hashSalt;
2665 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2666 bool fTrickleWait = ((hashRand & 3) != 0);
2668 // always trickle our own transactions
2672 if (GetTransaction(inv.hash, wtx))
2674 fTrickleWait = true;
2679 vInvWait.push_back(inv);
2684 // returns true if wasn't already contained in the set
2685 if (pto->setInventoryKnown.insert(inv).second)
2687 vInv.push_back(inv);
2688 if (vInv.size() >= 1000)
2690 pto->PushMessage("inv", vInv);
2695 pto->vInventoryToSend = vInvWait;
2698 pto->PushMessage("inv", vInv);
2704 vector<CInv> vGetData;
2705 int64 nNow = GetTime() * 1000000;
2707 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2709 const CInv& inv = (*pto->mapAskFor.begin()).second;
2710 if (!AlreadyHave(txdb, inv))
2712 printf("sending getdata: %s\n", inv.ToString().c_str());
2713 vGetData.push_back(inv);
2714 if (vGetData.size() >= 1000)
2716 pto->PushMessage("getdata", vGetData);
2720 mapAlreadyAskedFor[inv] = nNow;
2721 pto->mapAskFor.erase(pto->mapAskFor.begin());
2723 if (!vGetData.empty())
2724 pto->PushMessage("getdata", vGetData);
2743 //////////////////////////////////////////////////////////////////////////////
2748 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2750 unsigned char* pdata = (unsigned char*)pbuffer;
2751 unsigned int blocks = 1 + ((len + 8) / 64);
2752 unsigned char* pend = pdata + 64 * blocks;
2753 memset(pdata + len, 0, 64 * blocks - len);
2755 unsigned int bits = len * 8;
2756 pend[-1] = (bits >> 0) & 0xff;
2757 pend[-2] = (bits >> 8) & 0xff;
2758 pend[-3] = (bits >> 16) & 0xff;
2759 pend[-4] = (bits >> 24) & 0xff;
2763 static const unsigned int pSHA256InitState[8] =
2764 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2766 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2769 unsigned char data[64];
2773 for (int i = 0; i < 16; i++)
2774 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2776 for (int i = 0; i < 8; i++)
2777 ctx.h[i] = ((uint32_t*)pinit)[i];
2779 SHA256_Update(&ctx, data, sizeof(data));
2780 for (int i = 0; i < 8; i++)
2781 ((uint32_t*)pstate)[i] = ctx.h[i];
2785 // ScanHash scans nonces looking for a hash with at least some zero bits.
2786 // It operates on big endian data. Caller does the byte reversing.
2787 // All input buffers are 16-byte aligned. nNonce is usually preserved
2788 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2789 // the block is rebuilt and nNonce starts over at zero.
2791 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2793 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2797 // Hash pdata using pmidstate as the starting state into
2798 // preformatted buffer phash1, then hash phash1 into phash
2800 SHA256Transform(phash1, pdata, pmidstate);
2801 SHA256Transform(phash, phash1, pSHA256InitState);
2803 // Return the nonce if the hash has at least some zero bits,
2804 // caller will check if it has enough to reach the target
2805 if (((unsigned short*)phash)[14] == 0)
2808 // If nothing found after trying for a while, return -1
2809 if ((nNonce & 0xffff) == 0)
2811 nHashesDone = 0xffff+1;
2817 // Some explaining would be appreciated
2822 set<uint256> setDependsOn;
2825 COrphan(CTransaction* ptxIn)
2833 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2834 BOOST_FOREACH(uint256 hash, setDependsOn)
2835 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2840 CBlock* CreateNewBlock(CReserveKey& reservekey)
2842 CBlockIndex* pindexPrev = pindexBest;
2845 auto_ptr<CBlock> pblock(new CBlock());
2849 // Create coinbase tx
2851 txNew.vin.resize(1);
2852 txNew.vin[0].prevout.SetNull();
2853 txNew.vout.resize(1);
2854 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2856 // Add our coinbase tx as first transaction
2857 pblock->vtx.push_back(txNew);
2859 // Collect memory pool transactions into the block
2861 CRITICAL_BLOCK(cs_main)
2862 CRITICAL_BLOCK(cs_mapTransactions)
2866 // Priority order to process transactions
2867 list<COrphan> vOrphan; // list memory doesn't move
2868 map<uint256, vector<COrphan*> > mapDependers;
2869 multimap<double, CTransaction*> mapPriority;
2870 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2872 CTransaction& tx = (*mi).second;
2873 if (tx.IsCoinBase() || !tx.IsFinal())
2876 COrphan* porphan = NULL;
2877 double dPriority = 0;
2878 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2880 // Read prev transaction
2881 CTransaction txPrev;
2883 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2885 // Has to wait for dependencies
2888 // Use list for automatic deletion
2889 vOrphan.push_back(COrphan(&tx));
2890 porphan = &vOrphan.back();
2892 mapDependers[txin.prevout.hash].push_back(porphan);
2893 porphan->setDependsOn.insert(txin.prevout.hash);
2896 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2898 // Read block header
2899 int nConf = txindex.GetDepthInMainChain();
2901 dPriority += (double)nValueIn * nConf;
2903 if (fDebug && GetBoolArg("-printpriority"))
2904 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2907 // Priority is sum(valuein * age) / txsize
2908 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2911 porphan->dPriority = dPriority;
2913 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2915 if (fDebug && GetBoolArg("-printpriority"))
2917 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2924 // Collect transactions into block
2925 map<uint256, CTxIndex> mapTestPool;
2926 uint64 nBlockSize = 1000;
2927 int nBlockSigOps = 100;
2928 while (!mapPriority.empty())
2930 // Take highest priority transaction off priority queue
2931 double dPriority = -(*mapPriority.begin()).first;
2932 CTransaction& tx = *(*mapPriority.begin()).second;
2933 mapPriority.erase(mapPriority.begin());
2936 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2937 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2940 // Transaction fee required depends on block size
2941 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2942 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2944 // Connecting shouldn't fail due to dependency on other memory pool transactions
2945 // because we're already processing them in order of dependency
2946 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2947 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
2948 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
2951 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
2953 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2955 swap(mapTestPool, mapTestPoolTmp);
2958 pblock->vtx.push_back(tx);
2959 nBlockSize += nTxSize;
2960 nBlockSigOps += nTxSigOps;
2962 // Add transactions that depend on this one to the priority queue
2963 uint256 hash = tx.GetHash();
2964 if (mapDependers.count(hash))
2966 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2968 if (!porphan->setDependsOn.empty())
2970 porphan->setDependsOn.erase(hash);
2971 if (porphan->setDependsOn.empty())
2972 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2978 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2981 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2982 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2983 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2984 pblock->nBits = GetNextWorkRequired(pindexPrev);
2987 return pblock.release();
2991 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2993 // Update nExtraNonce
2994 static uint256 hashPrevBlock;
2995 if (hashPrevBlock != pblock->hashPrevBlock)
2998 hashPrevBlock = pblock->hashPrevBlock;
3001 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3003 // Put "OP_EVAL" in the coinbase so everybody can tell when
3004 // a majority of miners support it
3005 const char* pOpEvalName = GetOpName(OP_EVAL);
3006 pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
3007 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3009 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3013 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3016 // Prebuild hash buffers
3023 uint256 hashPrevBlock;
3024 uint256 hashMerkleRoot;
3027 unsigned int nNonce;
3030 unsigned char pchPadding0[64];
3032 unsigned char pchPadding1[64];
3035 memset(&tmp, 0, sizeof(tmp));
3037 tmp.block.nVersion = pblock->nVersion;
3038 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3039 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3040 tmp.block.nTime = pblock->nTime;
3041 tmp.block.nBits = pblock->nBits;
3042 tmp.block.nNonce = pblock->nNonce;
3044 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3045 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3047 // Byte swap all the input buffer
3048 for (int i = 0; i < sizeof(tmp)/4; i++)
3049 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3051 // Precalc the first half of the first hash, which stays constant
3052 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3054 memcpy(pdata, &tmp.block, 128);
3055 memcpy(phash1, &tmp.hash1, 64);
3059 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3061 uint256 hash = pblock->GetHash();
3062 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3064 if (hash > hashTarget)
3068 printf("BitcoinMiner:\n");
3069 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3071 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3072 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3075 CRITICAL_BLOCK(cs_main)
3077 if (pblock->hashPrevBlock != hashBestChain)
3078 return error("BitcoinMiner : generated block is stale");
3080 // Remove key from key pool
3081 reservekey.KeepKey();
3083 // Track how many getdata requests this block gets
3084 CRITICAL_BLOCK(wallet.cs_wallet)
3085 wallet.mapRequestCount[pblock->GetHash()] = 0;
3087 // Process this block the same as if we had received it from another node
3088 if (!ProcessBlock(NULL, pblock))
3089 return error("BitcoinMiner : ProcessBlock, block not accepted");
3095 void static ThreadBitcoinMiner(void* parg);
3097 void static BitcoinMiner(CWallet *pwallet)
3099 printf("BitcoinMiner started\n");
3100 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3102 // Each thread has its own key and counter
3103 CReserveKey reservekey(pwallet);
3104 unsigned int nExtraNonce = 0;
3106 while (fGenerateBitcoins)
3108 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3112 while (vNodes.empty() || IsInitialBlockDownload())
3117 if (!fGenerateBitcoins)
3125 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3126 CBlockIndex* pindexPrev = pindexBest;
3128 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3131 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3133 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3137 // Prebuild hash buffers
3139 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3140 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3141 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3143 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3145 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3146 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3152 int64 nStart = GetTime();
3153 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3155 uint256& hash = *alignup<16>(hashbuf);
3158 unsigned int nHashesDone = 0;
3159 unsigned int nNonceFound;
3162 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3163 (char*)&hash, nHashesDone);
3165 // Check if something found
3166 if (nNonceFound != -1)
3168 for (int i = 0; i < sizeof(hash)/4; i++)
3169 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3171 if (hash <= hashTarget)
3174 pblock->nNonce = ByteReverse(nNonceFound);
3175 assert(hash == pblock->GetHash());
3177 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3178 CheckWork(pblock.get(), *pwalletMain, reservekey);
3179 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3185 static int64 nHashCounter;
3186 if (nHPSTimerStart == 0)
3188 nHPSTimerStart = GetTimeMillis();
3192 nHashCounter += nHashesDone;
3193 if (GetTimeMillis() - nHPSTimerStart > 4000)
3195 static CCriticalSection cs;
3198 if (GetTimeMillis() - nHPSTimerStart > 4000)
3200 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3201 nHPSTimerStart = GetTimeMillis();
3203 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3204 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3205 static int64 nLogTime;
3206 if (GetTime() - nLogTime > 30 * 60)
3208 nLogTime = GetTime();
3209 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3210 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3216 // Check for stop or if block needs to be rebuilt
3219 if (!fGenerateBitcoins)
3221 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3225 if (nBlockNonce >= 0xffff0000)
3227 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3229 if (pindexPrev != pindexBest)
3232 // Update nTime every few seconds
3233 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3234 nBlockTime = ByteReverse(pblock->nTime);
3239 void static ThreadBitcoinMiner(void* parg)
3241 CWallet* pwallet = (CWallet*)parg;
3244 vnThreadsRunning[3]++;
3245 BitcoinMiner(pwallet);
3246 vnThreadsRunning[3]--;
3248 catch (std::exception& e) {
3249 vnThreadsRunning[3]--;
3250 PrintException(&e, "ThreadBitcoinMiner()");
3252 vnThreadsRunning[3]--;
3253 PrintException(NULL, "ThreadBitcoinMiner()");
3255 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3257 if (vnThreadsRunning[3] == 0)
3259 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3263 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3265 if (fGenerateBitcoins != fGenerate)
3267 fGenerateBitcoins = fGenerate;
3268 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3271 if (fGenerateBitcoins)
3273 int nProcessors = boost::thread::hardware_concurrency();
3274 printf("%d processors\n", nProcessors);
3275 if (nProcessors < 1)
3277 if (fLimitProcessors && nProcessors > nLimitProcessors)
3278 nProcessors = nLimitProcessors;
3279 int nAddThreads = nProcessors - vnThreadsRunning[3];
3280 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3281 for (int i = 0; i < nAddThreads; i++)
3283 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3284 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");