1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
12 #include <boost/algorithm/string/replace.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
17 using namespace boost;
23 CCriticalSection cs_setpwalletRegistered;
24 set<CWallet*> setpwalletRegistered;
26 CCriticalSection cs_main;
29 unsigned int nTransactionsUpdated = 0;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 CBlockIndex* pindexGenesisBlock = NULL;
36 CBigNum bnBestChainWork = 0;
37 CBigNum bnBestInvalidWork = 0;
38 uint256 hashBestChain = 0;
39 CBlockIndex* pindexBest = NULL;
40 int64 nTimeBestReceived = 0;
42 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
44 map<uint256, CBlock*> mapOrphanBlocks;
45 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
47 map<uint256, CDataStream*> mapOrphanTransactions;
48 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
50 // Constant stuff for coinbase transactions we create:
51 CScript COINBASE_FLAGS;
53 const string strMessageMagic = "Bitcoin Signed Message:\n";
59 int64 nTransactionFee = 0;
63 //////////////////////////////////////////////////////////////////////////////
65 // dispatching functions
68 // These functions dispatch to one or all registered wallets
71 void RegisterWallet(CWallet* pwalletIn)
74 LOCK(cs_setpwalletRegistered);
75 setpwalletRegistered.insert(pwalletIn);
79 void UnregisterWallet(CWallet* pwalletIn)
82 LOCK(cs_setpwalletRegistered);
83 setpwalletRegistered.erase(pwalletIn);
87 // check whether the passed transaction is from us
88 bool static IsFromMe(CTransaction& tx)
90 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
91 if (pwallet->IsFromMe(tx))
96 // get the wallet transaction with the given hash (if it exists)
97 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
99 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
100 if (pwallet->GetTransaction(hashTx,wtx))
105 // erases transaction with the given hash from all wallets
106 void static EraseFromWallets(uint256 hash)
108 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
109 pwallet->EraseFromWallet(hash);
112 // make sure all wallets know about the given transaction, in the given block
113 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
115 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
119 // notify wallets about a new best chain
120 void static SetBestChain(const CBlockLocator& loc)
122 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
123 pwallet->SetBestChain(loc);
126 // notify wallets about an updated transaction
127 void static UpdatedTransaction(const uint256& hashTx)
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 pwallet->UpdatedTransaction(hashTx);
134 void static PrintWallets(const CBlock& block)
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
137 pwallet->PrintWallet(block);
140 // notify wallets about an incoming inventory (for request counts)
141 void static Inventory(const uint256& hash)
143 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
144 pwallet->Inventory(hash);
147 // ask wallets to resend their transactions
148 void static ResendWalletTransactions()
150 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
151 pwallet->ResendWalletTransactions();
160 //////////////////////////////////////////////////////////////////////////////
162 // mapOrphanTransactions
165 bool AddOrphanTx(const CDataStream& vMsg)
168 CDataStream(vMsg) >> tx;
169 uint256 hash = tx.GetHash();
170 if (mapOrphanTransactions.count(hash))
173 CDataStream* pvMsg = new CDataStream(vMsg);
175 // Ignore big transactions, to avoid a
176 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
177 // large transaction with a missing parent then we assume
178 // it will rebroadcast it later, after the parent transaction(s)
179 // have been mined or received.
180 // 10,000 orphans, each of which is at most 5,000 bytes big is
181 // at most 500 megabytes of orphans:
182 if (pvMsg->size() > 5000)
184 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
189 mapOrphanTransactions[hash] = pvMsg;
190 BOOST_FOREACH(const CTxIn& txin, tx.vin)
191 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
193 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
194 mapOrphanTransactions.size());
198 void static EraseOrphanTx(uint256 hash)
200 if (!mapOrphanTransactions.count(hash))
202 const CDataStream* pvMsg = mapOrphanTransactions[hash];
204 CDataStream(*pvMsg) >> tx;
205 BOOST_FOREACH(const CTxIn& txin, tx.vin)
207 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
208 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
209 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
212 mapOrphanTransactions.erase(hash);
215 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
217 unsigned int nEvicted = 0;
218 while (mapOrphanTransactions.size() > nMaxOrphans)
220 // Evict a random orphan:
221 uint256 randomhash = GetRandHash();
222 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
223 if (it == mapOrphanTransactions.end())
224 it = mapOrphanTransactions.begin();
225 EraseOrphanTx(it->first);
237 //////////////////////////////////////////////////////////////////////////////
239 // CTransaction and CTxIndex
242 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
245 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
247 if (!ReadFromDisk(txindexRet.pos))
249 if (prevout.n >= vout.size())
257 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
260 return ReadFromDisk(txdb, prevout, txindex);
263 bool CTransaction::ReadFromDisk(COutPoint prevout)
267 return ReadFromDisk(txdb, prevout, txindex);
270 bool CTransaction::IsStandard() const
272 if (nVersion > CTransaction::CURRENT_VERSION)
275 BOOST_FOREACH(const CTxIn& txin, vin)
277 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
278 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
279 // ~65-byte public keys, plus a few script ops.
280 if (txin.scriptSig.size() > 500)
282 if (!txin.scriptSig.IsPushOnly())
285 BOOST_FOREACH(const CTxOut& txout, vout) {
286 if (!::IsStandard(txout.scriptPubKey))
288 if (txout.nValue == 0)
295 // Check transaction inputs, and make sure any
296 // pay-to-script-hash transactions are evaluating IsStandard scripts
298 // Why bother? To avoid denial-of-service attacks; an attacker
299 // can submit a standard HASH... OP_EQUAL transaction,
300 // which will get accepted into blocks. The redemption
301 // script can be anything; an attacker could use a very
302 // expensive-to-check-upon-redemption script like:
303 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
305 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
308 return true; // Coinbases don't use vin normally
310 for (unsigned int i = 0; i < vin.size(); i++)
312 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
314 vector<vector<unsigned char> > vSolutions;
315 txnouttype whichType;
316 // get the scriptPubKey corresponding to this input:
317 const CScript& prevScript = prev.scriptPubKey;
318 if (!Solver(prevScript, whichType, vSolutions))
320 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
321 if (nArgsExpected < 0)
324 // Transactions with extra stuff in their scriptSigs are
325 // non-standard. Note that this EvalScript() call will
326 // be quick, because if there are any operations
327 // beside "push data" in the scriptSig the
328 // IsStandard() call returns false
329 vector<vector<unsigned char> > stack;
330 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
333 if (whichType == TX_SCRIPTHASH)
337 CScript subscript(stack.back().begin(), stack.back().end());
338 vector<vector<unsigned char> > vSolutions2;
339 txnouttype whichType2;
340 if (!Solver(subscript, whichType2, vSolutions2))
342 if (whichType2 == TX_SCRIPTHASH)
346 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
349 nArgsExpected += tmpExpected;
352 if (stack.size() != (unsigned int)nArgsExpected)
360 CTransaction::GetLegacySigOpCount() const
362 unsigned int nSigOps = 0;
363 BOOST_FOREACH(const CTxIn& txin, vin)
365 nSigOps += txin.scriptSig.GetSigOpCount(false);
367 BOOST_FOREACH(const CTxOut& txout, vout)
369 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
375 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
387 // Load the block this tx is in
389 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
391 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
396 // Update the tx's hashBlock
397 hashBlock = pblock->GetHash();
399 // Locate the transaction
400 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
401 if (pblock->vtx[nIndex] == *(CTransaction*)this)
403 if (nIndex == (int)pblock->vtx.size())
405 vMerkleBranch.clear();
407 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
411 // Fill in merkle branch
412 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
415 // Is the tx in a block that's in the main chain
416 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
417 if (mi == mapBlockIndex.end())
419 CBlockIndex* pindex = (*mi).second;
420 if (!pindex || !pindex->IsInMainChain())
423 return pindexBest->nHeight - pindex->nHeight + 1;
432 bool CTransaction::CheckTransaction() const
434 // Basic checks that don't depend on any context
436 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
438 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
440 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
441 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
443 // Check for negative or overflow output values
445 BOOST_FOREACH(const CTxOut& txout, vout)
447 if (txout.nValue < 0)
448 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
449 if (txout.nValue > MAX_MONEY)
450 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
451 nValueOut += txout.nValue;
452 if (!MoneyRange(nValueOut))
453 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
456 // Check for duplicate inputs
457 set<COutPoint> vInOutPoints;
458 BOOST_FOREACH(const CTxIn& txin, vin)
460 if (vInOutPoints.count(txin.prevout))
462 vInOutPoints.insert(txin.prevout);
467 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
468 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
472 BOOST_FOREACH(const CTxIn& txin, vin)
473 if (txin.prevout.IsNull())
474 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
480 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
481 enum GetMinFee_mode mode) const
483 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
484 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
486 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
487 unsigned int nNewBlockSize = nBlockSize + nBytes;
488 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
494 // Transactions under 10K are free
495 // (about 4500 BTC if made of 50 BTC inputs)
501 // Free transaction area
502 if (nNewBlockSize < 27000)
507 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
508 if (nMinFee < nBaseFee)
510 BOOST_FOREACH(const CTxOut& txout, vout)
511 if (txout.nValue < CENT)
515 // Raise the price as the block approaches full
516 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
518 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
520 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
523 if (!MoneyRange(nMinFee))
529 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
530 bool* pfMissingInputs)
533 *pfMissingInputs = false;
535 if (!tx.CheckTransaction())
536 return error("CTxMemPool::accept() : CheckTransaction failed");
538 // Coinbase is only valid in a block, not as a loose transaction
540 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
542 // To help v0.1.5 clients who would see it as a negative number
543 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
544 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
546 // Rather not work on nonstandard transactions (unless -testnet)
547 if (!fTestNet && !tx.IsStandard())
548 return error("CTxMemPool::accept() : nonstandard transaction type");
550 // Do we already have it?
551 uint256 hash = tx.GetHash();
554 if (mapTx.count(hash))
558 if (txdb.ContainsTx(hash))
561 // Check for conflicts with in-memory transactions
562 CTransaction* ptxOld = NULL;
563 for (unsigned int i = 0; i < tx.vin.size(); i++)
565 COutPoint outpoint = tx.vin[i].prevout;
566 if (mapNextTx.count(outpoint))
568 // Disable replacement feature for now
571 // Allow replacing with a newer version of the same transaction
574 ptxOld = mapNextTx[outpoint].ptx;
575 if (ptxOld->IsFinal())
577 if (!tx.IsNewerThan(*ptxOld))
579 for (unsigned int i = 0; i < tx.vin.size(); i++)
581 COutPoint outpoint = tx.vin[i].prevout;
582 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
592 map<uint256, CTxIndex> mapUnused;
593 bool fInvalid = false;
594 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
597 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
599 *pfMissingInputs = true;
603 // Check for non-standard pay-to-script-hash in inputs
604 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
605 return error("CTxMemPool::accept() : nonstandard transaction input");
607 // Note: if you modify this code to accept non-standard transactions, then
608 // you should add code here to check that the transaction does a
609 // reasonable number of ECDSA signature verifications.
611 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
612 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
614 // Don't accept it if it can't get into a block
615 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
616 if (nFees < txMinFee)
617 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
618 hash.ToString().c_str(),
621 // Continuously rate-limit free transactions
622 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
623 // be annoying or make others' transactions take longer to confirm.
624 if (nFees < MIN_RELAY_TX_FEE)
626 static CCriticalSection cs;
627 static double dFreeCount;
628 static int64 nLastTime;
629 int64 nNow = GetTime();
633 // Use an exponentially decaying ~10-minute window:
634 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
636 // -limitfreerelay unit is thousand-bytes-per-minute
637 // At default rate it would take over a month to fill 1GB
638 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
639 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
641 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
646 // Check against previous transactions
647 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
648 if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
650 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
654 // Store transaction in memory
659 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
662 addUnchecked(hash, tx);
665 ///// are we sure this is ok when loading transactions or restoring block txes
666 // If updated, erase old tx from wallet
668 EraseFromWallets(ptxOld->GetHash());
670 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
671 hash.ToString().substr(0,10).c_str(),
676 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
678 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
681 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
683 // Add to memory pool without checking anything. Don't call this directly,
684 // call CTxMemPool::accept to properly check the transaction first.
687 for (unsigned int i = 0; i < tx.vin.size(); i++)
688 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
689 nTransactionsUpdated++;
695 bool CTxMemPool::remove(CTransaction &tx)
697 // Remove transaction from memory pool
700 uint256 hash = tx.GetHash();
701 if (mapTx.count(hash))
703 BOOST_FOREACH(const CTxIn& txin, tx.vin)
704 mapNextTx.erase(txin.prevout);
706 nTransactionsUpdated++;
712 void CTxMemPool::clear()
717 ++nTransactionsUpdated;
720 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
725 vtxid.reserve(mapTx.size());
726 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
727 vtxid.push_back((*mi).first);
733 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
735 if (hashBlock == 0 || nIndex == -1)
738 // Find the block it claims to be in
739 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
740 if (mi == mapBlockIndex.end())
742 CBlockIndex* pindex = (*mi).second;
743 if (!pindex || !pindex->IsInMainChain())
746 // Make sure the merkle branch connects to this block
747 if (!fMerkleVerified)
749 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
751 fMerkleVerified = true;
755 return pindexBest->nHeight - pindex->nHeight + 1;
759 int CMerkleTx::GetBlocksToMaturity() const
763 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
767 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
771 if (!IsInMainChain() && !ClientConnectInputs())
773 return CTransaction::AcceptToMemoryPool(txdb, false);
777 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
781 bool CMerkleTx::AcceptToMemoryPool()
784 return AcceptToMemoryPool(txdb);
789 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
794 // Add previous supporting transactions first
795 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
797 if (!tx.IsCoinBase())
799 uint256 hash = tx.GetHash();
800 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
801 tx.AcceptToMemoryPool(txdb, fCheckInputs);
804 return AcceptToMemoryPool(txdb, fCheckInputs);
809 bool CWalletTx::AcceptWalletTransaction()
812 return AcceptWalletTransaction(txdb);
815 int CTxIndex::GetDepthInMainChain() const
819 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
821 // Find the block in the index
822 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
823 if (mi == mapBlockIndex.end())
825 CBlockIndex* pindex = (*mi).second;
826 if (!pindex || !pindex->IsInMainChain())
828 return 1 + nBestHeight - pindex->nHeight;
831 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
832 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
838 if (mempool.exists(hash))
840 tx = mempool.lookup(hash);
846 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
849 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
850 hashBlock = block.GetHash();
864 //////////////////////////////////////////////////////////////////////////////
866 // CBlock and CBlockIndex
869 static CBlockIndex* pblockindexFBBHLast;
870 CBlockIndex* FindBlockByHeight(int nHeight)
872 CBlockIndex *pblockindex;
873 if (nHeight < nBestHeight / 2)
874 pblockindex = pindexGenesisBlock;
876 pblockindex = pindexBest;
877 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
878 pblockindex = pblockindexFBBHLast;
879 while (pblockindex->nHeight > nHeight)
880 pblockindex = pblockindex->pprev;
881 while (pblockindex->nHeight < nHeight)
882 pblockindex = pblockindex->pnext;
883 pblockindexFBBHLast = pblockindex;
887 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
889 if (!fReadTransactions)
891 *this = pindex->GetBlockHeader();
894 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
896 if (GetHash() != pindex->GetBlockHash())
897 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
901 uint256 static GetOrphanRoot(const CBlock* pblock)
903 // Work back to the first block in the orphan chain
904 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
905 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
906 return pblock->GetHash();
909 int64 static GetBlockValue(int nHeight, int64 nFees)
911 int64 nSubsidy = 50 * COIN;
913 // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
914 nSubsidy >>= (nHeight / 210000);
916 return nSubsidy + nFees;
919 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
920 static const int64 nTargetSpacing = 10 * 60;
921 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
924 // minimum amount of work that could possibly be required nTime after
925 // minimum work required was nBase
927 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
929 // Testnet has min-difficulty blocks
930 // after nTargetSpacing*2 time between blocks:
931 if (fTestNet && nTime > nTargetSpacing*2)
932 return bnProofOfWorkLimit.GetCompact();
935 bnResult.SetCompact(nBase);
936 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
938 // Maximum 400% adjustment...
940 // ... in best-case exactly 4-times-normal target time
941 nTime -= nTargetTimespan*4;
943 if (bnResult > bnProofOfWorkLimit)
944 bnResult = bnProofOfWorkLimit;
945 return bnResult.GetCompact();
948 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
950 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
953 if (pindexLast == NULL)
954 return nProofOfWorkLimit;
956 // Only change once per interval
957 if ((pindexLast->nHeight+1) % nInterval != 0)
959 // Special difficulty rule for testnet:
962 // If the new block's timestamp is more than 2* 10 minutes
963 // then allow mining of a min-difficulty block.
964 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
965 return nProofOfWorkLimit;
968 // Return the last non-special-min-difficulty-rules-block
969 const CBlockIndex* pindex = pindexLast;
970 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
971 pindex = pindex->pprev;
972 return pindex->nBits;
976 return pindexLast->nBits;
979 // Go back by what we want to be 14 days worth of blocks
980 const CBlockIndex* pindexFirst = pindexLast;
981 for (int i = 0; pindexFirst && i < nInterval-1; i++)
982 pindexFirst = pindexFirst->pprev;
985 // Limit adjustment step
986 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
987 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
988 if (nActualTimespan < nTargetTimespan/4)
989 nActualTimespan = nTargetTimespan/4;
990 if (nActualTimespan > nTargetTimespan*4)
991 nActualTimespan = nTargetTimespan*4;
995 bnNew.SetCompact(pindexLast->nBits);
996 bnNew *= nActualTimespan;
997 bnNew /= nTargetTimespan;
999 if (bnNew > bnProofOfWorkLimit)
1000 bnNew = bnProofOfWorkLimit;
1003 printf("GetNextWorkRequired RETARGET\n");
1004 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1005 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1006 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1008 return bnNew.GetCompact();
1011 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1014 bnTarget.SetCompact(nBits);
1017 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1018 return error("CheckProofOfWork() : nBits below minimum work");
1020 // Check proof of work matches claimed amount
1021 if (hash > bnTarget.getuint256())
1022 return error("CheckProofOfWork() : hash doesn't match nBits");
1027 // Return maximum amount of blocks that other nodes claim to have
1028 int GetNumBlocksOfPeers()
1030 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1033 bool IsInitialBlockDownload()
1035 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1037 static int64 nLastUpdate;
1038 static CBlockIndex* pindexLastBest;
1039 if (pindexBest != pindexLastBest)
1041 pindexLastBest = pindexBest;
1042 nLastUpdate = GetTime();
1044 return (GetTime() - nLastUpdate < 10 &&
1045 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1048 void static InvalidChainFound(CBlockIndex* pindexNew)
1050 if (pindexNew->bnChainWork > bnBestInvalidWork)
1052 bnBestInvalidWork = pindexNew->bnChainWork;
1053 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1054 uiInterface.NotifyBlocksChanged();
1056 printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
1057 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1058 pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
1059 pindexNew->GetBlockTime()).c_str());
1060 printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
1061 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1062 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1063 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1064 printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1067 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1069 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1071 // Updating time can change work required on testnet:
1073 nBits = GetNextWorkRequired(pindexPrev, this);
1086 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1088 // Relinquish previous transactions' spent pointers
1091 BOOST_FOREACH(const CTxIn& txin, vin)
1093 COutPoint prevout = txin.prevout;
1095 // Get prev txindex from disk
1097 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1098 return error("DisconnectInputs() : ReadTxIndex failed");
1100 if (prevout.n >= txindex.vSpent.size())
1101 return error("DisconnectInputs() : prevout.n out of range");
1103 // Mark outpoint as not spent
1104 txindex.vSpent[prevout.n].SetNull();
1107 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1108 return error("DisconnectInputs() : UpdateTxIndex failed");
1112 // Remove transaction from index
1113 // This can fail if a duplicate of this transaction was in a chain that got
1114 // reorganized away. This is only possible if this transaction was completely
1115 // spent, so erasing it would be a no-op anyway.
1116 txdb.EraseTxIndex(*this);
1122 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1123 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1125 // FetchInputs can return false either because we just haven't seen some inputs
1126 // (in which case the transaction should be stored as an orphan)
1127 // or because the transaction is malformed (in which case the transaction should
1128 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1132 return true; // Coinbase transactions have no inputs to fetch.
1134 for (unsigned int i = 0; i < vin.size(); i++)
1136 COutPoint prevout = vin[i].prevout;
1137 if (inputsRet.count(prevout.hash))
1138 continue; // Got it already
1141 CTxIndex& txindex = inputsRet[prevout.hash].first;
1143 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1145 // Get txindex from current proposed changes
1146 txindex = mapTestPool.find(prevout.hash)->second;
1150 // Read txindex from txdb
1151 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1153 if (!fFound && (fBlock || fMiner))
1154 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());
1157 CTransaction& txPrev = inputsRet[prevout.hash].second;
1158 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1160 // Get prev tx from single transactions in memory
1163 if (!mempool.exists(prevout.hash))
1164 return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1165 txPrev = mempool.lookup(prevout.hash);
1168 txindex.vSpent.resize(txPrev.vout.size());
1172 // Get prev tx from disk
1173 if (!txPrev.ReadFromDisk(txindex.pos))
1174 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1178 // Make sure all prevout.n indexes are valid:
1179 for (unsigned int i = 0; i < vin.size(); i++)
1181 const COutPoint prevout = vin[i].prevout;
1182 assert(inputsRet.count(prevout.hash) != 0);
1183 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1184 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1185 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1187 // Revisit this if/when transaction replacement is implemented and allows
1190 return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" 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()));
1197 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1199 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1200 if (mi == inputs.end())
1201 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1203 const CTransaction& txPrev = (mi->second).second;
1204 if (input.prevout.n >= txPrev.vout.size())
1205 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1207 return txPrev.vout[input.prevout.n];
1210 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1216 for (unsigned int i = 0; i < vin.size(); i++)
1218 nResult += GetOutputFor(vin[i], inputs).nValue;
1224 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1229 unsigned int nSigOps = 0;
1230 for (unsigned int i = 0; i < vin.size(); i++)
1232 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1233 if (prevout.scriptPubKey.IsPayToScriptHash())
1234 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1239 bool CTransaction::ConnectInputs(MapPrevTx inputs,
1240 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1241 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1243 // Take over previous transactions' spent pointers
1244 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1245 // fMiner is true when called from the internal bitcoin miner
1246 // ... both are false when called from CTransaction::AcceptToMemoryPool
1251 for (unsigned int i = 0; i < vin.size(); i++)
1253 COutPoint prevout = vin[i].prevout;
1254 assert(inputs.count(prevout.hash) > 0);
1255 CTxIndex& txindex = inputs[prevout.hash].first;
1256 CTransaction& txPrev = inputs[prevout.hash].second;
1258 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1259 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" 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()));
1261 // If prev is coinbase, check that it's matured
1262 if (txPrev.IsCoinBase())
1263 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1264 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1265 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1267 // Check for negative or overflow input values
1268 nValueIn += txPrev.vout[prevout.n].nValue;
1269 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1270 return DoS(100, error("ConnectInputs() : txin values out of range"));
1273 // The first loop above does all the inexpensive checks.
1274 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1275 // Helps prevent CPU exhaustion attacks.
1276 for (unsigned int i = 0; i < vin.size(); i++)
1278 COutPoint prevout = vin[i].prevout;
1279 assert(inputs.count(prevout.hash) > 0);
1280 CTxIndex& txindex = inputs[prevout.hash].first;
1281 CTransaction& txPrev = inputs[prevout.hash].second;
1283 // Check for conflicts (double-spend)
1284 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1285 // for an attacker to attempt to split the network.
1286 if (!txindex.vSpent[prevout.n].IsNull())
1287 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());
1289 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1290 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1291 // still computed and checked, and any change will be caught at the next checkpoint.
1292 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1295 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1297 // only during transition phase for P2SH: do not invoke anti-DoS code for
1298 // potentially old clients relaying bad P2SH transactions
1299 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1300 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1302 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1306 // Mark outpoints as spent
1307 txindex.vSpent[prevout.n] = posThisTx;
1310 if (fBlock || fMiner)
1312 mapTestPool[prevout.hash] = txindex;
1316 if (nValueIn < GetValueOut())
1317 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1319 // Tally transaction fees
1320 int64 nTxFee = nValueIn - GetValueOut();
1322 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1324 if (!MoneyRange(nFees))
1325 return DoS(100, error("ConnectInputs() : nFees out of range"));
1332 bool CTransaction::ClientConnectInputs()
1337 // Take over previous transactions' spent pointers
1341 for (unsigned int i = 0; i < vin.size(); i++)
1343 // Get prev tx from single transactions in memory
1344 COutPoint prevout = vin[i].prevout;
1345 if (!mempool.exists(prevout.hash))
1347 CTransaction& txPrev = mempool.lookup(prevout.hash);
1349 if (prevout.n >= txPrev.vout.size())
1353 if (!VerifySignature(txPrev, *this, i, true, 0))
1354 return error("ConnectInputs() : VerifySignature failed");
1356 ///// this is redundant with the mempool.mapNextTx stuff,
1357 ///// not sure which I want to get rid of
1358 ///// this has to go away now that posNext is gone
1359 // // Check for conflicts
1360 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1361 // return error("ConnectInputs() : prev tx already used");
1363 // // Flag outpoints as used
1364 // txPrev.vout[prevout.n].posNext = posThisTx;
1366 nValueIn += txPrev.vout[prevout.n].nValue;
1368 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1369 return error("ClientConnectInputs() : txin values out of range");
1371 if (GetValueOut() > nValueIn)
1381 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1383 // Disconnect in reverse order
1384 for (int i = vtx.size()-1; i >= 0; i--)
1385 if (!vtx[i].DisconnectInputs(txdb))
1388 // Update block index on disk without changing it in memory.
1389 // The memory index structure will be changed after the db commits.
1392 CDiskBlockIndex blockindexPrev(pindex->pprev);
1393 blockindexPrev.hashNext = 0;
1394 if (!txdb.WriteBlockIndex(blockindexPrev))
1395 return error("DisconnectBlock() : WriteBlockIndex failed");
1401 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1403 // Check it again in case a previous version let a bad block in
1404 if (!CheckBlock(!fJustCheck, !fJustCheck))
1407 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1408 // unless those are already completely spent.
1409 // If such overwrites are allowed, coinbases and transactions depending upon those
1410 // can be duplicated to remove the ability to spend the first instance -- even after
1411 // being sent to another address.
1412 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1413 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1414 // already refuses previously-known transaction ids entirely.
1415 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1416 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1417 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1418 // initial block download.
1419 bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1420 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1422 // BIP16 didn't become active until Apr 1 2012
1423 int64 nBIP16SwitchTime = 1333238400;
1424 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1426 //// issue here: it doesn't know the version
1427 unsigned int nTxPos;
1429 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1430 // Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
1433 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
1435 map<uint256, CTxIndex> mapQueuedChanges;
1437 unsigned int nSigOps = 0;
1438 BOOST_FOREACH(CTransaction& tx, vtx)
1440 uint256 hashTx = tx.GetHash();
1442 if (fEnforceBIP30) {
1443 CTxIndex txindexOld;
1444 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1445 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1451 nSigOps += tx.GetLegacySigOpCount();
1452 if (nSigOps > MAX_BLOCK_SIGOPS)
1453 return DoS(100, error("ConnectBlock() : too many sigops"));
1455 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1457 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1459 MapPrevTx mapInputs;
1460 if (!tx.IsCoinBase())
1463 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1466 if (fStrictPayToScriptHash)
1468 // Add in sigops done by pay-to-script-hash inputs;
1469 // this is to prevent a "rogue miner" from creating
1470 // an incredibly-expensive-to-validate block.
1471 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1472 if (nSigOps > MAX_BLOCK_SIGOPS)
1473 return DoS(100, error("ConnectBlock() : too many sigops"));
1476 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1478 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1482 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1485 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1491 // Write queued txindex changes
1492 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1494 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1495 return error("ConnectBlock() : UpdateTxIndex failed");
1498 // Update block index on disk without changing it in memory.
1499 // The memory index structure will be changed after the db commits.
1502 CDiskBlockIndex blockindexPrev(pindex->pprev);
1503 blockindexPrev.hashNext = pindex->GetBlockHash();
1504 if (!txdb.WriteBlockIndex(blockindexPrev))
1505 return error("ConnectBlock() : WriteBlockIndex failed");
1508 // Watch for transactions paying to me
1509 BOOST_FOREACH(CTransaction& tx, vtx)
1510 SyncWithWallets(tx, this, true);
1515 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1517 printf("REORGANIZE\n");
1520 CBlockIndex* pfork = pindexBest;
1521 CBlockIndex* plonger = pindexNew;
1522 while (pfork != plonger)
1524 while (plonger->nHeight > pfork->nHeight)
1525 if (!(plonger = plonger->pprev))
1526 return error("Reorganize() : plonger->pprev is null");
1527 if (pfork == plonger)
1529 if (!(pfork = pfork->pprev))
1530 return error("Reorganize() : pfork->pprev is null");
1533 // List of what to disconnect
1534 vector<CBlockIndex*> vDisconnect;
1535 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1536 vDisconnect.push_back(pindex);
1538 // List of what to connect
1539 vector<CBlockIndex*> vConnect;
1540 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1541 vConnect.push_back(pindex);
1542 reverse(vConnect.begin(), vConnect.end());
1544 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1545 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1547 // Disconnect shorter branch
1548 vector<CTransaction> vResurrect;
1549 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1552 if (!block.ReadFromDisk(pindex))
1553 return error("Reorganize() : ReadFromDisk for disconnect failed");
1554 if (!block.DisconnectBlock(txdb, pindex))
1555 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1557 // Queue memory transactions to resurrect
1558 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1559 if (!tx.IsCoinBase())
1560 vResurrect.push_back(tx);
1563 // Connect longer branch
1564 vector<CTransaction> vDelete;
1565 for (unsigned int i = 0; i < vConnect.size(); i++)
1567 CBlockIndex* pindex = vConnect[i];
1569 if (!block.ReadFromDisk(pindex))
1570 return error("Reorganize() : ReadFromDisk for connect failed");
1571 if (!block.ConnectBlock(txdb, pindex))
1574 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1577 // Queue memory transactions to delete
1578 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1579 vDelete.push_back(tx);
1581 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1582 return error("Reorganize() : WriteHashBestChain failed");
1584 // Make sure it's successfully written to disk before changing memory structure
1585 if (!txdb.TxnCommit())
1586 return error("Reorganize() : TxnCommit failed");
1588 // Disconnect shorter branch
1589 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1591 pindex->pprev->pnext = NULL;
1593 // Connect longer branch
1594 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1596 pindex->pprev->pnext = pindex;
1598 // Resurrect memory transactions that were in the disconnected branch
1599 BOOST_FOREACH(CTransaction& tx, vResurrect)
1600 tx.AcceptToMemoryPool(txdb, false);
1602 // Delete redundant memory transactions that are in the connected branch
1603 BOOST_FOREACH(CTransaction& tx, vDelete)
1606 printf("REORGANIZE: done\n");
1612 // Called from inside SetBestChain: attaches a block to the new best chain being built
1613 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1615 uint256 hash = GetHash();
1617 // Adding to current best branch
1618 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1621 InvalidChainFound(pindexNew);
1624 if (!txdb.TxnCommit())
1625 return error("SetBestChain() : TxnCommit failed");
1627 // Add to current best branch
1628 pindexNew->pprev->pnext = pindexNew;
1630 // Delete redundant memory transactions
1631 BOOST_FOREACH(CTransaction& tx, vtx)
1637 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1639 uint256 hash = GetHash();
1641 if (!txdb.TxnBegin())
1642 return error("SetBestChain() : TxnBegin failed");
1644 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1646 txdb.WriteHashBestChain(hash);
1647 if (!txdb.TxnCommit())
1648 return error("SetBestChain() : TxnCommit failed");
1649 pindexGenesisBlock = pindexNew;
1651 else if (hashPrevBlock == hashBestChain)
1653 if (!SetBestChainInner(txdb, pindexNew))
1654 return error("SetBestChain() : SetBestChainInner failed");
1658 // the first block in the new chain that will cause it to become the new best chain
1659 CBlockIndex *pindexIntermediate = pindexNew;
1661 // list of blocks that need to be connected afterwards
1662 std::vector<CBlockIndex*> vpindexSecondary;
1664 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1665 // Try to limit how much needs to be done inside
1666 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
1668 vpindexSecondary.push_back(pindexIntermediate);
1669 pindexIntermediate = pindexIntermediate->pprev;
1672 if (!vpindexSecondary.empty())
1673 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1675 // Switch to new best branch
1676 if (!Reorganize(txdb, pindexIntermediate))
1679 InvalidChainFound(pindexNew);
1680 return error("SetBestChain() : Reorganize failed");
1683 // Connect further blocks
1684 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1687 if (!block.ReadFromDisk(pindex))
1689 printf("SetBestChain() : ReadFromDisk failed\n");
1692 if (!txdb.TxnBegin()) {
1693 printf("SetBestChain() : TxnBegin 2 failed\n");
1696 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1697 if (!block.SetBestChainInner(txdb, pindex))
1702 // Update best block in wallet (so we can detect restored wallets)
1703 bool fIsInitialDownload = IsInitialBlockDownload();
1704 if (!fIsInitialDownload)
1706 const CBlockLocator locator(pindexNew);
1707 ::SetBestChain(locator);
1711 hashBestChain = hash;
1712 pindexBest = pindexNew;
1713 pblockindexFBBHLast = NULL;
1714 nBestHeight = pindexBest->nHeight;
1715 bnBestChainWork = pindexNew->bnChainWork;
1716 nTimeBestReceived = GetTime();
1717 nTransactionsUpdated++;
1718 printf("SetBestChain: new best=%s height=%d work=%s date=%s\n",
1719 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1720 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1722 // Check the version of the last 100 blocks to see if we need to upgrade:
1723 if (!fIsInitialDownload)
1726 const CBlockIndex* pindex = pindexBest;
1727 for (int i = 0; i < 100 && pindex != NULL; i++)
1729 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1731 pindex = pindex->pprev;
1734 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1735 if (nUpgraded > 100/2)
1736 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1737 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1740 std::string strCmd = GetArg("-blocknotify", "");
1742 if (!fIsInitialDownload && !strCmd.empty())
1744 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1745 boost::thread t(runCommand, strCmd); // thread runs free
1752 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1754 // Check for duplicate
1755 uint256 hash = GetHash();
1756 if (mapBlockIndex.count(hash))
1757 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1759 // Construct new block index object
1760 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1762 return error("AddToBlockIndex() : new CBlockIndex failed");
1763 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1764 pindexNew->phashBlock = &((*mi).first);
1765 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1766 if (miPrev != mapBlockIndex.end())
1768 pindexNew->pprev = (*miPrev).second;
1769 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1771 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1774 if (!txdb.TxnBegin())
1776 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1777 if (!txdb.TxnCommit())
1781 if (pindexNew->bnChainWork > bnBestChainWork)
1782 if (!SetBestChain(txdb, pindexNew))
1787 if (pindexNew == pindexBest)
1789 // Notify UI to display prev block's coinbase if it was ours
1790 static uint256 hashPrevBestCoinBase;
1791 UpdatedTransaction(hashPrevBestCoinBase);
1792 hashPrevBestCoinBase = vtx[0].GetHash();
1795 uiInterface.NotifyBlocksChanged();
1802 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
1804 // These are checks that are independent of context
1805 // that can be verified before saving an orphan block.
1808 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1809 return DoS(100, error("CheckBlock() : size limits failed"));
1811 // Check proof of work matches claimed amount
1812 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
1813 return DoS(50, error("CheckBlock() : proof of work failed"));
1816 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1817 return error("CheckBlock() : block timestamp too far in the future");
1819 // First transaction must be coinbase, the rest must not be
1820 if (vtx.empty() || !vtx[0].IsCoinBase())
1821 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1822 for (unsigned int i = 1; i < vtx.size(); i++)
1823 if (vtx[i].IsCoinBase())
1824 return DoS(100, error("CheckBlock() : more than one coinbase"));
1826 // Check transactions
1827 BOOST_FOREACH(const CTransaction& tx, vtx)
1828 if (!tx.CheckTransaction())
1829 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1831 // Check for duplicate txids. This is caught by ConnectInputs(),
1832 // but catching it earlier avoids a potential DoS attack:
1833 set<uint256> uniqueTx;
1834 BOOST_FOREACH(const CTransaction& tx, vtx)
1836 uniqueTx.insert(tx.GetHash());
1838 if (uniqueTx.size() != vtx.size())
1839 return DoS(100, error("CheckBlock() : duplicate transaction"));
1841 unsigned int nSigOps = 0;
1842 BOOST_FOREACH(const CTransaction& tx, vtx)
1844 nSigOps += tx.GetLegacySigOpCount();
1846 if (nSigOps > MAX_BLOCK_SIGOPS)
1847 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1849 // Check merkle root
1850 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
1851 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1856 bool CBlock::AcceptBlock()
1858 // Check for duplicate
1859 uint256 hash = GetHash();
1860 if (mapBlockIndex.count(hash))
1861 return error("AcceptBlock() : block already in mapBlockIndex");
1863 // Get prev block index
1864 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1865 if (mi == mapBlockIndex.end())
1866 return DoS(10, error("AcceptBlock() : prev block not found"));
1867 CBlockIndex* pindexPrev = (*mi).second;
1868 int nHeight = pindexPrev->nHeight+1;
1870 // Check proof of work
1871 if (nBits != GetNextWorkRequired(pindexPrev, this))
1872 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1874 // Check timestamp against prev
1875 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1876 return error("AcceptBlock() : block's timestamp is too early");
1878 // Check that all transactions are finalized
1879 BOOST_FOREACH(const CTransaction& tx, vtx)
1880 if (!tx.IsFinal(nHeight, GetBlockTime()))
1881 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1883 // Check that the block chain matches the known block chain up to a checkpoint
1884 if (!Checkpoints::CheckBlock(nHeight, hash))
1885 return DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
1887 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
1890 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
1891 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
1893 return error("AcceptBlock() : rejected nVersion=1 block");
1896 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
1899 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
1900 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
1901 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
1903 CScript expect = CScript() << nHeight;
1904 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
1905 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
1909 // Write block to history file
1910 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1911 return error("AcceptBlock() : out of disk space");
1912 unsigned int nFile = -1;
1913 unsigned int nBlockPos = 0;
1914 if (!WriteToDisk(nFile, nBlockPos))
1915 return error("AcceptBlock() : WriteToDisk failed");
1916 if (!AddToBlockIndex(nFile, nBlockPos))
1917 return error("AcceptBlock() : AddToBlockIndex failed");
1919 // Relay inventory, but don't relay old inventory during initial block download
1920 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1921 if (hashBestChain == hash)
1924 BOOST_FOREACH(CNode* pnode, vNodes)
1925 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1926 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1932 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
1934 unsigned int nFound = 0;
1935 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
1937 if (pstart->nVersion >= minVersion)
1939 pstart = pstart->pprev;
1941 return (nFound >= nRequired);
1944 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1946 // Check for duplicate
1947 uint256 hash = pblock->GetHash();
1948 if (mapBlockIndex.count(hash))
1949 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1950 if (mapOrphanBlocks.count(hash))
1951 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1953 // Preliminary checks
1954 if (!pblock->CheckBlock())
1955 return error("ProcessBlock() : CheckBlock FAILED");
1957 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1958 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1960 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1961 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1965 pfrom->Misbehaving(100);
1966 return error("ProcessBlock() : block with timestamp before last checkpoint");
1969 bnNewBlock.SetCompact(pblock->nBits);
1971 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1972 if (bnNewBlock > bnRequired)
1975 pfrom->Misbehaving(100);
1976 return error("ProcessBlock() : block with too little proof-of-work");
1981 // If we don't already have its previous block, shunt it off to holding area until we get it
1982 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1984 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1986 // Accept orphans as long as there is a node to request its parents from
1988 CBlock* pblock2 = new CBlock(*pblock);
1989 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1990 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1992 // Ask this guy to fill in what we're missing
1993 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1999 if (!pblock->AcceptBlock())
2000 return error("ProcessBlock() : AcceptBlock FAILED");
2002 // Recursively process any orphan blocks that depended on this one
2003 vector<uint256> vWorkQueue;
2004 vWorkQueue.push_back(hash);
2005 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2007 uint256 hashPrev = vWorkQueue[i];
2008 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2009 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2012 CBlock* pblockOrphan = (*mi).second;
2013 if (pblockOrphan->AcceptBlock())
2014 vWorkQueue.push_back(pblockOrphan->GetHash());
2015 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2016 delete pblockOrphan;
2018 mapOrphanBlocksByPrev.erase(hashPrev);
2021 printf("ProcessBlock: ACCEPTED\n");
2032 bool CheckDiskSpace(uint64 nAdditionalBytes)
2034 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2036 // Check for nMinDiskSpace bytes (currently 50MB)
2037 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2040 string strMessage = _("Warning: Disk space is low!");
2041 strMiscWarning = strMessage;
2042 printf("*** %s\n", strMessage.c_str());
2043 uiInterface.ThreadSafeMessageBox(strMessage, "Bitcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2050 static filesystem::path BlockFilePath(unsigned int nFile)
2052 string strBlockFn = strprintf("blk%04u.dat", nFile);
2053 return GetDataDir() / strBlockFn;
2056 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2058 if ((nFile < 1) || (nFile == (unsigned int) -1))
2060 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2063 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2065 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2074 static unsigned int nCurrentBlockFile = 1;
2076 FILE* AppendBlockFile(unsigned int& nFileRet)
2081 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2084 if (fseek(file, 0, SEEK_END) != 0)
2086 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2087 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2089 nFileRet = nCurrentBlockFile;
2093 nCurrentBlockFile++;
2097 bool LoadBlockIndex(bool fAllowNew)
2101 pchMessageStart[0] = 0x0b;
2102 pchMessageStart[1] = 0x11;
2103 pchMessageStart[2] = 0x09;
2104 pchMessageStart[3] = 0x07;
2105 hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
2112 if (!txdb.LoadBlockIndex())
2117 // Init with genesis block
2119 if (mapBlockIndex.empty())
2125 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2126 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2127 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2128 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2129 // vMerkleTree: 4a5e1e
2132 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
2134 txNew.vin.resize(1);
2135 txNew.vout.resize(1);
2136 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2137 txNew.vout[0].nValue = 50 * COIN;
2138 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
2140 block.vtx.push_back(txNew);
2141 block.hashPrevBlock = 0;
2142 block.hashMerkleRoot = block.BuildMerkleTree();
2144 block.nTime = 1231006505;
2145 block.nBits = 0x1d00ffff;
2146 block.nNonce = 2083236893;
2150 block.nTime = 1296688602;
2151 block.nNonce = 414098458;
2155 printf("%s\n", block.GetHash().ToString().c_str());
2156 printf("%s\n", hashGenesisBlock.ToString().c_str());
2157 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2158 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2160 assert(block.GetHash() == hashGenesisBlock);
2162 // Start new block file
2164 unsigned int nBlockPos;
2165 if (!block.WriteToDisk(nFile, nBlockPos))
2166 return error("LoadBlockIndex() : writing genesis block to disk failed");
2167 if (!block.AddToBlockIndex(nFile, nBlockPos))
2168 return error("LoadBlockIndex() : genesis block not accepted");
2176 void PrintBlockTree()
2178 // pre-compute tree structure
2179 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2180 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2182 CBlockIndex* pindex = (*mi).second;
2183 mapNext[pindex->pprev].push_back(pindex);
2185 //while (rand() % 3 == 0)
2186 // mapNext[pindex->pprev].push_back(pindex);
2189 vector<pair<int, CBlockIndex*> > vStack;
2190 vStack.push_back(make_pair(0, pindexGenesisBlock));
2193 while (!vStack.empty())
2195 int nCol = vStack.back().first;
2196 CBlockIndex* pindex = vStack.back().second;
2199 // print split or gap
2200 if (nCol > nPrevCol)
2202 for (int i = 0; i < nCol-1; i++)
2206 else if (nCol < nPrevCol)
2208 for (int i = 0; i < nCol; i++)
2215 for (int i = 0; i < nCol; i++)
2220 block.ReadFromDisk(pindex);
2221 printf("%d (%u,%u) %s %s tx %"PRIszu"",
2225 block.GetHash().ToString().substr(0,20).c_str(),
2226 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2229 PrintWallets(block);
2231 // put the main time-chain first
2232 vector<CBlockIndex*>& vNext = mapNext[pindex];
2233 for (unsigned int i = 0; i < vNext.size(); i++)
2235 if (vNext[i]->pnext)
2237 swap(vNext[0], vNext[i]);
2243 for (unsigned int i = 0; i < vNext.size(); i++)
2244 vStack.push_back(make_pair(nCol+i, vNext[i]));
2248 bool LoadExternalBlockFile(FILE* fileIn)
2250 int64 nStart = GetTimeMillis();
2256 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2257 unsigned int nPos = 0;
2258 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2260 unsigned char pchData[65536];
2262 fseek(blkdat, nPos, SEEK_SET);
2263 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2266 nPos = (unsigned int)-1;
2269 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2272 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2274 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2277 nPos += ((unsigned char*)nFind - pchData) + 1;
2280 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2281 } while(!fRequestShutdown);
2282 if (nPos == (unsigned int)-1)
2284 fseek(blkdat, nPos, SEEK_SET);
2287 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2291 if (ProcessBlock(NULL,&block))
2299 catch (std::exception &e) {
2300 printf("%s() : Deserialize or I/O error caught during load\n",
2301 __PRETTY_FUNCTION__);
2304 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2316 //////////////////////////////////////////////////////////////////////////////
2321 extern map<uint256, CAlert> mapAlerts;
2322 extern CCriticalSection cs_mapAlerts;
2324 string GetWarnings(string strFor)
2327 string strStatusBar;
2329 if (GetBoolArg("-testsafemode"))
2332 // Misc warnings like out of disk space and clock is wrong
2333 if (strMiscWarning != "")
2336 strStatusBar = strMiscWarning;
2339 // Longer invalid proof-of-work chain
2340 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2343 strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
2349 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2351 const CAlert& alert = item.second;
2352 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2354 nPriority = alert.nPriority;
2355 strStatusBar = alert.strStatusBar;
2360 if (strFor == "statusbar")
2361 return strStatusBar;
2362 else if (strFor == "rpc")
2364 assert(!"GetWarnings() : invalid parameter");
2375 //////////////////////////////////////////////////////////////////////////////
2381 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2387 bool txInMap = false;
2390 txInMap = (mempool.exists(inv.hash));
2393 mapOrphanTransactions.count(inv.hash) ||
2394 txdb.ContainsTx(inv.hash);
2398 return mapBlockIndex.count(inv.hash) ||
2399 mapOrphanBlocks.count(inv.hash);
2401 // Don't know what it is, just say we already got one
2407 static bool NodeRecentlyStarted()
2409 extern int64 nTimeNodeStart;
2410 int64 timediff = GetTime() - nTimeNodeStart;
2412 return (timediff < (2 * 60 * 60));
2416 // The message start string is designed to be unlikely to occur in normal data.
2417 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2418 // a large 4-byte int at any alignment.
2419 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2422 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2424 static map<CService, CPubKey> mapReuseKey;
2425 RandAddSeedPerfmon();
2427 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
2428 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2430 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2438 if (strCommand == "version")
2440 // Each connection can only send one version message
2441 if (pfrom->nVersion != 0)
2443 pfrom->Misbehaving(1);
2451 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2452 if (pfrom->nVersion < MIN_PROTO_VERSION)
2454 // Since February 20, 2012, the protocol is initiated at version 209,
2455 // and earlier versions are no longer supported
2456 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2457 pfrom->fDisconnect = true;
2461 if (pfrom->nVersion == 10300)
2462 pfrom->nVersion = 300;
2464 vRecv >> addrFrom >> nNonce;
2466 vRecv >> pfrom->strSubVer;
2468 vRecv >> pfrom->nStartingHeight;
2470 if (pfrom->fInbound && addrMe.IsRoutable())
2472 pfrom->addrLocal = addrMe;
2476 // Disconnect if we connected to ourself
2477 if (nNonce == nLocalHostNonce && nNonce > 1)
2479 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2480 pfrom->fDisconnect = true;
2484 // Be shy and don't send version until we hear
2485 if (pfrom->fInbound)
2486 pfrom->PushVersion();
2488 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2490 AddTimeData(pfrom->addr, nTime);
2493 pfrom->PushMessage("verack");
2494 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2496 if (!pfrom->fInbound)
2498 // Advertise our address
2499 if (!fNoListen && !IsInitialBlockDownload())
2501 CAddress addr = GetLocalAddress(&pfrom->addr);
2502 if (addr.IsRoutable())
2503 pfrom->PushAddress(addr);
2506 // Get recent addresses
2507 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2509 pfrom->PushMessage("getaddr");
2510 pfrom->fGetAddr = true;
2512 addrman.Good(pfrom->addr);
2514 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2516 addrman.Add(addrFrom, addrFrom);
2517 addrman.Good(addrFrom);
2521 // Trigger download of remote node's memory pool
2522 if (!IsInitialBlockDownload() && !pfrom->fInbound &&
2523 !pfrom->fClient && NodeRecentlyStarted() &&
2524 pfrom->nVersion >= MEMPOOL_GD_VERSION)
2525 pfrom->PushMessage("mempool");
2527 // Ask the first connected node for block updates
2528 static int nAskedForBlocks = 0;
2529 if (!pfrom->fClient && !pfrom->fOneShot &&
2530 (pfrom->nVersion < NOBLKS_VERSION_START ||
2531 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2532 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2535 pfrom->PushGetBlocks(pindexBest, uint256(0));
2541 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2542 item.second.RelayTo(pfrom);
2545 pfrom->fSuccessfullyConnected = true;
2547 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
2549 cPeerBlockCounts.input(pfrom->nStartingHeight);
2553 else if (pfrom->nVersion == 0)
2555 // Must have a version message before anything else
2556 pfrom->Misbehaving(1);
2561 else if (strCommand == "verack")
2563 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2567 else if (strCommand == "addr")
2569 vector<CAddress> vAddr;
2572 // Don't want addr from older versions unless seeding
2573 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2575 if (vAddr.size() > 1000)
2577 pfrom->Misbehaving(20);
2578 return error("message addr size() = %"PRIszu"", vAddr.size());
2581 // Store the new addresses
2582 vector<CAddress> vAddrOk;
2583 int64 nNow = GetAdjustedTime();
2584 int64 nSince = nNow - 10 * 60;
2585 BOOST_FOREACH(CAddress& addr, vAddr)
2589 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2590 addr.nTime = nNow - 5 * 24 * 60 * 60;
2591 pfrom->AddAddressKnown(addr);
2592 bool fReachable = IsReachable(addr);
2593 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2595 // Relay to a limited number of other nodes
2598 // Use deterministic randomness to send to the same nodes for 24 hours
2599 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2600 static uint256 hashSalt;
2602 hashSalt = GetRandHash();
2603 uint64 hashAddr = addr.GetHash();
2604 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2605 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2606 multimap<uint256, CNode*> mapMix;
2607 BOOST_FOREACH(CNode* pnode, vNodes)
2609 if (pnode->nVersion < CADDR_TIME_VERSION)
2611 unsigned int nPointer;
2612 memcpy(&nPointer, &pnode, sizeof(nPointer));
2613 uint256 hashKey = hashRand ^ nPointer;
2614 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2615 mapMix.insert(make_pair(hashKey, pnode));
2617 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
2618 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2619 ((*mi).second)->PushAddress(addr);
2622 // Do not store addresses outside our network
2624 vAddrOk.push_back(addr);
2626 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
2627 if (vAddr.size() < 1000)
2628 pfrom->fGetAddr = false;
2629 if (pfrom->fOneShot)
2630 pfrom->fDisconnect = true;
2634 else if (strCommand == "inv")
2638 if (vInv.size() > MAX_INV_SZ)
2640 pfrom->Misbehaving(20);
2641 return error("message inv size() = %"PRIszu"", vInv.size());
2644 // find last block in inv vector
2645 unsigned int nLastBlock = (unsigned int)(-1);
2646 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2647 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2648 nLastBlock = vInv.size() - 1 - nInv;
2653 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2655 const CInv &inv = vInv[nInv];
2659 pfrom->AddInventoryKnown(inv);
2661 bool fAlreadyHave = AlreadyHave(txdb, inv);
2663 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2667 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2668 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2669 } else if (nInv == nLastBlock) {
2670 // In case we are on a very long side-chain, it is possible that we already have
2671 // the last block in an inv bundle sent in response to getblocks. Try to detect
2672 // this situation and push another getblocks to continue.
2673 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2675 printf("force request: %s\n", inv.ToString().c_str());
2678 // Track requests for our stuff
2679 Inventory(inv.hash);
2684 else if (strCommand == "getdata")
2688 if (vInv.size() > MAX_INV_SZ)
2690 pfrom->Misbehaving(20);
2691 return error("message getdata size() = %"PRIszu"", vInv.size());
2694 if (fDebugNet || (vInv.size() != 1))
2695 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
2697 BOOST_FOREACH(const CInv& inv, vInv)
2701 if (fDebugNet || (vInv.size() == 1))
2702 printf("received getdata for: %s\n", inv.ToString().c_str());
2704 if (inv.type == MSG_BLOCK)
2706 // Send block from disk
2707 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2708 if (mi != mapBlockIndex.end())
2711 block.ReadFromDisk((*mi).second);
2712 pfrom->PushMessage("block", block);
2714 // Trigger them to send a getblocks request for the next batch of inventory
2715 if (inv.hash == pfrom->hashContinue)
2717 // Bypass PushInventory, this must send even if redundant,
2718 // and we want it right after the last block so they don't
2719 // wait for other stuff first.
2721 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2722 pfrom->PushMessage("inv", vInv);
2723 pfrom->hashContinue = 0;
2727 else if (inv.IsKnownType())
2729 // Send stream from relay memory
2730 bool pushed = false;
2733 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2734 if (mi != mapRelay.end()) {
2735 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2739 if (!pushed && inv.type == MSG_TX) {
2741 if (mempool.exists(inv.hash)) {
2742 CTransaction tx = mempool.lookup(inv.hash);
2743 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2746 pfrom->PushMessage("tx", ss);
2751 // Track requests for our stuff
2752 Inventory(inv.hash);
2757 else if (strCommand == "getblocks")
2759 CBlockLocator locator;
2761 vRecv >> locator >> hashStop;
2763 // Find the last block the caller has in the main chain
2764 CBlockIndex* pindex = locator.GetBlockIndex();
2766 // Send the rest of the chain
2768 pindex = pindex->pnext;
2770 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2771 for (; pindex; pindex = pindex->pnext)
2773 if (pindex->GetBlockHash() == hashStop)
2775 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2778 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2781 // When this block is requested, we'll send an inv that'll make them
2782 // getblocks the next batch of inventory.
2783 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2784 pfrom->hashContinue = pindex->GetBlockHash();
2791 else if (strCommand == "getheaders")
2793 CBlockLocator locator;
2795 vRecv >> locator >> hashStop;
2797 CBlockIndex* pindex = NULL;
2798 if (locator.IsNull())
2800 // If locator is null, return the hashStop block
2801 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2802 if (mi == mapBlockIndex.end())
2804 pindex = (*mi).second;
2808 // Find the last block the caller has in the main chain
2809 pindex = locator.GetBlockIndex();
2811 pindex = pindex->pnext;
2814 vector<CBlock> vHeaders;
2816 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2817 for (; pindex; pindex = pindex->pnext)
2819 vHeaders.push_back(pindex->GetBlockHeader());
2820 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2823 pfrom->PushMessage("headers", vHeaders);
2827 else if (strCommand == "tx")
2829 vector<uint256> vWorkQueue;
2830 vector<uint256> vEraseQueue;
2831 CDataStream vMsg(vRecv);
2836 CInv inv(MSG_TX, tx.GetHash());
2837 pfrom->AddInventoryKnown(inv);
2839 bool fMissingInputs = false;
2840 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2842 SyncWithWallets(tx, NULL, true);
2843 RelayMessage(inv, vMsg);
2844 mapAlreadyAskedFor.erase(inv);
2845 vWorkQueue.push_back(inv.hash);
2846 vEraseQueue.push_back(inv.hash);
2848 // Recursively process any orphan transactions that depended on this one
2849 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2851 uint256 hashPrev = vWorkQueue[i];
2852 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
2853 mi != mapOrphanTransactionsByPrev[hashPrev].end();
2856 const CDataStream& vMsg = *((*mi).second);
2858 CDataStream(vMsg) >> tx;
2859 CInv inv(MSG_TX, tx.GetHash());
2860 bool fMissingInputs2 = false;
2862 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
2864 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2865 SyncWithWallets(tx, NULL, true);
2866 RelayMessage(inv, vMsg);
2867 mapAlreadyAskedFor.erase(inv);
2868 vWorkQueue.push_back(inv.hash);
2869 vEraseQueue.push_back(inv.hash);
2871 else if (!fMissingInputs2)
2874 vEraseQueue.push_back(inv.hash);
2875 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2880 BOOST_FOREACH(uint256 hash, vEraseQueue)
2881 EraseOrphanTx(hash);
2883 else if (fMissingInputs)
2887 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2888 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2890 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
2892 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2896 else if (strCommand == "block")
2901 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2904 CInv inv(MSG_BLOCK, block.GetHash());
2905 pfrom->AddInventoryKnown(inv);
2907 if (ProcessBlock(pfrom, &block))
2908 mapAlreadyAskedFor.erase(inv);
2909 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2913 else if (strCommand == "getaddr")
2915 pfrom->vAddrToSend.clear();
2916 vector<CAddress> vAddr = addrman.GetAddr();
2917 BOOST_FOREACH(const CAddress &addr, vAddr)
2918 pfrom->PushAddress(addr);
2922 else if (strCommand == "mempool")
2924 std::vector<uint256> vtxid;
2925 mempool.queryHashes(vtxid);
2927 for (unsigned int i = 0; i < vtxid.size(); i++) {
2928 CInv inv(MSG_TX, vtxid[i]);
2929 vInv.push_back(inv);
2930 if (i == (MAX_INV_SZ - 1))
2933 if (vInv.size() > 0)
2934 pfrom->PushMessage("inv", vInv);
2938 else if (strCommand == "checkorder")
2943 if (!GetBoolArg("-allowreceivebyip"))
2945 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2952 /// we have a chance to check the order here
2954 // Keep giving the same key to the same ip until they use it
2955 if (!mapReuseKey.count(pfrom->addr))
2956 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2958 // Send back approval of order and pubkey to use
2959 CScript scriptPubKey;
2960 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2961 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2965 else if (strCommand == "reply")
2970 CRequestTracker tracker;
2972 LOCK(pfrom->cs_mapRequests);
2973 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2974 if (mi != pfrom->mapRequests.end())
2976 tracker = (*mi).second;
2977 pfrom->mapRequests.erase(mi);
2980 if (!tracker.IsNull())
2981 tracker.fn(tracker.param1, vRecv);
2985 else if (strCommand == "ping")
2987 if (pfrom->nVersion > BIP0031_VERSION)
2991 // Echo the message back with the nonce. This allows for two useful features:
2993 // 1) A remote node can quickly check if the connection is operational
2994 // 2) Remote nodes can measure the latency of the network thread. If this node
2995 // is overloaded it won't respond to pings quickly and the remote node can
2996 // avoid sending us more work, like chain download requests.
2998 // The nonce stops the remote getting confused between different pings: without
2999 // it, if the remote node sends a ping once per second and this node takes 5
3000 // seconds to respond to each, the 5th ping the remote sends would appear to
3001 // return very quickly.
3002 pfrom->PushMessage("pong", nonce);
3007 else if (strCommand == "alert")
3012 uint256 alertHash = alert.GetHash();
3013 if (pfrom->setKnown.count(alertHash) == 0)
3015 if (alert.ProcessAlert())
3018 pfrom->setKnown.insert(alertHash);
3021 BOOST_FOREACH(CNode* pnode, vNodes)
3022 alert.RelayTo(pnode);
3026 // Small DoS penalty so peers that send us lots of
3027 // duplicate/expired/invalid-signature/whatever alerts
3028 // eventually get banned.
3029 // This isn't a Misbehaving(100) (immediate ban) because the
3030 // peer might be an older or different implementation with
3031 // a different signature key, etc.
3032 pfrom->Misbehaving(10);
3040 // Ignore unknown commands for extensibility
3044 // Update the last seen time for this node's address
3045 if (pfrom->fNetworkNode)
3046 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3047 AddressCurrentlyConnected(pfrom->addr);
3053 bool ProcessMessages(CNode* pfrom)
3055 CDataStream& vRecv = pfrom->vRecv;
3059 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3063 // (4) message start
3072 // Don't bother if send buffer is too full to respond anyway
3073 if (pfrom->vSend.size() >= SendBufferSize())
3076 // Scan for message start
3077 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3078 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3079 if (vRecv.end() - pstart < nHeaderSize)
3081 if ((int)vRecv.size() > nHeaderSize)
3083 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3084 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3088 if (pstart - vRecv.begin() > 0)
3089 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3090 vRecv.erase(vRecv.begin(), pstart);
3093 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3098 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3101 string strCommand = hdr.GetCommand();
3104 unsigned int nMessageSize = hdr.nMessageSize;
3105 if (nMessageSize > MAX_SIZE)
3107 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3110 if (nMessageSize > vRecv.size())
3112 // Rewind and wait for rest of message
3113 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3118 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3119 unsigned int nChecksum = 0;
3120 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3121 if (nChecksum != hdr.nChecksum)
3123 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3124 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3128 // Copy message to its own buffer
3129 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3130 vRecv.ignore(nMessageSize);
3138 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3143 catch (std::ios_base::failure& e)
3145 if (strstr(e.what(), "end of data"))
3147 // Allow exceptions from under-length message on vRecv
3148 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
3150 else if (strstr(e.what(), "size too large"))
3152 // Allow exceptions from over-long size
3153 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3157 PrintExceptionContinue(&e, "ProcessMessages()");
3160 catch (std::exception& e) {
3161 PrintExceptionContinue(&e, "ProcessMessages()");
3163 PrintExceptionContinue(NULL, "ProcessMessages()");
3167 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3175 bool SendMessages(CNode* pto, bool fSendTrickle)
3177 TRY_LOCK(cs_main, lockMain);
3179 // Don't send anything until we get their version message
3180 if (pto->nVersion == 0)
3183 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3185 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3187 if (pto->nVersion > BIP0031_VERSION)
3188 pto->PushMessage("ping", nonce);
3190 pto->PushMessage("ping");
3193 // Resend wallet transactions that haven't gotten in a block yet
3194 ResendWalletTransactions();
3196 // Address refresh broadcast
3197 static int64 nLastRebroadcast;
3198 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3202 BOOST_FOREACH(CNode* pnode, vNodes)
3204 // Periodically clear setAddrKnown to allow refresh broadcasts
3205 if (nLastRebroadcast)
3206 pnode->setAddrKnown.clear();
3208 // Rebroadcast our address
3211 CAddress addr = GetLocalAddress(&pnode->addr);
3212 if (addr.IsRoutable())
3213 pnode->PushAddress(addr);
3217 nLastRebroadcast = GetTime();
3225 vector<CAddress> vAddr;
3226 vAddr.reserve(pto->vAddrToSend.size());
3227 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3229 // returns true if wasn't already contained in the set
3230 if (pto->setAddrKnown.insert(addr).second)
3232 vAddr.push_back(addr);
3233 // receiver rejects addr messages larger than 1000
3234 if (vAddr.size() >= 1000)
3236 pto->PushMessage("addr", vAddr);
3241 pto->vAddrToSend.clear();
3243 pto->PushMessage("addr", vAddr);
3248 // Message: inventory
3251 vector<CInv> vInvWait;
3253 LOCK(pto->cs_inventory);
3254 vInv.reserve(pto->vInventoryToSend.size());
3255 vInvWait.reserve(pto->vInventoryToSend.size());
3256 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3258 if (pto->setInventoryKnown.count(inv))
3261 // trickle out tx inv to protect privacy
3262 if (inv.type == MSG_TX && !fSendTrickle)
3264 // 1/4 of tx invs blast to all immediately
3265 static uint256 hashSalt;
3267 hashSalt = GetRandHash();
3268 uint256 hashRand = inv.hash ^ hashSalt;
3269 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3270 bool fTrickleWait = ((hashRand & 3) != 0);
3272 // always trickle our own transactions
3276 if (GetTransaction(inv.hash, wtx))
3278 fTrickleWait = true;
3283 vInvWait.push_back(inv);
3288 // returns true if wasn't already contained in the set
3289 if (pto->setInventoryKnown.insert(inv).second)
3291 vInv.push_back(inv);
3292 if (vInv.size() >= 1000)
3294 pto->PushMessage("inv", vInv);
3299 pto->vInventoryToSend = vInvWait;
3302 pto->PushMessage("inv", vInv);
3308 vector<CInv> vGetData;
3309 int64 nNow = GetTime() * 1000000;
3311 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3313 const CInv& inv = (*pto->mapAskFor.begin()).second;
3314 if (!AlreadyHave(txdb, inv))
3317 printf("sending getdata: %s\n", inv.ToString().c_str());
3318 vGetData.push_back(inv);
3319 if (vGetData.size() >= 1000)
3321 pto->PushMessage("getdata", vGetData);
3324 mapAlreadyAskedFor[inv] = nNow;
3326 pto->mapAskFor.erase(pto->mapAskFor.begin());
3328 if (!vGetData.empty())
3329 pto->PushMessage("getdata", vGetData);
3348 //////////////////////////////////////////////////////////////////////////////
3353 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3355 unsigned char* pdata = (unsigned char*)pbuffer;
3356 unsigned int blocks = 1 + ((len + 8) / 64);
3357 unsigned char* pend = pdata + 64 * blocks;
3358 memset(pdata + len, 0, 64 * blocks - len);
3360 unsigned int bits = len * 8;
3361 pend[-1] = (bits >> 0) & 0xff;
3362 pend[-2] = (bits >> 8) & 0xff;
3363 pend[-3] = (bits >> 16) & 0xff;
3364 pend[-4] = (bits >> 24) & 0xff;
3368 static const unsigned int pSHA256InitState[8] =
3369 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3371 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3374 unsigned char data[64];
3378 for (int i = 0; i < 16; i++)
3379 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3381 for (int i = 0; i < 8; i++)
3382 ctx.h[i] = ((uint32_t*)pinit)[i];
3384 SHA256_Update(&ctx, data, sizeof(data));
3385 for (int i = 0; i < 8; i++)
3386 ((uint32_t*)pstate)[i] = ctx.h[i];
3390 // ScanHash scans nonces looking for a hash with at least some zero bits.
3391 // It operates on big endian data. Caller does the byte reversing.
3392 // All input buffers are 16-byte aligned. nNonce is usually preserved
3393 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3394 // the block is rebuilt and nNonce starts over at zero.
3396 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3398 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3402 // Hash pdata using pmidstate as the starting state into
3403 // pre-formatted buffer phash1, then hash phash1 into phash
3405 SHA256Transform(phash1, pdata, pmidstate);
3406 SHA256Transform(phash, phash1, pSHA256InitState);
3408 // Return the nonce if the hash has at least some zero bits,
3409 // caller will check if it has enough to reach the target
3410 if (((unsigned short*)phash)[14] == 0)
3413 // If nothing found after trying for a while, return -1
3414 if ((nNonce & 0xffff) == 0)
3416 nHashesDone = 0xffff+1;
3417 return (unsigned int) -1;
3422 // Some explaining would be appreciated
3427 set<uint256> setDependsOn;
3431 COrphan(CTransaction* ptxIn)
3434 dPriority = dFeePerKb = 0;
3439 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
3440 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
3441 BOOST_FOREACH(uint256 hash, setDependsOn)
3442 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3447 uint64 nLastBlockTx = 0;
3448 uint64 nLastBlockSize = 0;
3450 // We want to sort transactions by priority and fee, so:
3451 typedef boost::tuple<double, double, CTransaction*> TxPriority;
3452 class TxPriorityCompare
3456 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
3457 bool operator()(const TxPriority& a, const TxPriority& b)
3461 if (a.get<1>() == b.get<1>())
3462 return a.get<0>() < b.get<0>();
3463 return a.get<1>() < b.get<1>();
3467 if (a.get<0>() == b.get<0>())
3468 return a.get<1>() < b.get<1>();
3469 return a.get<0>() < b.get<0>();
3474 const char* pszDummy = "\0\0";
3475 CScript scriptDummy(std::vector<unsigned char>(pszDummy, pszDummy + sizeof(pszDummy)));
3477 CBlock* CreateNewBlock(CReserveKey& reservekey)
3479 CBlockIndex* pindexPrev = pindexBest;
3482 auto_ptr<CBlock> pblock(new CBlock());
3486 // Create coinbase tx
3488 txNew.vin.resize(1);
3489 txNew.vin[0].prevout.SetNull();
3490 txNew.vout.resize(1);
3491 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3493 // Add our coinbase tx as first transaction
3494 pblock->vtx.push_back(txNew);
3496 // Largest block you're willing to create:
3497 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
3498 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
3499 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
3501 // How much of the block should be dedicated to high-priority transactions,
3502 // included regardless of the fees they pay
3503 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
3504 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
3506 // Minimum block size you want to create; block will be filled with free transactions
3507 // until there are no more or the block reaches this size:
3508 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
3509 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
3511 // Fee-per-kilobyte amount considered the same as "free"
3512 // Be careful setting this: if you set it to zero then
3513 // a transaction spammer can cheaply fill blocks using
3514 // 1-satoshi-fee transactions. It should be set above the real
3515 // cost to you of processing a transaction.
3516 int64 nMinTxFee = MIN_TX_FEE;
3517 if (mapArgs.count("-mintxfee"))
3518 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
3520 // Collect memory pool transactions into the block
3523 LOCK2(cs_main, mempool.cs);
3526 // Priority order to process transactions
3527 list<COrphan> vOrphan; // list memory doesn't move
3528 map<uint256, vector<COrphan*> > mapDependers;
3530 // This vector will be sorted into a priority queue:
3531 vector<TxPriority> vecPriority;
3532 vecPriority.reserve(mempool.mapTx.size());
3533 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3535 CTransaction& tx = (*mi).second;
3536 if (tx.IsCoinBase() || !tx.IsFinal())
3539 COrphan* porphan = NULL;
3540 double dPriority = 0;
3542 bool fMissingInputs = false;
3543 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3545 // Read prev transaction
3546 CTransaction txPrev;
3548 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3550 // This should never happen; all transactions in the memory
3551 // pool should connect to either transactions in the chain
3552 // or other transactions in the memory pool.
3553 if (!mempool.mapTx.count(txin.prevout.hash))
3555 printf("ERROR: mempool transaction missing input\n");
3556 if (fDebug) assert("mempool transaction missing input" == 0);
3557 fMissingInputs = true;
3563 // Has to wait for dependencies
3566 // Use list for automatic deletion
3567 vOrphan.push_back(COrphan(&tx));
3568 porphan = &vOrphan.back();
3570 mapDependers[txin.prevout.hash].push_back(porphan);
3571 porphan->setDependsOn.insert(txin.prevout.hash);
3572 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
3575 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3576 nTotalIn += nValueIn;
3578 int nConf = txindex.GetDepthInMainChain();
3579 dPriority += (double)nValueIn * nConf;
3581 if (fMissingInputs) continue;
3583 // Priority is sum(valuein * age) / txsize
3584 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3585 dPriority /= nTxSize;
3587 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
3588 // client code rounds up the size to the nearest 1K. That's good, because it gives an
3589 // incentive to create smaller transactions.
3590 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
3594 porphan->dPriority = dPriority;
3595 porphan->dFeePerKb = dFeePerKb;
3598 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
3601 // Collect transactions into block
3602 map<uint256, CTxIndex> mapTestPool;
3603 uint64 nBlockSize = 1000;
3604 uint64 nBlockTx = 0;
3605 int nBlockSigOps = 100;
3606 bool fSortedByFee = (nBlockPrioritySize <= 0);
3608 TxPriorityCompare comparer(fSortedByFee);
3609 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
3611 while (!vecPriority.empty())
3613 // Take highest priority transaction off the priority queue:
3614 double dPriority = vecPriority.front().get<0>();
3615 double dFeePerKb = vecPriority.front().get<1>();
3616 CTransaction& tx = *(vecPriority.front().get<2>());
3618 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
3619 vecPriority.pop_back();
3622 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3623 if (nBlockSize + nTxSize >= nBlockMaxSize)
3626 // Legacy limits on sigOps:
3627 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3628 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3631 // Skip free transactions if we're past the minimum block size:
3632 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
3635 // Prioritize by fee once past the priority size or we run out of high-priority
3637 if (!fSortedByFee &&
3638 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
3640 fSortedByFee = true;
3641 comparer = TxPriorityCompare(fSortedByFee);
3642 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
3645 // Connecting shouldn't fail due to dependency on other memory pool transactions
3646 // because we're already processing them in order of dependency
3647 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3648 MapPrevTx mapInputs;
3650 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3653 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3655 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3656 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3659 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3661 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3662 swap(mapTestPool, mapTestPoolTmp);
3665 pblock->vtx.push_back(tx);
3666 nBlockSize += nTxSize;
3668 nBlockSigOps += nTxSigOps;
3671 if (fDebug && GetBoolArg("-printpriority"))
3673 printf("priority %.1f feeperkb %.1f txid %s\n",
3674 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
3677 // Add transactions that depend on this one to the priority queue
3678 uint256 hash = tx.GetHash();
3679 if (mapDependers.count(hash))
3681 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3683 if (!porphan->setDependsOn.empty())
3685 porphan->setDependsOn.erase(hash);
3686 if (porphan->setDependsOn.empty())
3688 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
3689 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
3696 nLastBlockTx = nBlockTx;
3697 nLastBlockSize = nBlockSize;
3698 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
3700 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3703 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3704 pblock->UpdateTime(pindexPrev);
3705 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3708 pblock->vtx[0].vin[0].scriptSig = scriptDummy;
3709 CBlockIndex indexDummy(1, 1, *pblock);
3710 indexDummy.pprev = pindexPrev;
3711 indexDummy.nHeight = pindexPrev->nHeight + 1;
3712 if (!pblock->ConnectBlock(txdb, &indexDummy, true))
3713 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
3716 return pblock.release();
3720 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3722 // Update nExtraNonce
3723 static uint256 hashPrevBlock;
3724 if (hashPrevBlock != pblock->hashPrevBlock)
3727 hashPrevBlock = pblock->hashPrevBlock;
3730 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
3731 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3732 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3734 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3738 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3741 // Pre-build hash buffers
3748 uint256 hashPrevBlock;
3749 uint256 hashMerkleRoot;
3752 unsigned int nNonce;
3755 unsigned char pchPadding0[64];
3757 unsigned char pchPadding1[64];
3760 memset(&tmp, 0, sizeof(tmp));
3762 tmp.block.nVersion = pblock->nVersion;
3763 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3764 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3765 tmp.block.nTime = pblock->nTime;
3766 tmp.block.nBits = pblock->nBits;
3767 tmp.block.nNonce = pblock->nNonce;
3769 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3770 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3772 // Byte swap all the input buffer
3773 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3774 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3776 // Precalc the first half of the first hash, which stays constant
3777 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3779 memcpy(pdata, &tmp.block, 128);
3780 memcpy(phash1, &tmp.hash1, 64);
3784 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3786 uint256 hash = pblock->GetHash();
3787 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3789 if (hash > hashTarget)
3793 printf("BitcoinMiner:\n");
3794 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3796 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3801 if (pblock->hashPrevBlock != hashBestChain)
3802 return error("BitcoinMiner : generated block is stale");
3804 // Remove key from key pool
3805 reservekey.KeepKey();
3807 // Track how many getdata requests this block gets
3809 LOCK(wallet.cs_wallet);
3810 wallet.mapRequestCount[pblock->GetHash()] = 0;
3813 // Process this block the same as if we had received it from another node
3814 if (!ProcessBlock(NULL, pblock))
3815 return error("BitcoinMiner : ProcessBlock, block not accepted");
3821 void static ThreadBitcoinMiner(void* parg);
3823 static bool fGenerateBitcoins = false;
3824 static bool fLimitProcessors = false;
3825 static int nLimitProcessors = -1;
3827 void static BitcoinMiner(CWallet *pwallet)
3829 printf("BitcoinMiner started\n");
3830 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3832 // Make this thread recognisable as the mining thread
3833 RenameThread("bitcoin-miner");
3835 // Each thread has its own key and counter
3836 CReserveKey reservekey(pwallet);
3837 unsigned int nExtraNonce = 0;
3839 while (fGenerateBitcoins)
3843 while (vNodes.empty() || IsInitialBlockDownload())
3848 if (!fGenerateBitcoins)
3856 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3857 CBlockIndex* pindexPrev = pindexBest;
3859 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3862 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3864 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
3865 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
3869 // Pre-build hash buffers
3871 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3872 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3873 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3875 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3877 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3878 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3879 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3885 int64 nStart = GetTime();
3886 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3888 uint256& hash = *alignup<16>(hashbuf);
3891 unsigned int nHashesDone = 0;
3892 unsigned int nNonceFound;
3895 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3896 (char*)&hash, nHashesDone);
3898 // Check if something found
3899 if (nNonceFound != (unsigned int) -1)
3901 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3902 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3904 if (hash <= hashTarget)
3907 pblock->nNonce = ByteReverse(nNonceFound);
3908 assert(hash == pblock->GetHash());
3910 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3911 CheckWork(pblock.get(), *pwalletMain, reservekey);
3912 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3918 static int64 nHashCounter;
3919 if (nHPSTimerStart == 0)
3921 nHPSTimerStart = GetTimeMillis();
3925 nHashCounter += nHashesDone;
3926 if (GetTimeMillis() - nHPSTimerStart > 4000)
3928 static CCriticalSection cs;
3931 if (GetTimeMillis() - nHPSTimerStart > 4000)
3933 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3934 nHPSTimerStart = GetTimeMillis();
3936 static int64 nLogTime;
3937 if (GetTime() - nLogTime > 30 * 60)
3939 nLogTime = GetTime();
3940 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
3946 // Check for stop or if block needs to be rebuilt
3949 if (!fGenerateBitcoins)
3951 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
3955 if (nBlockNonce >= 0xffff0000)
3957 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3959 if (pindexPrev != pindexBest)
3962 // Update nTime every few seconds
3963 pblock->UpdateTime(pindexPrev);
3964 nBlockTime = ByteReverse(pblock->nTime);
3967 // Changing pblock->nTime can change work required on testnet:
3968 nBlockBits = ByteReverse(pblock->nBits);
3969 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3975 void static ThreadBitcoinMiner(void* parg)
3977 CWallet* pwallet = (CWallet*)parg;
3980 vnThreadsRunning[THREAD_MINER]++;
3981 BitcoinMiner(pwallet);
3982 vnThreadsRunning[THREAD_MINER]--;
3984 catch (std::exception& e) {
3985 vnThreadsRunning[THREAD_MINER]--;
3986 PrintException(&e, "ThreadBitcoinMiner()");
3988 vnThreadsRunning[THREAD_MINER]--;
3989 PrintException(NULL, "ThreadBitcoinMiner()");
3992 if (vnThreadsRunning[THREAD_MINER] == 0)
3994 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
3998 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4000 fGenerateBitcoins = fGenerate;
4001 nLimitProcessors = GetArg("-genproclimit", -1);
4002 if (nLimitProcessors == 0)
4003 fGenerateBitcoins = false;
4004 fLimitProcessors = (nLimitProcessors != -1);
4008 int nProcessors = boost::thread::hardware_concurrency();
4009 printf("%d processors\n", nProcessors);
4010 if (nProcessors < 1)
4012 if (fLimitProcessors && nProcessors > nLimitProcessors)
4013 nProcessors = nLimitProcessors;
4014 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4015 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4016 for (int i = 0; i < nAddThreads; i++)
4018 if (!NewThread(ThreadBitcoinMiner, pwallet))
4019 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");