1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
26 static map<uint256, CTransaction> mapTransactions;
27 CCriticalSection cs_mapTransactions;
28 unsigned int nTransactionsUpdated = 0;
29 map<COutPoint, CInPoint> mapNextTx;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 uint256 hashGenesisBlock("0x00000000b00cf820bc2b23ec0aad05da6c58af7fd71c34a6f21a747fd0f5620b");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
35 CBlockIndex* pindexGenesisBlock = NULL;
37 uint64 nBestChainTrust = 0;
38 uint64 nBestInvalidTrust = 0;
39 uint256 hashBestChain = 0;
40 CBlockIndex* pindexBest = NULL;
41 int64 nTimeBestReceived = 0;
43 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
45 map<uint256, CBlock*> mapOrphanBlocks;
46 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
48 map<uint256, CDataStream*> mapOrphanTransactions;
49 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
56 int fGenerateBitcoins = false;
57 int64 nTransactionFee = MIN_TX_FEE;
58 int fLimitProcessors = false;
59 int nLimitProcessors = 1;
60 int fMinimizeToTray = true;
61 int fMinimizeOnClose = true;
69 //////////////////////////////////////////////////////////////////////////////
71 // dispatching functions
74 // These functions dispatch to one or all registered wallets
77 void RegisterWallet(CWallet* pwalletIn)
79 CRITICAL_BLOCK(cs_setpwalletRegistered)
81 setpwalletRegistered.insert(pwalletIn);
85 void UnregisterWallet(CWallet* pwalletIn)
87 CRITICAL_BLOCK(cs_setpwalletRegistered)
89 setpwalletRegistered.erase(pwalletIn);
93 // check whether the passed transaction is from us
94 bool static IsFromMe(CTransaction& tx)
96 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
97 if (pwallet->IsFromMe(tx))
102 // get the wallet transaction with the given hash (if it exists)
103 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
105 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
106 if (pwallet->GetTransaction(hashTx,wtx))
111 // erases transaction with the given hash from all wallets
112 void static EraseFromWallets(uint256 hash)
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 pwallet->EraseFromWallet(hash);
118 // make sure all wallets know about the given transaction, in the given block
119 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
121 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
122 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
125 // notify wallets about a new best chain
126 void static SetBestChain(const CBlockLocator& loc)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 pwallet->SetBestChain(loc);
132 // notify wallets about an updated transaction
133 void static UpdatedTransaction(const uint256& hashTx)
135 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
136 pwallet->UpdatedTransaction(hashTx);
140 void static PrintWallets(const CBlock& block)
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->PrintWallet(block);
146 // notify wallets about an incoming inventory (for request counts)
147 void static Inventory(const uint256& hash)
149 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
150 pwallet->Inventory(hash);
153 // ask wallets to resend their transactions
154 void static ResendWalletTransactions()
156 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
157 pwallet->ResendWalletTransactions();
166 //////////////////////////////////////////////////////////////////////////////
168 // mapOrphanTransactions
171 void static AddOrphanTx(const CDataStream& vMsg)
174 CDataStream(vMsg) >> tx;
175 uint256 hash = tx.GetHash();
176 if (mapOrphanTransactions.count(hash))
178 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
179 BOOST_FOREACH(const CTxIn& txin, tx.vin)
180 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
183 void static EraseOrphanTx(uint256 hash)
185 if (!mapOrphanTransactions.count(hash))
187 const CDataStream* pvMsg = mapOrphanTransactions[hash];
189 CDataStream(*pvMsg) >> tx;
190 BOOST_FOREACH(const CTxIn& txin, tx.vin)
192 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
193 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
195 if ((*mi).second == pvMsg)
196 mapOrphanTransactionsByPrev.erase(mi++);
202 mapOrphanTransactions.erase(hash);
212 //////////////////////////////////////////////////////////////////////////////
214 // CTransaction and CTxIndex
217 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
220 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
222 if (!ReadFromDisk(txindexRet.pos))
224 if (prevout.n >= vout.size())
232 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
235 return ReadFromDisk(txdb, prevout, txindex);
238 bool CTransaction::ReadFromDisk(COutPoint prevout)
242 return ReadFromDisk(txdb, prevout, txindex);
247 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
259 // Load the block this tx is in
261 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
263 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
268 // Update the tx's hashBlock
269 hashBlock = pblock->GetHash();
271 // Locate the transaction
272 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
273 if (pblock->vtx[nIndex] == *(CTransaction*)this)
275 if (nIndex == pblock->vtx.size())
277 vMerkleBranch.clear();
279 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
283 // Fill in merkle branch
284 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
287 // Is the tx in a block that's in the main chain
288 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
289 if (mi == mapBlockIndex.end())
291 CBlockIndex* pindex = (*mi).second;
292 if (!pindex || !pindex->IsInMainChain())
295 return pindexBest->nHeight - pindex->nHeight + 1;
304 bool CTransaction::CheckTransaction() const
306 // Basic checks that don't depend on any context
308 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
310 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
312 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
313 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
315 // Check for negative or overflow output values
317 BOOST_FOREACH(const CTxOut& txout, vout)
319 if (txout.nValue < 0)
320 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
321 if (txout.nValue > MAX_MONEY)
322 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
323 nValueOut += txout.nValue;
324 if (!MoneyRange(nValueOut))
325 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
328 // Check for duplicate inputs
329 set<COutPoint> vInOutPoints;
330 BOOST_FOREACH(const CTxIn& txin, vin)
332 if (vInOutPoints.count(txin.prevout))
334 vInOutPoints.insert(txin.prevout);
339 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
340 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
344 BOOST_FOREACH(const CTxIn& txin, vin)
345 if (txin.prevout.IsNull())
346 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
352 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
355 *pfMissingInputs = false;
357 if (!CheckTransaction())
358 return error("AcceptToMemoryPool() : CheckTransaction failed");
360 // Coinbase is only valid in a block, not as a loose transaction
362 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
364 // To help v0.1.5 clients who would see it as a negative number
365 if ((int64)nLockTime > INT_MAX)
366 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
369 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
370 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
371 // attacks disallow transactions with more than one SigOp per 34 bytes.
372 // 34 bytes because a TxOut is:
373 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
374 if (GetSigOpCount() > nSize / 34 || nSize < 100)
375 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
377 // Rather not work on nonstandard transactions (unless -testnet)
378 if (!fTestNet && !IsStandard())
379 return error("AcceptToMemoryPool() : nonstandard transaction type");
381 // Do we already have it?
382 uint256 hash = GetHash();
383 CRITICAL_BLOCK(cs_mapTransactions)
384 if (mapTransactions.count(hash))
387 if (txdb.ContainsTx(hash))
390 // Check for conflicts with in-memory transactions
391 CTransaction* ptxOld = NULL;
392 for (int i = 0; i < vin.size(); i++)
394 COutPoint outpoint = vin[i].prevout;
395 if (mapNextTx.count(outpoint))
397 // Disable replacement feature for now
400 // Allow replacing with a newer version of the same transaction
403 ptxOld = mapNextTx[outpoint].ptx;
404 if (ptxOld->IsFinal())
406 if (!IsNewerThan(*ptxOld))
408 for (int i = 0; i < vin.size(); i++)
410 COutPoint outpoint = vin[i].prevout;
411 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
420 // Check against previous transactions
421 map<uint256, CTxIndex> mapUnused;
423 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
426 *pfMissingInputs = true;
427 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
430 // Don't accept it if it can't get into a block
431 if (nFees < GetMinFee(1000, false, true))
432 return error("AcceptToMemoryPool() : not enough fees");
434 // Continuously rate-limit free transactions
435 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
436 // be annoying or make other's transactions take longer to confirm.
437 if (nFees < MIN_RELAY_TX_FEE)
439 static CCriticalSection cs;
440 static double dFreeCount;
441 static int64 nLastTime;
442 int64 nNow = GetTime();
446 // Use an exponentially decaying ~10-minute window:
447 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
449 // -limitfreerelay unit is thousand-bytes-per-minute
450 // At default rate it would take over a month to fill 1GB
451 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
452 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
454 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
460 // Store transaction in memory
461 CRITICAL_BLOCK(cs_mapTransactions)
465 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
466 ptxOld->RemoveFromMemoryPool();
468 AddToMemoryPoolUnchecked();
471 ///// are we sure this is ok when loading transactions or restoring block txes
472 // If updated, erase old tx from wallet
474 EraseFromWallets(ptxOld->GetHash());
476 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
480 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
483 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
486 bool CTransaction::AddToMemoryPoolUnchecked()
488 // Add to memory pool without checking anything. Don't call this directly,
489 // call AcceptToMemoryPool to properly check the transaction first.
490 CRITICAL_BLOCK(cs_mapTransactions)
492 uint256 hash = GetHash();
493 mapTransactions[hash] = *this;
494 for (int i = 0; i < vin.size(); i++)
495 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
496 nTransactionsUpdated++;
502 bool CTransaction::RemoveFromMemoryPool()
504 // Remove transaction from memory pool
505 CRITICAL_BLOCK(cs_mapTransactions)
507 BOOST_FOREACH(const CTxIn& txin, vin)
508 mapNextTx.erase(txin.prevout);
509 mapTransactions.erase(GetHash());
510 nTransactionsUpdated++;
520 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
522 if (hashBlock == 0 || nIndex == -1)
525 // Find the block it claims to be in
526 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
527 if (mi == mapBlockIndex.end())
529 CBlockIndex* pindex = (*mi).second;
530 if (!pindex || !pindex->IsInMainChain())
533 // Make sure the merkle branch connects to this block
534 if (!fMerkleVerified)
536 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
538 fMerkleVerified = true;
541 nHeightRet = pindex->nHeight;
542 return pindexBest->nHeight - pindex->nHeight + 1;
546 int CMerkleTx::GetBlocksToMaturity() const
550 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
554 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
558 if (!IsInMainChain() && !ClientConnectInputs())
560 return CTransaction::AcceptToMemoryPool(txdb, false);
564 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
568 bool CMerkleTx::AcceptToMemoryPool()
571 return AcceptToMemoryPool(txdb);
576 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
578 CRITICAL_BLOCK(cs_mapTransactions)
580 // Add previous supporting transactions first
581 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
583 if (!tx.IsCoinBase())
585 uint256 hash = tx.GetHash();
586 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
587 tx.AcceptToMemoryPool(txdb, fCheckInputs);
590 return AcceptToMemoryPool(txdb, fCheckInputs);
595 bool CWalletTx::AcceptWalletTransaction()
598 return AcceptWalletTransaction(txdb);
601 int CTxIndex::GetDepthInMainChain() const
605 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
607 // Find the block in the index
608 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
609 if (mi == mapBlockIndex.end())
611 CBlockIndex* pindex = (*mi).second;
612 if (!pindex || !pindex->IsInMainChain())
614 return 1 + nBestHeight - pindex->nHeight;
626 //////////////////////////////////////////////////////////////////////////////
628 // CBlock and CBlockIndex
631 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
633 if (!fReadTransactions)
635 *this = pindex->GetBlockHeader();
638 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
640 if (GetHash() != pindex->GetBlockHash())
641 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
645 uint256 static GetOrphanRoot(const CBlock* pblock)
647 // Work back to the first block in the orphan chain
648 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
649 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
650 return pblock->GetHash();
653 int64 static GetBlockValue(int nHeight, int64 nFees)
655 int64 nSubsidy = 50 * COIN;
657 // Subsidy is cut in half every 4 years
658 nSubsidy >>= (nHeight / 210000);
660 return nSubsidy + nFees;
663 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
664 static const int64 nTargetSpacing = 10 * 60;
665 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
668 // minimum amount of work that could possibly be required nTime after
669 // minimum work required was nBase
671 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
674 bnResult.SetCompact(nBase);
675 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
677 // Maximum 400% adjustment...
679 // ... in best-case exactly 4-times-normal target time
680 nTime -= nTargetTimespan*4;
682 if (bnResult > bnProofOfWorkLimit)
683 bnResult = bnProofOfWorkLimit;
684 return bnResult.GetCompact();
687 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
689 // Genesis block and first block
690 if (pindexLast == NULL || pindexLast->pprev == NULL)
691 return bnProofOfWorkLimit.GetCompact();
693 int64 nActualSpacing = pindexLast->GetBlockTime() - pindexLast->pprev->GetBlockTime();
695 // ppcoin: target change every block
696 // ppcoin: retarget with exponential moving toward target spacing
698 bnNew.SetCompact(pindexLast->nBits);
699 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
700 bnNew /= ((nInterval + 1) * nTargetSpacing);
702 if (bnNew > bnProofOfWorkLimit)
703 bnNew = bnProofOfWorkLimit;
705 return bnNew.GetCompact();
708 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
711 bnTarget.SetCompact(nBits);
714 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
715 return error("CheckProofOfWork() : nBits below minimum work");
717 // Check proof of work matches claimed amount
718 if (hash > bnTarget.getuint256())
719 return error("CheckProofOfWork() : hash doesn't match nBits");
724 // Return maximum amount of blocks that other nodes claim to have
725 int GetNumBlocksOfPeers()
727 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
730 bool IsInitialBlockDownload()
732 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
734 static int64 nLastUpdate;
735 static CBlockIndex* pindexLastBest;
736 if (pindexBest != pindexLastBest)
738 pindexLastBest = pindexBest;
739 nLastUpdate = GetTime();
741 return (GetTime() - nLastUpdate < 10 &&
742 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
745 void static InvalidChainFound(CBlockIndex* pindexNew)
747 if (pindexNew->nChainTrust > nBestInvalidTrust)
749 nBestInvalidTrust = pindexNew->nChainTrust;
750 CTxDB().WriteBestInvalidTrust(nBestInvalidTrust);
753 printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->nChainTrust).ToString().c_str());
754 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
755 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
756 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
769 bool CTransaction::DisconnectInputs(CTxDB& txdb)
771 // Relinquish previous transactions' spent pointers
774 BOOST_FOREACH(const CTxIn& txin, vin)
776 COutPoint prevout = txin.prevout;
778 // Get prev txindex from disk
780 if (!txdb.ReadTxIndex(prevout.hash, txindex))
781 return error("DisconnectInputs() : ReadTxIndex failed");
783 if (prevout.n >= txindex.vSpent.size())
784 return error("DisconnectInputs() : prevout.n out of range");
786 // Mark outpoint as not spent
787 txindex.vSpent[prevout.n].SetNull();
790 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
791 return error("DisconnectInputs() : UpdateTxIndex failed");
795 // Remove transaction from index
796 if (!txdb.EraseTxIndex(*this))
797 return error("DisconnectInputs() : EraseTxPos failed");
803 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
804 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
806 // Take over previous transactions' spent pointers
807 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
808 // fMiner is true when called from the internal bitcoin miner
809 // ... both are false when called from CTransaction::AcceptToMemoryPool
813 for (int i = 0; i < vin.size(); i++)
815 COutPoint prevout = vin[i].prevout;
820 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
822 // Get txindex from current proposed changes
823 txindex = mapTestPool[prevout.hash];
827 // Read txindex from txdb
828 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
830 if (!fFound && (fBlock || fMiner))
831 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
835 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
837 // Get prev tx from single transactions in memory
838 CRITICAL_BLOCK(cs_mapTransactions)
840 if (!mapTransactions.count(prevout.hash))
841 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
842 txPrev = mapTransactions[prevout.hash];
845 txindex.vSpent.resize(txPrev.vout.size());
849 // Get prev tx from disk
850 if (!txPrev.ReadFromDisk(txindex.pos))
851 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
854 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
855 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()));
857 // If prev is coinbase, check that it's matured
858 if (txPrev.IsCoinBase())
859 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
860 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
861 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
863 // ppcoin: check transaction timestamp
864 if (txPrev.nTime > nTime)
865 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
867 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
868 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
869 // still computed and checked, and any change will be caught at the next checkpoint.
870 if (!(fBlock && IsInitialBlockDownload()))
872 if (!VerifySignature(txPrev, *this, i))
873 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
875 // Check for conflicts (double-spend)
876 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
877 // for an attacker to attempt to split the network.
878 if (!txindex.vSpent[prevout.n].IsNull())
879 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());
881 // Check for negative or overflow input values
882 nValueIn += txPrev.vout[prevout.n].nValue;
883 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
884 return DoS(100, error("ConnectInputs() : txin values out of range"));
886 // Mark outpoints as spent
887 txindex.vSpent[prevout.n] = posThisTx;
890 if (fBlock || fMiner)
892 mapTestPool[prevout.hash] = txindex;
896 if (nValueIn < GetValueOut())
897 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
899 // Tally transaction fees
900 int64 nTxFee = nValueIn - GetValueOut();
902 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
903 if (nTxFee < nMinFee)
906 if (!MoneyRange(nFees))
907 return DoS(100, error("ConnectInputs() : nFees out of range"));
912 // Add transaction to changes
913 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
917 // Add transaction to test pool
918 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
925 bool CTransaction::ClientConnectInputs()
930 // Take over previous transactions' spent pointers
931 CRITICAL_BLOCK(cs_mapTransactions)
934 for (int i = 0; i < vin.size(); i++)
936 // Get prev tx from single transactions in memory
937 COutPoint prevout = vin[i].prevout;
938 if (!mapTransactions.count(prevout.hash))
940 CTransaction& txPrev = mapTransactions[prevout.hash];
942 if (prevout.n >= txPrev.vout.size())
946 if (!VerifySignature(txPrev, *this, i))
947 return error("ConnectInputs() : VerifySignature failed");
949 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
950 ///// this has to go away now that posNext is gone
951 // // Check for conflicts
952 // if (!txPrev.vout[prevout.n].posNext.IsNull())
953 // return error("ConnectInputs() : prev tx already used");
955 // // Flag outpoints as used
956 // txPrev.vout[prevout.n].posNext = posThisTx;
958 nValueIn += txPrev.vout[prevout.n].nValue;
960 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
961 return error("ClientConnectInputs() : txin values out of range");
963 if (GetValueOut() > nValueIn)
973 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
975 // Disconnect in reverse order
976 for (int i = vtx.size()-1; i >= 0; i--)
977 if (!vtx[i].DisconnectInputs(txdb))
980 // Update block index on disk without changing it in memory.
981 // The memory index structure will be changed after the db commits.
984 CDiskBlockIndex blockindexPrev(pindex->pprev);
985 blockindexPrev.hashNext = 0;
986 if (!txdb.WriteBlockIndex(blockindexPrev))
987 return error("DisconnectBlock() : WriteBlockIndex failed");
993 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
995 // Check it again in case a previous version let a bad block in
999 //// issue here: it doesn't know the version
1000 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1002 map<uint256, CTxIndex> mapQueuedChanges;
1004 BOOST_FOREACH(CTransaction& tx, vtx)
1006 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1007 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1009 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false))
1012 // Write queued txindex changes
1013 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1015 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1016 return error("ConnectBlock() : UpdateTxIndex failed");
1019 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1022 // Update block index on disk without changing it in memory.
1023 // The memory index structure will be changed after the db commits.
1026 CDiskBlockIndex blockindexPrev(pindex->pprev);
1027 blockindexPrev.hashNext = pindex->GetBlockHash();
1028 if (!txdb.WriteBlockIndex(blockindexPrev))
1029 return error("ConnectBlock() : WriteBlockIndex failed");
1032 // Watch for transactions paying to me
1033 BOOST_FOREACH(CTransaction& tx, vtx)
1034 SyncWithWallets(tx, this, true);
1039 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1041 printf("REORGANIZE\n");
1044 CBlockIndex* pfork = pindexBest;
1045 CBlockIndex* plonger = pindexNew;
1046 while (pfork != plonger)
1048 while (plonger->nHeight > pfork->nHeight)
1049 if (!(plonger = plonger->pprev))
1050 return error("Reorganize() : plonger->pprev is null");
1051 if (pfork == plonger)
1053 if (!(pfork = pfork->pprev))
1054 return error("Reorganize() : pfork->pprev is null");
1057 // List of what to disconnect
1058 vector<CBlockIndex*> vDisconnect;
1059 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1060 vDisconnect.push_back(pindex);
1062 // List of what to connect
1063 vector<CBlockIndex*> vConnect;
1064 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1065 vConnect.push_back(pindex);
1066 reverse(vConnect.begin(), vConnect.end());
1068 // Disconnect shorter branch
1069 vector<CTransaction> vResurrect;
1070 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1073 if (!block.ReadFromDisk(pindex))
1074 return error("Reorganize() : ReadFromDisk for disconnect failed");
1075 if (!block.DisconnectBlock(txdb, pindex))
1076 return error("Reorganize() : DisconnectBlock failed");
1078 // Queue memory transactions to resurrect
1079 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1080 if (!tx.IsCoinBase())
1081 vResurrect.push_back(tx);
1084 // Connect longer branch
1085 vector<CTransaction> vDelete;
1086 for (int i = 0; i < vConnect.size(); i++)
1088 CBlockIndex* pindex = vConnect[i];
1090 if (!block.ReadFromDisk(pindex))
1091 return error("Reorganize() : ReadFromDisk for connect failed");
1092 if (!block.ConnectBlock(txdb, pindex))
1096 return error("Reorganize() : ConnectBlock failed");
1099 // Queue memory transactions to delete
1100 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1101 vDelete.push_back(tx);
1103 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1104 return error("Reorganize() : WriteHashBestChain failed");
1106 // Make sure it's successfully written to disk before changing memory structure
1107 if (!txdb.TxnCommit())
1108 return error("Reorganize() : TxnCommit failed");
1110 // Disconnect shorter branch
1111 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1113 pindex->pprev->pnext = NULL;
1115 // Connect longer branch
1116 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1118 pindex->pprev->pnext = pindex;
1120 // Resurrect memory transactions that were in the disconnected branch
1121 BOOST_FOREACH(CTransaction& tx, vResurrect)
1122 tx.AcceptToMemoryPool(txdb, false);
1124 // Delete redundant memory transactions that are in the connected branch
1125 BOOST_FOREACH(CTransaction& tx, vDelete)
1126 tx.RemoveFromMemoryPool();
1132 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1134 uint256 hash = GetHash();
1137 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1139 txdb.WriteHashBestChain(hash);
1140 if (!txdb.TxnCommit())
1141 return error("SetBestChain() : TxnCommit failed");
1142 pindexGenesisBlock = pindexNew;
1144 else if (hashPrevBlock == hashBestChain)
1146 // Adding to current best branch
1147 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1150 InvalidChainFound(pindexNew);
1151 return error("SetBestChain() : ConnectBlock failed");
1153 if (!txdb.TxnCommit())
1154 return error("SetBestChain() : TxnCommit failed");
1156 // Add to current best branch
1157 pindexNew->pprev->pnext = pindexNew;
1159 // Delete redundant memory transactions
1160 BOOST_FOREACH(CTransaction& tx, vtx)
1161 tx.RemoveFromMemoryPool();
1166 if (!Reorganize(txdb, pindexNew))
1169 InvalidChainFound(pindexNew);
1170 return error("SetBestChain() : Reorganize failed");
1174 // Update best block in wallet (so we can detect restored wallets)
1175 if (!IsInitialBlockDownload())
1177 const CBlockLocator locator(pindexNew);
1178 ::SetBestChain(locator);
1182 hashBestChain = hash;
1183 pindexBest = pindexNew;
1184 nBestHeight = pindexBest->nHeight;
1185 nBestChainTrust = pindexNew->nChainTrust;
1186 nTimeBestReceived = GetTime();
1187 nTransactionsUpdated++;
1188 printf("SetBestChain: new best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
1194 // ppcoin: total coin age spent in block, in the unit of coin-days.
1195 uint64 CBlock::GetBlockCoinAge()
1197 uint64 nCoinAge = 0;
1199 BOOST_FOREACH(const CTransaction& tx, vtx)
1201 if (tx.IsCoinBase())
1204 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1206 // First try finding the previous transaction in database
1207 CTransaction txPrev;
1208 if (!txPrev.ReadFromDisk(txin.prevout))
1210 // If database lookup fails try memory pool
1211 CRITICAL_BLOCK(cs_mapTransactions)
1213 if (!mapTransactions.count(txin.prevout.hash))
1214 return 0; // Neither found in database nor memory pool
1215 txPrev = mapTransactions[txin.prevout.hash];
1219 if (tx.nTime < txPrev.nTime)
1220 return 0; // Transaction timestamp violation
1222 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1223 CBigNum bnTxInCoinAge = CBigNum(nValueIn) * (tx.nTime - txPrev.nTime) / COIN / (24 * 60 * 60);
1224 nCoinAge += bnTxInCoinAge.getuint64();
1226 if (fDebug && GetBoolArg("-printcoinage"))
1227 printf("coin age nValueIn=%-12I64d nTimeDiff=%d nCoinAge=%"PRI64d"\n", nValueIn, tx.nTime - txPrev.nTime, nCoinAge);
1238 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1240 // Check for duplicate
1241 uint256 hash = GetHash();
1242 if (mapBlockIndex.count(hash))
1243 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1245 // Construct new block index object
1246 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1248 return error("AddToBlockIndex() : new CBlockIndex failed");
1249 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1250 pindexNew->phashBlock = &((*mi).first);
1251 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1252 if (miPrev != mapBlockIndex.end())
1254 pindexNew->pprev = (*miPrev).second;
1255 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1257 uint64 nCoinAge = GetBlockCoinAge();
1259 return error("AddToBlockIndex() : invalid or orphaned transaction in block");
1260 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + nCoinAge;
1264 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1265 if (!txdb.TxnCommit())
1269 if (pindexNew->nChainTrust > nBestChainTrust)
1270 if (!SetBestChain(txdb, pindexNew))
1275 if (pindexNew == pindexBest)
1277 // Notify UI to display prev block's coinbase if it was ours
1278 static uint256 hashPrevBestCoinBase;
1279 UpdatedTransaction(hashPrevBestCoinBase);
1280 hashPrevBestCoinBase = vtx[0].GetHash();
1290 bool CBlock::CheckBlock() const
1292 // These are checks that are independent of context
1293 // that can be verified before saving an orphan block.
1296 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1297 return DoS(100, error("CheckBlock() : size limits failed"));
1299 // Check proof of work matches claimed amount
1300 if (!CheckProofOfWork(GetHash(), nBits))
1301 return DoS(50, error("CheckBlock() : proof of work failed"));
1304 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1305 return error("CheckBlock() : block timestamp too far in the future");
1307 // First transaction must be coinbase, the rest must not be
1308 if (vtx.empty() || !vtx[0].IsCoinBase())
1309 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1310 for (int i = 1; i < vtx.size(); i++)
1311 if (vtx[i].IsCoinBase())
1312 return DoS(100, error("CheckBlock() : more than one coinbase"));
1314 // Check transactions
1315 BOOST_FOREACH(const CTransaction& tx, vtx)
1317 if (!tx.CheckTransaction())
1318 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1319 // ppcoin: check transaction timestamp
1320 if (GetBlockTime() < (int64)tx.nTime)
1321 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1324 // Check that it's not full of nonstandard transactions
1325 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1326 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1329 if (hashMerkleRoot != BuildMerkleTree())
1330 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1335 bool CBlock::AcceptBlock()
1337 // Check for duplicate
1338 uint256 hash = GetHash();
1339 if (mapBlockIndex.count(hash))
1340 return error("AcceptBlock() : block already in mapBlockIndex");
1342 // Get prev block index
1343 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1344 if (mi == mapBlockIndex.end())
1345 return DoS(10, error("AcceptBlock() : prev block not found"));
1346 CBlockIndex* pindexPrev = (*mi).second;
1347 int nHeight = pindexPrev->nHeight+1;
1349 // Check proof of work
1350 if (nBits != GetNextWorkRequired(pindexPrev))
1351 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1353 // Check timestamp against prev
1354 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1355 return error("AcceptBlock() : block's timestamp is too early");
1357 // Check that all transactions are finalized
1358 BOOST_FOREACH(const CTransaction& tx, vtx)
1359 if (!tx.IsFinal(nHeight, GetBlockTime()))
1360 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1362 // Check that the block chain matches the known block chain up to a checkpoint
1363 if (!Checkpoints::CheckBlock(nHeight, hash))
1364 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1366 // Write block to history file
1367 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1368 return error("AcceptBlock() : out of disk space");
1369 unsigned int nFile = -1;
1370 unsigned int nBlockPos = 0;
1371 if (!WriteToDisk(nFile, nBlockPos))
1372 return error("AcceptBlock() : WriteToDisk failed");
1373 if (!AddToBlockIndex(nFile, nBlockPos))
1374 return error("AcceptBlock() : AddToBlockIndex failed");
1376 // Relay inventory, but don't relay old inventory during initial block download
1377 if (hashBestChain == hash)
1378 CRITICAL_BLOCK(cs_vNodes)
1379 BOOST_FOREACH(CNode* pnode, vNodes)
1380 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1381 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1386 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1388 // Check for duplicate
1389 uint256 hash = pblock->GetHash();
1390 if (mapBlockIndex.count(hash))
1391 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1392 if (mapOrphanBlocks.count(hash))
1393 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1395 // Preliminary checks
1396 if (!pblock->CheckBlock())
1397 return error("ProcessBlock() : CheckBlock FAILED");
1399 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1400 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1402 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1403 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1406 pfrom->Misbehaving(100);
1407 return error("ProcessBlock() : block with timestamp before last checkpoint");
1410 bnNewBlock.SetCompact(pblock->nBits);
1412 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1413 if (bnNewBlock > bnRequired)
1415 pfrom->Misbehaving(100);
1416 return error("ProcessBlock() : block with too little proof-of-work");
1421 // If don't already have its previous block, shunt it off to holding area until we get it
1422 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1424 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1425 CBlock* pblock2 = new CBlock(*pblock);
1426 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1427 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1429 // Ask this guy to fill in what we're missing
1431 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1436 if (!pblock->AcceptBlock())
1437 return error("ProcessBlock() : AcceptBlock FAILED");
1439 // Recursively process any orphan blocks that depended on this one
1440 vector<uint256> vWorkQueue;
1441 vWorkQueue.push_back(hash);
1442 for (int i = 0; i < vWorkQueue.size(); i++)
1444 uint256 hashPrev = vWorkQueue[i];
1445 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1446 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1449 CBlock* pblockOrphan = (*mi).second;
1450 if (pblockOrphan->AcceptBlock())
1451 vWorkQueue.push_back(pblockOrphan->GetHash());
1452 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1453 delete pblockOrphan;
1455 mapOrphanBlocksByPrev.erase(hashPrev);
1458 printf("ProcessBlock: ACCEPTED\n");
1469 bool CheckDiskSpace(uint64 nAdditionalBytes)
1471 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1473 // Check for 15MB because database could create another 10MB log file at any time
1474 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1477 string strMessage = _("Warning: Disk space is low ");
1478 strMiscWarning = strMessage;
1479 printf("*** %s\n", strMessage.c_str());
1480 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1481 CreateThread(Shutdown, NULL);
1487 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1491 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1494 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1496 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1505 static unsigned int nCurrentBlockFile = 1;
1507 FILE* AppendBlockFile(unsigned int& nFileRet)
1512 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1515 if (fseek(file, 0, SEEK_END) != 0)
1517 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1518 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1520 nFileRet = nCurrentBlockFile;
1524 nCurrentBlockFile++;
1528 bool LoadBlockIndex(bool fAllowNew)
1532 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1533 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1534 pchMessageStart[0] = 0xfa;
1535 pchMessageStart[1] = 0xbf;
1536 pchMessageStart[2] = 0xb5;
1537 pchMessageStart[3] = 0xda;
1544 if (!txdb.LoadBlockIndex())
1549 // Init with genesis block
1551 if (mapBlockIndex.empty())
1557 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1558 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1559 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1560 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1561 // vMerkleTree: 4a5e1e
1564 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
1566 txNew.nTime = 1324698231;
1567 txNew.vin.resize(1);
1568 txNew.vout.resize(1);
1569 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1570 txNew.vout[0].nValue = 50 * COIN;
1571 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1573 block.vtx.push_back(txNew);
1574 block.hashPrevBlock = 0;
1575 block.hashMerkleRoot = block.BuildMerkleTree();
1577 block.nTime = 1324707839;
1578 block.nBits = 0x1d00ffff;
1579 block.nNonce = 486102291;
1583 block.nTime = 1296688602;
1584 block.nBits = 0x1d07fff8;
1585 block.nNonce = 384568319;
1589 printf("%s\n", block.GetHash().ToString().c_str());
1590 printf("%s\n", hashGenesisBlock.ToString().c_str());
1591 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1592 assert(block.hashMerkleRoot == uint256("0x487e83bd2b5a5196a2a6b87998d779a162101cb02cc64bf9ac33289dd0c22352"));
1594 assert(block.GetHash() == hashGenesisBlock);
1596 // Start new block file
1598 unsigned int nBlockPos;
1599 if (!block.WriteToDisk(nFile, nBlockPos))
1600 return error("LoadBlockIndex() : writing genesis block to disk failed");
1601 if (!block.AddToBlockIndex(nFile, nBlockPos))
1602 return error("LoadBlockIndex() : genesis block not accepted");
1610 void PrintBlockTree()
1612 // precompute tree structure
1613 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1614 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1616 CBlockIndex* pindex = (*mi).second;
1617 mapNext[pindex->pprev].push_back(pindex);
1619 //while (rand() % 3 == 0)
1620 // mapNext[pindex->pprev].push_back(pindex);
1623 vector<pair<int, CBlockIndex*> > vStack;
1624 vStack.push_back(make_pair(0, pindexGenesisBlock));
1627 while (!vStack.empty())
1629 int nCol = vStack.back().first;
1630 CBlockIndex* pindex = vStack.back().second;
1633 // print split or gap
1634 if (nCol > nPrevCol)
1636 for (int i = 0; i < nCol-1; i++)
1640 else if (nCol < nPrevCol)
1642 for (int i = 0; i < nCol; i++)
1649 for (int i = 0; i < nCol; i++)
1654 block.ReadFromDisk(pindex);
1655 printf("%d (%u,%u) %s %s tx %d",
1659 block.GetHash().ToString().substr(0,20).c_str(),
1660 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1663 PrintWallets(block);
1665 // put the main timechain first
1666 vector<CBlockIndex*>& vNext = mapNext[pindex];
1667 for (int i = 0; i < vNext.size(); i++)
1669 if (vNext[i]->pnext)
1671 swap(vNext[0], vNext[i]);
1677 for (int i = 0; i < vNext.size(); i++)
1678 vStack.push_back(make_pair(nCol+i, vNext[i]));
1691 //////////////////////////////////////////////////////////////////////////////
1696 map<uint256, CAlert> mapAlerts;
1697 CCriticalSection cs_mapAlerts;
1699 string GetWarnings(string strFor)
1702 string strStatusBar;
1704 if (GetBoolArg("-testsafemode"))
1707 // Misc warnings like out of disk space and clock is wrong
1708 if (strMiscWarning != "")
1711 strStatusBar = strMiscWarning;
1714 // Longer invalid proof-of-work chain
1715 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
1718 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1722 CRITICAL_BLOCK(cs_mapAlerts)
1724 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1726 const CAlert& alert = item.second;
1727 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1729 nPriority = alert.nPriority;
1730 strStatusBar = alert.strStatusBar;
1735 if (strFor == "statusbar")
1736 return strStatusBar;
1737 else if (strFor == "rpc")
1739 assert(!"GetWarnings() : invalid parameter");
1743 bool CAlert::ProcessAlert()
1745 if (!CheckSignature())
1750 CRITICAL_BLOCK(cs_mapAlerts)
1752 // Cancel previous alerts
1753 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1755 const CAlert& alert = (*mi).second;
1758 printf("cancelling alert %d\n", alert.nID);
1759 mapAlerts.erase(mi++);
1761 else if (!alert.IsInEffect())
1763 printf("expiring alert %d\n", alert.nID);
1764 mapAlerts.erase(mi++);
1770 // Check if this alert has been cancelled
1771 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1773 const CAlert& alert = item.second;
1774 if (alert.Cancels(*this))
1776 printf("alert already cancelled by %d\n", alert.nID);
1782 mapAlerts.insert(make_pair(GetHash(), *this));
1785 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1797 //////////////////////////////////////////////////////////////////////////////
1803 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1807 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1808 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1810 // Don't know what it is, just say we already got one
1817 // The message start string is designed to be unlikely to occur in normal data.
1818 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1819 // a large 4-byte int at any alignment.
1820 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1823 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1825 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1826 RandAddSeedPerfmon();
1828 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1829 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1831 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1833 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1841 if (strCommand == "version")
1843 // Each connection can only send one version message
1844 if (pfrom->nVersion != 0)
1846 pfrom->Misbehaving(1);
1854 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1855 if (pfrom->nVersion == 10300)
1856 pfrom->nVersion = 300;
1857 if (pfrom->nVersion >= 106 && !vRecv.empty())
1858 vRecv >> addrFrom >> nNonce;
1859 if (pfrom->nVersion >= 106 && !vRecv.empty())
1860 vRecv >> pfrom->strSubVer;
1861 if (pfrom->nVersion >= 209 && !vRecv.empty())
1862 vRecv >> pfrom->nStartingHeight;
1864 if (pfrom->nVersion == 0)
1867 // Disconnect if we connected to ourself
1868 if (nNonce == nLocalHostNonce && nNonce > 1)
1870 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1871 pfrom->fDisconnect = true;
1875 // Be shy and don't send version until we hear
1876 if (pfrom->fInbound)
1877 pfrom->PushVersion();
1879 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1881 AddTimeData(pfrom->addr.ip, nTime);
1884 if (pfrom->nVersion >= 209)
1885 pfrom->PushMessage("verack");
1886 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1887 if (pfrom->nVersion < 209)
1888 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1890 if (!pfrom->fInbound)
1892 // Advertise our address
1893 if (addrLocalHost.IsRoutable() && !fUseProxy)
1895 CAddress addr(addrLocalHost);
1896 addr.nTime = GetAdjustedTime();
1897 pfrom->PushAddress(addr);
1900 // Get recent addresses
1901 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1903 pfrom->PushMessage("getaddr");
1904 pfrom->fGetAddr = true;
1908 // Ask the first connected node for block updates
1909 static int nAskedForBlocks;
1910 if (!pfrom->fClient &&
1911 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1912 (nAskedForBlocks < 1 || vNodes.size() <= 1))
1915 pfrom->PushGetBlocks(pindexBest, uint256(0));
1919 CRITICAL_BLOCK(cs_mapAlerts)
1920 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1921 item.second.RelayTo(pfrom);
1923 pfrom->fSuccessfullyConnected = true;
1925 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1927 cPeerBlockCounts.input(pfrom->nStartingHeight);
1931 else if (pfrom->nVersion == 0)
1933 // Must have a version message before anything else
1934 pfrom->Misbehaving(1);
1939 else if (strCommand == "verack")
1941 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1945 else if (strCommand == "addr")
1947 vector<CAddress> vAddr;
1950 // Don't want addr from older versions unless seeding
1951 if (pfrom->nVersion < 209)
1953 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1955 if (vAddr.size() > 1000)
1957 pfrom->Misbehaving(20);
1958 return error("message addr size() = %d", vAddr.size());
1961 // Store the new addresses
1964 int64 nNow = GetAdjustedTime();
1965 int64 nSince = nNow - 10 * 60;
1966 BOOST_FOREACH(CAddress& addr, vAddr)
1970 // ignore IPv6 for now, since it isn't implemented anyway
1973 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1974 addr.nTime = nNow - 5 * 24 * 60 * 60;
1975 AddAddress(addr, 2 * 60 * 60, &addrDB);
1976 pfrom->AddAddressKnown(addr);
1977 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1979 // Relay to a limited number of other nodes
1980 CRITICAL_BLOCK(cs_vNodes)
1982 // Use deterministic randomness to send to the same nodes for 24 hours
1983 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1984 static uint256 hashSalt;
1986 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1987 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1988 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1989 multimap<uint256, CNode*> mapMix;
1990 BOOST_FOREACH(CNode* pnode, vNodes)
1992 if (pnode->nVersion < 31402)
1994 unsigned int nPointer;
1995 memcpy(&nPointer, &pnode, sizeof(nPointer));
1996 uint256 hashKey = hashRand ^ nPointer;
1997 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1998 mapMix.insert(make_pair(hashKey, pnode));
2000 int nRelayNodes = 2;
2001 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2002 ((*mi).second)->PushAddress(addr);
2006 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2007 if (vAddr.size() < 1000)
2008 pfrom->fGetAddr = false;
2012 else if (strCommand == "inv")
2016 if (vInv.size() > 50000)
2018 pfrom->Misbehaving(20);
2019 return error("message inv size() = %d", vInv.size());
2023 BOOST_FOREACH(const CInv& inv, vInv)
2027 pfrom->AddInventoryKnown(inv);
2029 bool fAlreadyHave = AlreadyHave(txdb, inv);
2031 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2035 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2036 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2038 // Track requests for our stuff
2039 Inventory(inv.hash);
2044 else if (strCommand == "getdata")
2048 if (vInv.size() > 50000)
2050 pfrom->Misbehaving(20);
2051 return error("message getdata size() = %d", vInv.size());
2054 BOOST_FOREACH(const CInv& inv, vInv)
2058 printf("received getdata for: %s\n", inv.ToString().c_str());
2060 if (inv.type == MSG_BLOCK)
2062 // Send block from disk
2063 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2064 if (mi != mapBlockIndex.end())
2067 block.ReadFromDisk((*mi).second);
2068 pfrom->PushMessage("block", block);
2070 // Trigger them to send a getblocks request for the next batch of inventory
2071 if (inv.hash == pfrom->hashContinue)
2073 // Bypass PushInventory, this must send even if redundant,
2074 // and we want it right after the last block so they don't
2075 // wait for other stuff first.
2077 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2078 pfrom->PushMessage("inv", vInv);
2079 pfrom->hashContinue = 0;
2083 else if (inv.IsKnownType())
2085 // Send stream from relay memory
2086 CRITICAL_BLOCK(cs_mapRelay)
2088 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2089 if (mi != mapRelay.end())
2090 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2094 // Track requests for our stuff
2095 Inventory(inv.hash);
2100 else if (strCommand == "getblocks")
2102 CBlockLocator locator;
2104 vRecv >> locator >> hashStop;
2106 // Find the last block the caller has in the main chain
2107 CBlockIndex* pindex = locator.GetBlockIndex();
2109 // Send the rest of the chain
2111 pindex = pindex->pnext;
2112 int nLimit = 500 + locator.GetDistanceBack();
2113 unsigned int nBytes = 0;
2114 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2115 for (; pindex; pindex = pindex->pnext)
2117 if (pindex->GetBlockHash() == hashStop)
2119 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2122 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2124 block.ReadFromDisk(pindex, true);
2125 nBytes += block.GetSerializeSize(SER_NETWORK);
2126 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2128 // When this block is requested, we'll send an inv that'll make them
2129 // getblocks the next batch of inventory.
2130 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2131 pfrom->hashContinue = pindex->GetBlockHash();
2138 else if (strCommand == "getheaders")
2140 CBlockLocator locator;
2142 vRecv >> locator >> hashStop;
2144 CBlockIndex* pindex = NULL;
2145 if (locator.IsNull())
2147 // If locator is null, return the hashStop block
2148 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2149 if (mi == mapBlockIndex.end())
2151 pindex = (*mi).second;
2155 // Find the last block the caller has in the main chain
2156 pindex = locator.GetBlockIndex();
2158 pindex = pindex->pnext;
2161 vector<CBlock> vHeaders;
2162 int nLimit = 2000 + locator.GetDistanceBack();
2163 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2164 for (; pindex; pindex = pindex->pnext)
2166 vHeaders.push_back(pindex->GetBlockHeader());
2167 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2170 pfrom->PushMessage("headers", vHeaders);
2174 else if (strCommand == "tx")
2176 vector<uint256> vWorkQueue;
2177 CDataStream vMsg(vRecv);
2181 CInv inv(MSG_TX, tx.GetHash());
2182 pfrom->AddInventoryKnown(inv);
2184 bool fMissingInputs = false;
2185 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2187 SyncWithWallets(tx, NULL, true);
2188 RelayMessage(inv, vMsg);
2189 mapAlreadyAskedFor.erase(inv);
2190 vWorkQueue.push_back(inv.hash);
2192 // Recursively process any orphan transactions that depended on this one
2193 for (int i = 0; i < vWorkQueue.size(); i++)
2195 uint256 hashPrev = vWorkQueue[i];
2196 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2197 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2200 const CDataStream& vMsg = *((*mi).second);
2202 CDataStream(vMsg) >> tx;
2203 CInv inv(MSG_TX, tx.GetHash());
2205 if (tx.AcceptToMemoryPool(true))
2207 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2208 SyncWithWallets(tx, NULL, true);
2209 RelayMessage(inv, vMsg);
2210 mapAlreadyAskedFor.erase(inv);
2211 vWorkQueue.push_back(inv.hash);
2216 BOOST_FOREACH(uint256 hash, vWorkQueue)
2217 EraseOrphanTx(hash);
2219 else if (fMissingInputs)
2221 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2224 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2228 else if (strCommand == "block")
2233 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2236 CInv inv(MSG_BLOCK, block.GetHash());
2237 pfrom->AddInventoryKnown(inv);
2239 if (ProcessBlock(pfrom, &block))
2240 mapAlreadyAskedFor.erase(inv);
2241 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2245 else if (strCommand == "getaddr")
2247 // Nodes rebroadcast an addr every 24 hours
2248 pfrom->vAddrToSend.clear();
2249 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2250 CRITICAL_BLOCK(cs_mapAddresses)
2252 unsigned int nCount = 0;
2253 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2255 const CAddress& addr = item.second;
2256 if (addr.nTime > nSince)
2259 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2261 const CAddress& addr = item.second;
2262 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2263 pfrom->PushAddress(addr);
2269 else if (strCommand == "checkorder")
2274 if (!GetBoolArg("-allowreceivebyip"))
2276 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2283 /// we have a chance to check the order here
2285 // Keep giving the same key to the same ip until they use it
2286 if (!mapReuseKey.count(pfrom->addr.ip))
2287 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2289 // Send back approval of order and pubkey to use
2290 CScript scriptPubKey;
2291 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2292 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2296 else if (strCommand == "reply")
2301 CRequestTracker tracker;
2302 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2304 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2305 if (mi != pfrom->mapRequests.end())
2307 tracker = (*mi).second;
2308 pfrom->mapRequests.erase(mi);
2311 if (!tracker.IsNull())
2312 tracker.fn(tracker.param1, vRecv);
2316 else if (strCommand == "ping")
2321 else if (strCommand == "alert")
2326 if (alert.ProcessAlert())
2329 pfrom->setKnown.insert(alert.GetHash());
2330 CRITICAL_BLOCK(cs_vNodes)
2331 BOOST_FOREACH(CNode* pnode, vNodes)
2332 alert.RelayTo(pnode);
2339 // Ignore unknown commands for extensibility
2343 // Update the last seen time for this node's address
2344 if (pfrom->fNetworkNode)
2345 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2346 AddressCurrentlyConnected(pfrom->addr);
2352 bool ProcessMessages(CNode* pfrom)
2354 CDataStream& vRecv = pfrom->vRecv;
2358 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2362 // (4) message start
2371 // Scan for message start
2372 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2373 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2374 if (vRecv.end() - pstart < nHeaderSize)
2376 if (vRecv.size() > nHeaderSize)
2378 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2379 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2383 if (pstart - vRecv.begin() > 0)
2384 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2385 vRecv.erase(vRecv.begin(), pstart);
2388 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2393 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2396 string strCommand = hdr.GetCommand();
2399 unsigned int nMessageSize = hdr.nMessageSize;
2400 if (nMessageSize > MAX_SIZE)
2402 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2405 if (nMessageSize > vRecv.size())
2407 // Rewind and wait for rest of message
2408 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2413 if (vRecv.GetVersion() >= 209)
2415 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2416 unsigned int nChecksum = 0;
2417 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2418 if (nChecksum != hdr.nChecksum)
2420 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2421 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2426 // Copy message to its own buffer
2427 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2428 vRecv.ignore(nMessageSize);
2434 CRITICAL_BLOCK(cs_main)
2435 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2439 catch (std::ios_base::failure& e)
2441 if (strstr(e.what(), "end of data"))
2443 // Allow exceptions from underlength message on vRecv
2444 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());
2446 else if (strstr(e.what(), "size too large"))
2448 // Allow exceptions from overlong size
2449 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2453 PrintExceptionContinue(&e, "ProcessMessage()");
2456 catch (std::exception& e) {
2457 PrintExceptionContinue(&e, "ProcessMessage()");
2459 PrintExceptionContinue(NULL, "ProcessMessage()");
2463 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2471 bool SendMessages(CNode* pto, bool fSendTrickle)
2473 CRITICAL_BLOCK(cs_main)
2475 // Don't send anything until we get their version message
2476 if (pto->nVersion == 0)
2480 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2481 pto->PushMessage("ping");
2483 // Resend wallet transactions that haven't gotten in a block yet
2484 ResendWalletTransactions();
2486 // Address refresh broadcast
2487 static int64 nLastRebroadcast;
2488 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2490 nLastRebroadcast = GetTime();
2491 CRITICAL_BLOCK(cs_vNodes)
2493 BOOST_FOREACH(CNode* pnode, vNodes)
2495 // Periodically clear setAddrKnown to allow refresh broadcasts
2496 pnode->setAddrKnown.clear();
2498 // Rebroadcast our address
2499 if (addrLocalHost.IsRoutable() && !fUseProxy)
2501 CAddress addr(addrLocalHost);
2502 addr.nTime = GetAdjustedTime();
2503 pnode->PushAddress(addr);
2509 // Clear out old addresses periodically so it's not too much work at once
2510 static int64 nLastClear;
2511 if (nLastClear == 0)
2512 nLastClear = GetTime();
2513 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2515 nLastClear = GetTime();
2516 CRITICAL_BLOCK(cs_mapAddresses)
2519 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2520 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2521 mi != mapAddresses.end();)
2523 const CAddress& addr = (*mi).second;
2524 if (addr.nTime < nSince)
2526 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2528 addrdb.EraseAddress(addr);
2529 mapAddresses.erase(mi++);
2543 vector<CAddress> vAddr;
2544 vAddr.reserve(pto->vAddrToSend.size());
2545 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2547 // returns true if wasn't already contained in the set
2548 if (pto->setAddrKnown.insert(addr).second)
2550 vAddr.push_back(addr);
2551 // receiver rejects addr messages larger than 1000
2552 if (vAddr.size() >= 1000)
2554 pto->PushMessage("addr", vAddr);
2559 pto->vAddrToSend.clear();
2561 pto->PushMessage("addr", vAddr);
2566 // Message: inventory
2569 vector<CInv> vInvWait;
2570 CRITICAL_BLOCK(pto->cs_inventory)
2572 vInv.reserve(pto->vInventoryToSend.size());
2573 vInvWait.reserve(pto->vInventoryToSend.size());
2574 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2576 if (pto->setInventoryKnown.count(inv))
2579 // trickle out tx inv to protect privacy
2580 if (inv.type == MSG_TX && !fSendTrickle)
2582 // 1/4 of tx invs blast to all immediately
2583 static uint256 hashSalt;
2585 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2586 uint256 hashRand = inv.hash ^ hashSalt;
2587 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2588 bool fTrickleWait = ((hashRand & 3) != 0);
2590 // always trickle our own transactions
2594 if (GetTransaction(inv.hash, wtx))
2596 fTrickleWait = true;
2601 vInvWait.push_back(inv);
2606 // returns true if wasn't already contained in the set
2607 if (pto->setInventoryKnown.insert(inv).second)
2609 vInv.push_back(inv);
2610 if (vInv.size() >= 1000)
2612 pto->PushMessage("inv", vInv);
2617 pto->vInventoryToSend = vInvWait;
2620 pto->PushMessage("inv", vInv);
2626 vector<CInv> vGetData;
2627 int64 nNow = GetTime() * 1000000;
2629 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2631 const CInv& inv = (*pto->mapAskFor.begin()).second;
2632 if (!AlreadyHave(txdb, inv))
2634 printf("sending getdata: %s\n", inv.ToString().c_str());
2635 vGetData.push_back(inv);
2636 if (vGetData.size() >= 1000)
2638 pto->PushMessage("getdata", vGetData);
2642 mapAlreadyAskedFor[inv] = nNow;
2643 pto->mapAskFor.erase(pto->mapAskFor.begin());
2645 if (!vGetData.empty())
2646 pto->PushMessage("getdata", vGetData);
2665 //////////////////////////////////////////////////////////////////////////////
2670 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2672 unsigned char* pdata = (unsigned char*)pbuffer;
2673 unsigned int blocks = 1 + ((len + 8) / 64);
2674 unsigned char* pend = pdata + 64 * blocks;
2675 memset(pdata + len, 0, 64 * blocks - len);
2677 unsigned int bits = len * 8;
2678 pend[-1] = (bits >> 0) & 0xff;
2679 pend[-2] = (bits >> 8) & 0xff;
2680 pend[-3] = (bits >> 16) & 0xff;
2681 pend[-4] = (bits >> 24) & 0xff;
2685 static const unsigned int pSHA256InitState[8] =
2686 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2688 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2691 unsigned char data[64];
2695 for (int i = 0; i < 16; i++)
2696 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2698 for (int i = 0; i < 8; i++)
2699 ctx.h[i] = ((uint32_t*)pinit)[i];
2701 SHA256_Update(&ctx, data, sizeof(data));
2702 for (int i = 0; i < 8; i++)
2703 ((uint32_t*)pstate)[i] = ctx.h[i];
2707 // ScanHash scans nonces looking for a hash with at least some zero bits.
2708 // It operates on big endian data. Caller does the byte reversing.
2709 // All input buffers are 16-byte aligned. nNonce is usually preserved
2710 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2711 // the block is rebuilt and nNonce starts over at zero.
2713 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2715 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2719 // Hash pdata using pmidstate as the starting state into
2720 // preformatted buffer phash1, then hash phash1 into phash
2722 SHA256Transform(phash1, pdata, pmidstate);
2723 SHA256Transform(phash, phash1, pSHA256InitState);
2725 // Return the nonce if the hash has at least some zero bits,
2726 // caller will check if it has enough to reach the target
2727 if (((unsigned short*)phash)[14] == 0)
2730 // If nothing found after trying for a while, return -1
2731 if ((nNonce & 0xffff) == 0)
2733 nHashesDone = 0xffff+1;
2739 // Some explaining would be appreciated
2744 set<uint256> setDependsOn;
2747 COrphan(CTransaction* ptxIn)
2755 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2756 BOOST_FOREACH(uint256 hash, setDependsOn)
2757 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2762 CBlock* CreateNewBlock(CReserveKey& reservekey)
2764 CBlockIndex* pindexPrev = pindexBest;
2767 auto_ptr<CBlock> pblock(new CBlock());
2771 // Create coinbase tx
2773 txNew.vin.resize(1);
2774 txNew.vin[0].prevout.SetNull();
2775 txNew.vout.resize(1);
2776 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2778 // Add our coinbase tx as first transaction
2779 pblock->vtx.push_back(txNew);
2781 // Collect memory pool transactions into the block
2783 CRITICAL_BLOCK(cs_main)
2784 CRITICAL_BLOCK(cs_mapTransactions)
2788 // Priority order to process transactions
2789 list<COrphan> vOrphan; // list memory doesn't move
2790 map<uint256, vector<COrphan*> > mapDependers;
2791 multimap<double, CTransaction*> mapPriority;
2792 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2794 CTransaction& tx = (*mi).second;
2795 if (tx.IsCoinBase() || !tx.IsFinal())
2798 COrphan* porphan = NULL;
2799 double dPriority = 0;
2800 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2802 // Read prev transaction
2803 CTransaction txPrev;
2805 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2807 // Has to wait for dependencies
2810 // Use list for automatic deletion
2811 vOrphan.push_back(COrphan(&tx));
2812 porphan = &vOrphan.back();
2814 mapDependers[txin.prevout.hash].push_back(porphan);
2815 porphan->setDependsOn.insert(txin.prevout.hash);
2818 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2820 // Read block header
2821 int nConf = txindex.GetDepthInMainChain();
2823 dPriority += (double)nValueIn * nConf;
2825 if (fDebug && GetBoolArg("-printpriority"))
2826 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2829 // Priority is sum(valuein * age) / txsize
2830 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2833 porphan->dPriority = dPriority;
2835 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2837 if (fDebug && GetBoolArg("-printpriority"))
2839 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2846 // Collect transactions into block
2847 map<uint256, CTxIndex> mapTestPool;
2848 uint64 nBlockSize = 1000;
2849 int nBlockSigOps = 100;
2850 while (!mapPriority.empty())
2852 // Take highest priority transaction off priority queue
2853 double dPriority = -(*mapPriority.begin()).first;
2854 CTransaction& tx = *(*mapPriority.begin()).second;
2855 mapPriority.erase(mapPriority.begin());
2858 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2859 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2861 int nTxSigOps = tx.GetSigOpCount();
2862 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2866 if (tx.nTime > GetAdjustedTime())
2869 // ppcoin: simplify transaction fee - allow free = false
2870 int64 nMinFee = tx.GetMinFee(nBlockSize, false, true);
2872 // Connecting shouldn't fail due to dependency on other memory pool transactions
2873 // because we're already processing them in order of dependency
2874 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2875 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2877 swap(mapTestPool, mapTestPoolTmp);
2880 pblock->vtx.push_back(tx);
2881 nBlockSize += nTxSize;
2882 nBlockSigOps += nTxSigOps;
2884 // Add transactions that depend on this one to the priority queue
2885 uint256 hash = tx.GetHash();
2886 if (mapDependers.count(hash))
2888 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2890 if (!porphan->setDependsOn.empty())
2892 porphan->setDependsOn.erase(hash);
2893 if (porphan->setDependsOn.empty())
2894 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2900 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2903 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2904 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2905 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2906 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
2907 pblock->nBits = GetNextWorkRequired(pindexPrev);
2910 return pblock.release();
2914 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2916 // Update nExtraNonce
2917 static uint256 hashPrevBlock;
2918 if (hashPrevBlock != pblock->hashPrevBlock)
2921 hashPrevBlock = pblock->hashPrevBlock;
2924 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2925 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2929 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2932 // Prebuild hash buffers
2939 uint256 hashPrevBlock;
2940 uint256 hashMerkleRoot;
2943 unsigned int nNonce;
2946 unsigned char pchPadding0[64];
2948 unsigned char pchPadding1[64];
2951 memset(&tmp, 0, sizeof(tmp));
2953 tmp.block.nVersion = pblock->nVersion;
2954 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2955 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2956 tmp.block.nTime = pblock->nTime;
2957 tmp.block.nBits = pblock->nBits;
2958 tmp.block.nNonce = pblock->nNonce;
2960 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2961 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2963 // Byte swap all the input buffer
2964 for (int i = 0; i < sizeof(tmp)/4; i++)
2965 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2967 // Precalc the first half of the first hash, which stays constant
2968 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2970 memcpy(pdata, &tmp.block, 128);
2971 memcpy(phash1, &tmp.hash1, 64);
2975 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2977 uint256 hash = pblock->GetHash();
2978 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2980 if (hash > hashTarget)
2984 printf("BitcoinMiner:\n");
2985 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2987 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2988 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2991 CRITICAL_BLOCK(cs_main)
2993 if (pblock->hashPrevBlock != hashBestChain)
2994 return error("BitcoinMiner : generated block is stale");
2996 // Remove key from key pool
2997 reservekey.KeepKey();
2999 // Track how many getdata requests this block gets
3000 CRITICAL_BLOCK(wallet.cs_wallet)
3001 wallet.mapRequestCount[pblock->GetHash()] = 0;
3003 // Process this block the same as if we had received it from another node
3004 if (!ProcessBlock(NULL, pblock))
3005 return error("BitcoinMiner : ProcessBlock, block not accepted");
3011 void static ThreadBitcoinMiner(void* parg);
3013 void static BitcoinMiner(CWallet *pwallet)
3015 printf("BitcoinMiner started\n");
3016 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3018 // Each thread has its own key and counter
3019 CReserveKey reservekey(pwallet);
3020 unsigned int nExtraNonce = 0;
3022 while (fGenerateBitcoins)
3024 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3028 while (vNodes.empty() || IsInitialBlockDownload())
3033 if (!fGenerateBitcoins)
3041 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3042 CBlockIndex* pindexPrev = pindexBest;
3044 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3047 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3049 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3053 // Prebuild hash buffers
3055 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3056 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3057 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3059 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3061 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3062 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3068 int64 nStart = GetTime();
3069 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3071 uint256& hash = *alignup<16>(hashbuf);
3074 unsigned int nHashesDone = 0;
3075 unsigned int nNonceFound;
3078 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3079 (char*)&hash, nHashesDone);
3081 // Check if something found
3082 if (nNonceFound != -1)
3084 for (int i = 0; i < sizeof(hash)/4; i++)
3085 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3087 if (hash <= hashTarget)
3090 pblock->nNonce = ByteReverse(nNonceFound);
3091 assert(hash == pblock->GetHash());
3093 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3094 CheckWork(pblock.get(), *pwalletMain, reservekey);
3095 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3101 static int64 nHashCounter;
3102 if (nHPSTimerStart == 0)
3104 nHPSTimerStart = GetTimeMillis();
3108 nHashCounter += nHashesDone;
3109 if (GetTimeMillis() - nHPSTimerStart > 4000)
3111 static CCriticalSection cs;
3114 if (GetTimeMillis() - nHPSTimerStart > 4000)
3116 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3117 nHPSTimerStart = GetTimeMillis();
3119 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3120 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3121 static int64 nLogTime;
3122 if (GetTime() - nLogTime > 30 * 60)
3124 nLogTime = GetTime();
3125 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3126 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3132 // Check for stop or if block needs to be rebuilt
3135 if (!fGenerateBitcoins)
3137 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3141 if (nBlockNonce >= 0xffff0000)
3143 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3145 if (pindexPrev != pindexBest)
3148 // Update nTime every few seconds
3149 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3150 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3151 nBlockTime = ByteReverse(pblock->nTime);
3156 void static ThreadBitcoinMiner(void* parg)
3158 CWallet* pwallet = (CWallet*)parg;
3161 vnThreadsRunning[3]++;
3162 BitcoinMiner(pwallet);
3163 vnThreadsRunning[3]--;
3165 catch (std::exception& e) {
3166 vnThreadsRunning[3]--;
3167 PrintException(&e, "ThreadBitcoinMiner()");
3169 vnThreadsRunning[3]--;
3170 PrintException(NULL, "ThreadBitcoinMiner()");
3172 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3174 if (vnThreadsRunning[3] == 0)
3176 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3180 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3182 if (fGenerateBitcoins != fGenerate)
3184 fGenerateBitcoins = fGenerate;
3185 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3188 if (fGenerateBitcoins)
3190 int nProcessors = boost::thread::hardware_concurrency();
3191 printf("%d processors\n", nProcessors);
3192 if (nProcessors < 1)
3194 if (fLimitProcessors && nProcessors > nLimitProcessors)
3195 nProcessors = nLimitProcessors;
3196 int nAddThreads = nProcessors - vnThreadsRunning[3];
3197 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3198 for (int i = 0; i < nAddThreads; i++)
3200 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3201 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");