1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 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"
12 #include "ui_interface.h"
13 #include "checkqueue.h"
14 #include "chainparams.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
20 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
36 uint256 nBestInvalidWork = 0;
37 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
38 int64 nTimeBestReceived = 0;
39 int nScriptCheckThreads = 0;
40 bool fImporting = false;
41 bool fReindex = false;
42 bool fBenchmark = false;
43 bool fTxIndex = false;
44 unsigned int nCoinCacheSize = 5000;
45 bool fHaveGUI = false;
47 /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
48 int64 CTransaction::nMinTxFee = 10000; // Override with -mintxfee
49 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
50 int64 CTransaction::nMinRelayTxFee = 10000;
52 CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
54 map<uint256, CBlock*> mapOrphanBlocks;
55 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
57 map<uint256, CTransaction> mapOrphanTransactions;
58 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
60 // Constant stuff for coinbase transactions we create:
61 CScript COINBASE_FLAGS;
63 const string strMessageMagic = "Bitcoin Signed Message:\n";
66 int64 nTransactionFee = 0;
70 //////////////////////////////////////////////////////////////////////////////
72 // dispatching functions
75 // These functions dispatch to one or all registered wallets
78 void RegisterWallet(CWallet* pwalletIn)
81 LOCK(cs_setpwalletRegistered);
82 setpwalletRegistered.insert(pwalletIn);
86 void UnregisterWallet(CWallet* pwalletIn)
89 LOCK(cs_setpwalletRegistered);
90 setpwalletRegistered.erase(pwalletIn);
94 void UnregisterAllWallets()
96 LOCK(cs_setpwalletRegistered);
97 setpwalletRegistered.clear();
100 // get the wallet transaction with the given hash (if it exists)
101 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
103 LOCK(cs_setpwalletRegistered);
104 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
105 if (pwallet->GetTransaction(hashTx,wtx))
110 // erases transaction with the given hash from all wallets
111 void static EraseFromWallets(uint256 hash)
113 LOCK(cs_setpwalletRegistered);
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 pwallet->EraseFromWallet(hash);
118 // make sure all wallets know about the given transaction, in the given block
119 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
121 LOCK(cs_setpwalletRegistered);
122 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
123 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
126 // notify wallets about a new best chain
127 void static SetBestChain(const CBlockLocator& loc)
129 LOCK(cs_setpwalletRegistered);
130 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
131 pwallet->SetBestChain(loc);
134 // notify wallets about an updated transaction
135 void static UpdatedTransaction(const uint256& hashTx)
137 LOCK(cs_setpwalletRegistered);
138 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139 pwallet->UpdatedTransaction(hashTx);
143 void static PrintWallets(const CBlock& block)
145 LOCK(cs_setpwalletRegistered);
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->PrintWallet(block);
150 // notify wallets about an incoming inventory (for request counts)
151 void static Inventory(const uint256& hash)
153 LOCK(cs_setpwalletRegistered);
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->Inventory(hash);
158 // ask wallets to resend their transactions
159 void static ResendWalletTransactions()
161 LOCK(cs_setpwalletRegistered);
162 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
163 pwallet->ResendWalletTransactions();
166 //////////////////////////////////////////////////////////////////////////////
168 // Registration of network node signals.
171 int static GetHeight()
174 return chainActive.Height();
177 void RegisterNodeSignals(CNodeSignals& nodeSignals)
179 nodeSignals.GetHeight.connect(&GetHeight);
180 nodeSignals.ProcessMessages.connect(&ProcessMessages);
181 nodeSignals.SendMessages.connect(&SendMessages);
184 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
186 nodeSignals.GetHeight.disconnect(&GetHeight);
187 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
188 nodeSignals.SendMessages.disconnect(&SendMessages);
191 //////////////////////////////////////////////////////////////////////////////
193 // CChain implementation
196 CBlockIndex *CChain::SetTip(CBlockIndex *pindex) {
197 if (pindex == NULL) {
201 vChain.resize(pindex->nHeight + 1);
202 while (pindex && vChain[pindex->nHeight] != pindex) {
203 vChain[pindex->nHeight] = pindex;
204 pindex = pindex->pprev;
209 CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
211 std::vector<uint256> vHave;
217 vHave.push_back(pindex->GetBlockHash());
218 // Stop when we have added the genesis block.
219 if (pindex->nHeight == 0)
221 // Exponentially larger steps back, plus the genesis block.
222 int nHeight = std::max(pindex->nHeight - nStep, 0);
223 // In case pindex is not in this chain, iterate pindex->pprev to find blocks.
224 while (pindex->nHeight > nHeight && !Contains(pindex))
225 pindex = pindex->pprev;
226 // If pindex is in this chain, use direct height-based access.
227 if (pindex->nHeight > nHeight)
228 pindex = (*this)[nHeight];
229 if (vHave.size() > 10)
233 return CBlockLocator(vHave);
236 CBlockIndex *CChain::FindFork(const CBlockLocator &locator) const {
237 // Find the first block the caller has in the main chain
238 BOOST_FOREACH(const uint256& hash, locator.vHave) {
239 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
240 if (mi != mapBlockIndex.end())
242 CBlockIndex* pindex = (*mi).second;
243 if (Contains(pindex))
250 //////////////////////////////////////////////////////////////////////////////
252 // CCoinsView implementations
255 bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; }
256 bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; }
257 bool CCoinsView::HaveCoins(const uint256 &txid) { return false; }
258 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
259 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
260 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
261 bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
264 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
265 bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); }
266 bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
267 bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); }
268 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
269 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
270 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
271 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
272 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
274 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
276 bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) {
277 if (cacheCoins.count(txid)) {
278 coins = cacheCoins[txid];
281 if (base->GetCoins(txid, coins)) {
282 cacheCoins[txid] = coins;
288 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) {
289 std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid);
290 if (it != cacheCoins.end() && it->first == txid)
293 if (!base->GetCoins(txid,tmp))
294 return cacheCoins.end();
295 std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins()));
296 tmp.swap(ret->second);
300 CCoins &CCoinsViewCache::GetCoins(const uint256 &txid) {
301 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
302 assert(it != cacheCoins.end());
306 bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) {
307 cacheCoins[txid] = coins;
311 bool CCoinsViewCache::HaveCoins(const uint256 &txid) {
312 return FetchCoins(txid) != cacheCoins.end();
315 CBlockIndex *CCoinsViewCache::GetBestBlock() {
316 if (pindexTip == NULL)
317 pindexTip = base->GetBestBlock();
321 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
326 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
327 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
328 cacheCoins[it->first] = it->second;
333 bool CCoinsViewCache::Flush() {
334 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
340 unsigned int CCoinsViewCache::GetCacheSize() {
341 return cacheCoins.size();
344 /** CCoinsView that brings transactions from a memorypool into view.
345 It does not check for spendings by memory pool transactions. */
346 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
348 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) {
349 if (base->GetCoins(txid, coins))
351 if (mempool.exists(txid)) {
352 const CTransaction &tx = mempool.lookup(txid);
353 coins = CCoins(tx, MEMPOOL_HEIGHT);
359 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) {
360 return mempool.exists(txid) || base->HaveCoins(txid);
363 CCoinsViewCache *pcoinsTip = NULL;
364 CBlockTreeDB *pblocktree = NULL;
366 //////////////////////////////////////////////////////////////////////////////
368 // mapOrphanTransactions
371 bool AddOrphanTx(const CTransaction& tx)
373 uint256 hash = tx.GetHash();
374 if (mapOrphanTransactions.count(hash))
377 // Ignore big transactions, to avoid a
378 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
379 // large transaction with a missing parent then we assume
380 // it will rebroadcast it later, after the parent transaction(s)
381 // have been mined or received.
382 // 10,000 orphans, each of which is at most 5,000 bytes big is
383 // at most 500 megabytes of orphans:
384 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
387 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
391 mapOrphanTransactions[hash] = tx;
392 BOOST_FOREACH(const CTxIn& txin, tx.vin)
393 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
395 LogPrint("mempool", "stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
396 mapOrphanTransactions.size());
400 void static EraseOrphanTx(uint256 hash)
402 if (!mapOrphanTransactions.count(hash))
404 const CTransaction& tx = mapOrphanTransactions[hash];
405 BOOST_FOREACH(const CTxIn& txin, tx.vin)
407 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
408 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
409 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
411 mapOrphanTransactions.erase(hash);
414 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
416 unsigned int nEvicted = 0;
417 while (mapOrphanTransactions.size() > nMaxOrphans)
419 // Evict a random orphan:
420 uint256 randomhash = GetRandHash();
421 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
422 if (it == mapOrphanTransactions.end())
423 it = mapOrphanTransactions.begin();
424 EraseOrphanTx(it->first);
436 bool IsStandardTx(const CTransaction& tx, string& reason)
438 if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
443 if (!IsFinalTx(tx)) {
444 reason = "non-final";
448 // Extremely large transactions with lots of inputs can cost the network
449 // almost as much to process as they cost the sender in fees, because
450 // computing signature hashes is O(ninputs*txsize). Limiting transactions
451 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
452 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
453 if (sz >= MAX_STANDARD_TX_SIZE) {
458 BOOST_FOREACH(const CTxIn& txin, tx.vin)
460 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
461 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
462 // ~65-byte public keys, plus a few script ops.
463 if (txin.scriptSig.size() > 500) {
464 reason = "scriptsig-size";
467 if (!txin.scriptSig.IsPushOnly()) {
468 reason = "scriptsig-not-pushonly";
473 unsigned int nDataOut = 0;
474 txnouttype whichType;
475 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
476 if (!::IsStandard(txout.scriptPubKey, whichType)) {
477 reason = "scriptpubkey";
480 if (whichType == TX_NULL_DATA)
482 else if (txout.IsDust(CTransaction::nMinRelayTxFee)) {
488 // only one OP_RETURN txout is permitted
490 reason = "mucho-data";
497 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64 nBlockTime)
499 // Time based nLockTime implemented in 0.1.6
500 if (tx.nLockTime == 0)
502 if (nBlockHeight == 0)
503 nBlockHeight = chainActive.Height();
505 nBlockTime = GetAdjustedTime();
506 if ((int64)tx.nLockTime < ((int64)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
508 BOOST_FOREACH(const CTxIn& txin, tx.vin)
514 /** Amount of bitcoins spent by the transaction.
515 @return sum of all outputs (note: does not include fees)
517 int64 GetValueOut(const CTransaction& tx)
520 BOOST_FOREACH(const CTxOut& txout, tx.vout)
522 nValueOut += txout.nValue;
523 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
524 throw std::runtime_error("GetValueOut() : value out of range");
530 // Check transaction inputs, and make sure any
531 // pay-to-script-hash transactions are evaluating IsStandard scripts
533 // Why bother? To avoid denial-of-service attacks; an attacker
534 // can submit a standard HASH... OP_EQUAL transaction,
535 // which will get accepted into blocks. The redemption
536 // script can be anything; an attacker could use a very
537 // expensive-to-check-upon-redemption script like:
538 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
540 bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs)
543 return true; // Coinbases don't use vin normally
545 for (unsigned int i = 0; i < tx.vin.size(); i++)
547 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
549 vector<vector<unsigned char> > vSolutions;
550 txnouttype whichType;
551 // get the scriptPubKey corresponding to this input:
552 const CScript& prevScript = prev.scriptPubKey;
553 if (!Solver(prevScript, whichType, vSolutions))
555 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
556 if (nArgsExpected < 0)
559 // Transactions with extra stuff in their scriptSigs are
560 // non-standard. Note that this EvalScript() call will
561 // be quick, because if there are any operations
562 // beside "push data" in the scriptSig the
563 // IsStandard() call returns false
564 vector<vector<unsigned char> > stack;
565 if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, false, 0))
568 if (whichType == TX_SCRIPTHASH)
572 CScript subscript(stack.back().begin(), stack.back().end());
573 vector<vector<unsigned char> > vSolutions2;
574 txnouttype whichType2;
575 if (!Solver(subscript, whichType2, vSolutions2))
577 if (whichType2 == TX_SCRIPTHASH)
581 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
584 nArgsExpected += tmpExpected;
587 if (stack.size() != (unsigned int)nArgsExpected)
594 unsigned int GetLegacySigOpCount(const CTransaction& tx)
596 unsigned int nSigOps = 0;
597 BOOST_FOREACH(const CTxIn& txin, tx.vin)
599 nSigOps += txin.scriptSig.GetSigOpCount(false);
601 BOOST_FOREACH(const CTxOut& txout, tx.vout)
603 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
608 unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& inputs)
613 unsigned int nSigOps = 0;
614 for (unsigned int i = 0; i < tx.vin.size(); i++)
616 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
617 if (prevout.scriptPubKey.IsPayToScriptHash())
618 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
623 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
627 if (pblock == NULL) {
629 if (pcoinsTip->GetCoins(GetHash(), coins)) {
630 CBlockIndex *pindex = chainActive[coins.nHeight];
632 if (!ReadBlockFromDisk(blockTmp, pindex))
640 // Update the tx's hashBlock
641 hashBlock = pblock->GetHash();
643 // Locate the transaction
644 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
645 if (pblock->vtx[nIndex] == *(CTransaction*)this)
647 if (nIndex == (int)pblock->vtx.size())
649 vMerkleBranch.clear();
651 LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
655 // Fill in merkle branch
656 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
659 // Is the tx in a block that's in the main chain
660 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
661 if (mi == mapBlockIndex.end())
663 CBlockIndex* pindex = (*mi).second;
664 if (!pindex || !chainActive.Contains(pindex))
667 return chainActive.Height() - pindex->nHeight + 1;
676 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
678 // Basic checks that don't depend on any context
680 return state.DoS(10, error("CheckTransaction() : vin empty"));
682 return state.DoS(10, error("CheckTransaction() : vout empty"));
684 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
685 return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
687 // Check for negative or overflow output values
689 BOOST_FOREACH(const CTxOut& txout, tx.vout)
691 if (txout.nValue < 0)
692 return state.DoS(100, error("CheckTransaction() : txout.nValue negative"));
693 if (txout.nValue > MAX_MONEY)
694 return state.DoS(100, error("CheckTransaction() : txout.nValue too high"));
695 nValueOut += txout.nValue;
696 if (!MoneyRange(nValueOut))
697 return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
700 // Check for duplicate inputs
701 set<COutPoint> vInOutPoints;
702 BOOST_FOREACH(const CTxIn& txin, tx.vin)
704 if (vInOutPoints.count(txin.prevout))
705 return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
706 vInOutPoints.insert(txin.prevout);
711 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
712 return state.DoS(100, error("CheckTransaction() : coinbase script size"));
716 BOOST_FOREACH(const CTxIn& txin, tx.vin)
717 if (txin.prevout.IsNull())
718 return state.DoS(10, error("CheckTransaction() : prevout is null"));
724 int64 GetMinFee(const CTransaction& tx, bool fAllowFree, enum GetMinFee_mode mode)
726 // Base fee is either nMinTxFee or nMinRelayTxFee
727 int64 nBaseFee = (mode == GMF_RELAY) ? tx.nMinRelayTxFee : tx.nMinTxFee;
729 unsigned int nBytes = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
730 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
734 // There is a free transaction area in blocks created by most miners,
735 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
736 // to be considered to fall into this category. We don't want to encourage sending
737 // multiple transactions instead of one big transaction to avoid fees.
738 // * If we are creating a transaction we allow transactions up to 1,000 bytes
739 // to be considered safe and assume they can likely make it into this section.
740 if (nBytes < (mode == GMF_SEND ? 1000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
744 // This code can be removed after enough miners have upgraded to version 0.9.
745 // Until then, be safe when sending and require a fee if any output
746 // is less than CENT:
747 if (nMinFee < nBaseFee && mode == GMF_SEND)
749 BOOST_FOREACH(const CTxOut& txout, tx.vout)
750 if (txout.nValue < CENT)
754 if (!MoneyRange(nMinFee))
759 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
763 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
765 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
766 while (it != mapNextTx.end() && it->first.hash == hashTx) {
767 coins.Spend(it->first.n); // and remove those outputs from coins
772 bool CTxMemPool::accept(CValidationState &state, const CTransaction &tx, bool fLimitFree,
773 bool* pfMissingInputs, bool fRejectInsaneFee)
776 *pfMissingInputs = false;
778 if (!CheckTransaction(tx, state))
779 return error("CTxMemPool::accept() : CheckTransaction failed");
781 // Coinbase is only valid in a block, not as a loose transaction
783 return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
785 // To help v0.1.5 clients who would see it as a negative number
786 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
787 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
789 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
791 if (Params().NetworkID() == CChainParams::MAIN && !IsStandardTx(tx, reason))
792 return error("CTxMemPool::accept() : nonstandard transaction: %s",
795 // is it already in the memory pool?
796 uint256 hash = tx.GetHash();
799 if (mapTx.count(hash))
803 // Check for conflicts with in-memory transactions
804 CTransaction* ptxOld = NULL;
805 for (unsigned int i = 0; i < tx.vin.size(); i++)
807 COutPoint outpoint = tx.vin[i].prevout;
808 if (mapNextTx.count(outpoint))
810 // Disable replacement feature for now
813 // Allow replacing with a newer version of the same transaction
816 ptxOld = mapNextTx[outpoint].ptx;
817 if (IsFinalTx(*ptxOld))
819 if (!tx.IsNewerThan(*ptxOld))
821 for (unsigned int i = 0; i < tx.vin.size(); i++)
823 COutPoint outpoint = tx.vin[i].prevout;
824 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
833 CCoinsViewCache view(dummy);
837 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
838 view.SetBackend(viewMemPool);
840 // do we already have it?
841 if (view.HaveCoins(hash))
844 // do all inputs exist?
845 // Note that this does not check for the presence of actual outputs (see the next check for that),
846 // only helps filling in pfMissingInputs (to determine missing vs spent).
847 BOOST_FOREACH(const CTxIn txin, tx.vin) {
848 if (!view.HaveCoins(txin.prevout.hash)) {
850 *pfMissingInputs = true;
855 // are the actual inputs available?
856 if (!view.HaveInputs(tx))
857 return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
859 // Bring the best block into scope
862 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
863 view.SetBackend(dummy);
866 // Check for non-standard pay-to-script-hash in inputs
867 if (Params().NetworkID() == CChainParams::MAIN && !AreInputsStandard(tx, view))
868 return error("CTxMemPool::accept() : nonstandard transaction input");
870 // Note: if you modify this code to accept non-standard transactions, then
871 // you should add code here to check that the transaction does a
872 // reasonable number of ECDSA signature verifications.
874 int64 nFees = view.GetValueIn(tx)-GetValueOut(tx);
875 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
877 // Don't accept it if it can't get into a block
878 int64 txMinFee = GetMinFee(tx, true, GMF_RELAY);
879 if (fLimitFree && nFees < txMinFee)
880 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
881 hash.ToString().c_str(),
884 // Continuously rate-limit free transactions
885 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
886 // be annoying or make others' transactions take longer to confirm.
887 if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
889 static double dFreeCount;
890 static int64 nLastTime;
891 int64 nNow = GetTime();
895 // Use an exponentially decaying ~10-minute window:
896 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
898 // -limitfreerelay unit is thousand-bytes-per-minute
899 // At default rate it would take over a month to fill 1GB
900 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
901 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
903 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
907 if (fRejectInsaneFee && nFees > CTransaction::nMinRelayTxFee * 10000)
908 return error("CTxMemPool::accept() : insane fees %s, %"PRI64d" > %"PRI64d,
909 hash.ToString().c_str(),
910 nFees, CTransaction::nMinRelayTxFee * 10000);
912 // Check against previous transactions
913 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
914 if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
916 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().c_str());
920 // Store transaction in memory
925 LogPrint("mempool", "CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
928 addUnchecked(hash, tx);
931 ///// are we sure this is ok when loading transactions or restoring block txes
932 // If updated, erase old tx from wallet
934 EraseFromWallets(ptxOld->GetHash());
935 SyncWithWallets(hash, tx, NULL, true);
937 LogPrint("mempool", "CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
938 hash.ToString().c_str(),
944 bool CTxMemPool::addUnchecked(const uint256& hash, const CTransaction &tx)
946 // Add to memory pool without checking anything. Don't call this directly,
947 // call CTxMemPool::accept to properly check the transaction first.
950 for (unsigned int i = 0; i < tx.vin.size(); i++)
951 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
952 nTransactionsUpdated++;
958 bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
960 // Remove transaction from memory pool
963 uint256 hash = tx.GetHash();
965 for (unsigned int i = 0; i < tx.vout.size(); i++) {
966 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
967 if (it != mapNextTx.end())
968 remove(*it->second.ptx, true);
971 if (mapTx.count(hash))
973 BOOST_FOREACH(const CTxIn& txin, tx.vin)
974 mapNextTx.erase(txin.prevout);
976 nTransactionsUpdated++;
982 bool CTxMemPool::removeConflicts(const CTransaction &tx)
984 // Remove transactions which depend on inputs of tx, recursively
986 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
987 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
988 if (it != mapNextTx.end()) {
989 const CTransaction &txConflict = *it->second.ptx;
990 if (txConflict != tx)
991 remove(txConflict, true);
997 void CTxMemPool::clear()
1002 ++nTransactionsUpdated;
1005 bool CTxMemPool::fChecks = false;
1007 void CTxMemPool::check(CCoinsViewCache *pcoins) const
1012 LogPrintf("Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
1015 for (std::map<uint256, CTransaction>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
1017 BOOST_FOREACH(const CTxIn &txin, it->second.vin) {
1018 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
1019 std::map<uint256, CTransaction>::const_iterator it2 = mapTx.find(txin.prevout.hash);
1020 if (it2 != mapTx.end()) {
1021 assert(it2->second.vout.size() > txin.prevout.n && !it2->second.vout[txin.prevout.n].IsNull());
1023 CCoins &coins = pcoins->GetCoins(txin.prevout.hash);
1024 assert(coins.IsAvailable(txin.prevout.n));
1026 // Check whether its inputs are marked in mapNextTx.
1027 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
1028 assert(it3 != mapNextTx.end());
1029 assert(it3->second.ptx == &it->second);
1030 assert(it3->second.n == i);
1034 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
1035 uint256 hash = it->second.ptx->GetHash();
1036 std::map<uint256, CTransaction>::const_iterator it2 = mapTx.find(hash);
1037 assert(it2 != mapTx.end());
1038 assert(&it2->second == it->second.ptx);
1039 assert(it2->second.vin.size() > it->second.n);
1040 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
1044 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
1049 vtxid.reserve(mapTx.size());
1050 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
1051 vtxid.push_back((*mi).first);
1057 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
1059 if (hashBlock == 0 || nIndex == -1)
1062 // Find the block it claims to be in
1063 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1064 if (mi == mapBlockIndex.end())
1066 CBlockIndex* pindex = (*mi).second;
1067 if (!pindex || !chainActive.Contains(pindex))
1070 // Make sure the merkle branch connects to this block
1071 if (!fMerkleVerified)
1073 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
1075 fMerkleVerified = true;
1079 return chainActive.Height() - pindex->nHeight + 1;
1083 int CMerkleTx::GetBlocksToMaturity() const
1087 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
1091 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree)
1093 CValidationState state;
1094 return mempool.accept(state, *this, fLimitFree, NULL);
1099 bool CWalletTx::AcceptWalletTransaction()
1103 // Add previous supporting transactions first
1104 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
1106 if (!tx.IsCoinBase())
1108 uint256 hash = tx.GetHash();
1109 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
1110 tx.AcceptToMemoryPool(false);
1113 return AcceptToMemoryPool(false);
1119 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
1120 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1122 CBlockIndex *pindexSlow = NULL;
1127 if (mempool.exists(hash))
1129 txOut = mempool.lookup(hash);
1136 if (pblocktree->ReadTxIndex(hash, postx)) {
1137 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1138 CBlockHeader header;
1141 fseek(file, postx.nTxOffset, SEEK_CUR);
1143 } catch (std::exception &e) {
1144 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1146 hashBlock = header.GetHash();
1147 if (txOut.GetHash() != hash)
1148 return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
1153 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1156 CCoinsViewCache &view = *pcoinsTip;
1158 if (view.GetCoins(hash, coins))
1159 nHeight = coins.nHeight;
1162 pindexSlow = chainActive[nHeight];
1168 if (ReadBlockFromDisk(block, pindexSlow)) {
1169 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1170 if (tx.GetHash() == hash) {
1172 hashBlock = pindexSlow->GetBlockHash();
1187 //////////////////////////////////////////////////////////////////////////////
1189 // CBlock and CBlockIndex
1192 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
1194 // Open history file to append
1195 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1197 return error("WriteBlockToDisk() : OpenBlockFile failed");
1199 // Write index header
1200 unsigned int nSize = fileout.GetSerializeSize(block);
1201 fileout << FLATDATA(Params().MessageStart()) << nSize;
1204 long fileOutPos = ftell(fileout);
1206 return error("WriteBlockToDisk() : ftell failed");
1207 pos.nPos = (unsigned int)fileOutPos;
1210 // Flush stdio buffers and commit to disk before returning
1212 if (!IsInitialBlockDownload())
1213 FileCommit(fileout);
1218 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1222 // Open history file to read
1223 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1225 return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : OpenBlockFile failed");
1231 catch (std::exception &e) {
1232 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1236 if (!CheckProofOfWork(block.GetHash(), block.nBits))
1237 return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : errors in block header");
1242 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1244 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1246 if (block.GetHash() != pindex->GetBlockHash())
1247 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
1251 uint256 static GetOrphanRoot(const CBlockHeader* pblock)
1253 // Work back to the first block in the orphan chain
1254 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1255 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1256 return pblock->GetHash();
1259 int64 GetBlockValue(int nHeight, int64 nFees)
1261 int64 nSubsidy = 50 * COIN;
1263 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1264 nSubsidy >>= (nHeight / Params().SubsidyHalvingInterval());
1266 return nSubsidy + nFees;
1269 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1270 static const int64 nTargetSpacing = 10 * 60;
1271 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1274 // minimum amount of work that could possibly be required nTime after
1275 // minimum work required was nBase
1277 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1279 const CBigNum &bnLimit = Params().ProofOfWorkLimit();
1280 // Testnet has min-difficulty blocks
1281 // after nTargetSpacing*2 time between blocks:
1282 if (TestNet() && nTime > nTargetSpacing*2)
1283 return bnLimit.GetCompact();
1286 bnResult.SetCompact(nBase);
1287 while (nTime > 0 && bnResult < bnLimit)
1289 // Maximum 400% adjustment...
1291 // ... in best-case exactly 4-times-normal target time
1292 nTime -= nTargetTimespan*4;
1294 if (bnResult > bnLimit)
1296 return bnResult.GetCompact();
1299 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
1301 unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
1304 if (pindexLast == NULL)
1305 return nProofOfWorkLimit;
1307 // Only change once per interval
1308 if ((pindexLast->nHeight+1) % nInterval != 0)
1312 // Special difficulty rule for testnet:
1313 // If the new block's timestamp is more than 2* 10 minutes
1314 // then allow mining of a min-difficulty block.
1315 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1316 return nProofOfWorkLimit;
1319 // Return the last non-special-min-difficulty-rules-block
1320 const CBlockIndex* pindex = pindexLast;
1321 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1322 pindex = pindex->pprev;
1323 return pindex->nBits;
1326 return pindexLast->nBits;
1329 // Go back by what we want to be 14 days worth of blocks
1330 const CBlockIndex* pindexFirst = pindexLast;
1331 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1332 pindexFirst = pindexFirst->pprev;
1333 assert(pindexFirst);
1335 // Limit adjustment step
1336 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1337 LogPrintf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1338 if (nActualTimespan < nTargetTimespan/4)
1339 nActualTimespan = nTargetTimespan/4;
1340 if (nActualTimespan > nTargetTimespan*4)
1341 nActualTimespan = nTargetTimespan*4;
1345 bnNew.SetCompact(pindexLast->nBits);
1346 bnNew *= nActualTimespan;
1347 bnNew /= nTargetTimespan;
1349 if (bnNew > Params().ProofOfWorkLimit())
1350 bnNew = Params().ProofOfWorkLimit();
1353 LogPrintf("GetNextWorkRequired RETARGET\n");
1354 LogPrintf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1355 LogPrintf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1356 LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1358 return bnNew.GetCompact();
1361 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1364 bnTarget.SetCompact(nBits);
1367 if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit())
1368 return error("CheckProofOfWork() : nBits below minimum work");
1370 // Check proof of work matches claimed amount
1371 if (hash > bnTarget.getuint256())
1372 return error("CheckProofOfWork() : hash doesn't match nBits");
1377 // Return maximum amount of blocks that other nodes claim to have
1378 int GetNumBlocksOfPeers()
1380 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1383 bool IsInitialBlockDownload()
1385 if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1387 static int64 nLastUpdate;
1388 static CBlockIndex* pindexLastBest;
1389 if (chainActive.Tip() != pindexLastBest)
1391 pindexLastBest = chainActive.Tip();
1392 nLastUpdate = GetTime();
1394 return (GetTime() - nLastUpdate < 10 &&
1395 chainActive.Tip()->GetBlockTime() < GetTime() - 24 * 60 * 60);
1398 bool fLargeWorkForkFound = false;
1399 bool fLargeWorkInvalidChainFound = false;
1400 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1402 void CheckForkWarningConditions()
1404 // Before we get past initial download, we cannot reliably alert about forks
1405 // (we assume we don't get stuck on a fork before the last checkpoint)
1406 if (IsInitialBlockDownload())
1409 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1410 // of our head, drop it
1411 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1412 pindexBestForkTip = NULL;
1414 if (pindexBestForkTip || nBestInvalidWork > chainActive.Tip()->nChainWork + (chainActive.Tip()->GetBlockWork() * 6).getuint256())
1416 if (!fLargeWorkForkFound)
1418 std::string strCmd = GetArg("-alertnotify", "");
1419 if (!strCmd.empty())
1421 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1422 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1423 boost::replace_all(strCmd, "%s", warning);
1424 boost::thread t(runCommand, strCmd); // thread runs free
1427 if (pindexBestForkTip)
1429 LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
1430 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString().c_str(),
1431 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString().c_str());
1432 fLargeWorkForkFound = true;
1436 LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1437 fLargeWorkInvalidChainFound = true;
1442 fLargeWorkForkFound = false;
1443 fLargeWorkInvalidChainFound = false;
1447 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1449 // If we are on a fork that is sufficiently large, set a warning flag
1450 CBlockIndex* pfork = pindexNewForkTip;
1451 CBlockIndex* plonger = chainActive.Tip();
1452 while (pfork && pfork != plonger)
1454 while (plonger && plonger->nHeight > pfork->nHeight)
1455 plonger = plonger->pprev;
1456 if (pfork == plonger)
1458 pfork = pfork->pprev;
1461 // We define a condition which we should warn the user about as a fork of at least 7 blocks
1462 // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1463 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1464 // hash rate operating on the fork.
1465 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1466 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1467 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1468 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1469 pindexNewForkTip->nChainWork - pfork->nChainWork > (pfork->GetBlockWork() * 7).getuint256() &&
1470 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1472 pindexBestForkTip = pindexNewForkTip;
1473 pindexBestForkBase = pfork;
1476 CheckForkWarningConditions();
1479 void static InvalidChainFound(CBlockIndex* pindexNew)
1481 if (pindexNew->nChainWork > nBestInvalidWork)
1483 nBestInvalidWork = pindexNew->nChainWork;
1484 pblocktree->WriteBestInvalidWork(CBigNum(nBestInvalidWork));
1485 uiInterface.NotifyBlocksChanged();
1487 LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1488 pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
1489 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1490 pindexNew->GetBlockTime()).c_str());
1491 LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1492 chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1493 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
1494 CheckForkWarningConditions();
1497 void static InvalidBlockFound(CBlockIndex *pindex) {
1498 pindex->nStatus |= BLOCK_FAILED_VALID;
1499 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1500 setBlockIndexValid.erase(pindex);
1501 InvalidChainFound(pindex);
1502 if (chainActive.Next(pindex)) {
1503 CValidationState stateDummy;
1504 ConnectBestBlock(stateDummy); // reorganise away from the failed block
1508 bool ConnectBestBlock(CValidationState &state) {
1510 CBlockIndex *pindexNewBest;
1513 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1514 if (it == setBlockIndexValid.rend())
1516 pindexNewBest = *it;
1519 if (pindexNewBest == chainActive.Tip() || (chainActive.Tip() && pindexNewBest->nChainWork == chainActive.Tip()->nChainWork))
1520 return true; // nothing to do
1523 CBlockIndex *pindexTest = pindexNewBest;
1524 std::vector<CBlockIndex*> vAttach;
1526 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1527 // mark descendants failed
1528 CBlockIndex *pindexFailed = pindexNewBest;
1529 while (pindexTest != pindexFailed) {
1530 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1531 setBlockIndexValid.erase(pindexFailed);
1532 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1533 pindexFailed = pindexFailed->pprev;
1535 InvalidChainFound(pindexNewBest);
1539 if (chainActive.Tip() == NULL || pindexTest->nChainWork > chainActive.Tip()->nChainWork)
1540 vAttach.push_back(pindexTest);
1542 if (pindexTest->pprev == NULL || chainActive.Next(pindexTest)) {
1543 reverse(vAttach.begin(), vAttach.end());
1544 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
1545 boost::this_thread::interruption_point();
1547 if (!SetBestChain(state, pindexSwitch))
1549 } catch(std::runtime_error &e) {
1550 return state.Abort(_("System error: ") + e.what());
1555 pindexTest = pindexTest->pprev;
1560 void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev)
1562 block.nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1564 // Updating time can change work required on testnet:
1566 block.nBits = GetNextWorkRequired(pindexPrev, &block);
1579 const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input)
1581 const CCoins &coins = GetCoins(input.prevout.hash);
1582 assert(coins.IsAvailable(input.prevout.n));
1583 return coins.vout[input.prevout.n];
1586 int64 CCoinsViewCache::GetValueIn(const CTransaction& tx)
1588 if (tx.IsCoinBase())
1592 for (unsigned int i = 0; i < tx.vin.size(); i++)
1593 nResult += GetOutputFor(tx.vin[i]).nValue;
1598 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
1600 // mark inputs spent
1601 if (!tx.IsCoinBase()) {
1602 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1603 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1605 assert(coins.Spend(txin.prevout, undo));
1606 txundo.vprevout.push_back(undo);
1611 assert(inputs.SetCoins(txhash, CCoins(tx, nHeight)));
1614 bool CCoinsViewCache::HaveInputs(const CTransaction& tx)
1616 if (!tx.IsCoinBase()) {
1617 // first check whether information about the prevout hash is available
1618 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1619 const COutPoint &prevout = tx.vin[i].prevout;
1620 if (!HaveCoins(prevout.hash))
1624 // then check whether the actual outputs are available
1625 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1626 const COutPoint &prevout = tx.vin[i].prevout;
1627 const CCoins &coins = GetCoins(prevout.hash);
1628 if (!coins.IsAvailable(prevout.n))
1635 bool CScriptCheck::operator()() const {
1636 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1637 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1638 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
1642 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1644 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1647 bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1649 if (!tx.IsCoinBase())
1652 pvChecks->reserve(tx.vin.size());
1654 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1655 // for an attacker to attempt to split the network.
1656 if (!inputs.HaveInputs(tx))
1657 return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString().c_str()));
1659 // While checking, GetBestBlock() refers to the parent block.
1660 // This is also true for mempool checks.
1661 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1664 for (unsigned int i = 0; i < tx.vin.size(); i++)
1666 const COutPoint &prevout = tx.vin[i].prevout;
1667 const CCoins &coins = inputs.GetCoins(prevout.hash);
1669 // If prev is coinbase, check that it's matured
1670 if (coins.IsCoinBase()) {
1671 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1672 return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
1675 // Check for negative or overflow input values
1676 nValueIn += coins.vout[prevout.n].nValue;
1677 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1678 return state.DoS(100, error("CheckInputs() : txin values out of range"));
1682 if (nValueIn < GetValueOut(tx))
1683 return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString().c_str()));
1685 // Tally transaction fees
1686 int64 nTxFee = nValueIn - GetValueOut(tx);
1688 return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString().c_str()));
1690 if (!MoneyRange(nFees))
1691 return state.DoS(100, error("CheckInputs() : nFees out of range"));
1693 // The first loop above does all the inexpensive checks.
1694 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1695 // Helps prevent CPU exhaustion attacks.
1697 // Skip ECDSA signature verification when connecting blocks
1698 // before the last block chain checkpoint. This is safe because block merkle hashes are
1699 // still computed and checked, and any change will be caught at the next checkpoint.
1700 if (fScriptChecks) {
1701 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1702 const COutPoint &prevout = tx.vin[i].prevout;
1703 const CCoins &coins = inputs.GetCoins(prevout.hash);
1706 CScriptCheck check(coins, tx, i, flags, 0);
1708 pvChecks->push_back(CScriptCheck());
1709 check.swap(pvChecks->back());
1710 } else if (!check()) {
1711 if (flags & SCRIPT_VERIFY_STRICTENC) {
1712 // For now, check whether the failure was caused by non-canonical
1713 // encodings or not; if so, don't trigger DoS protection.
1714 CScriptCheck check(coins, tx, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
1716 return state.Invalid();
1718 return state.DoS(100,false);
1729 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1731 assert(pindex == view.GetBestBlock());
1738 CBlockUndo blockUndo;
1739 CDiskBlockPos pos = pindex->GetUndoPos();
1741 return error("DisconnectBlock() : no undo data available");
1742 if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1743 return error("DisconnectBlock() : failure reading undo data");
1745 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1746 return error("DisconnectBlock() : block and undo data inconsistent");
1748 // undo transactions in reverse order
1749 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1750 const CTransaction &tx = block.vtx[i];
1751 uint256 hash = tx.GetHash();
1753 // check that all outputs are available
1754 if (!view.HaveCoins(hash)) {
1755 fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1756 view.SetCoins(hash, CCoins());
1758 CCoins &outs = view.GetCoins(hash);
1759 outs.ClearUnspendable();
1761 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1762 // The CCoins serialization does not serialize negative numbers.
1763 // No network rules currently depend on the version here, so an inconsistency is harmless
1764 // but it must be corrected before txout nversion ever influences a network rule.
1765 if (outsBlock.nVersion < 0)
1766 outs.nVersion = outsBlock.nVersion;
1767 if (outs != outsBlock)
1768 fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1774 if (i > 0) { // not coinbases
1775 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1776 if (txundo.vprevout.size() != tx.vin.size())
1777 return error("DisconnectBlock() : transaction and undo data inconsistent");
1778 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1779 const COutPoint &out = tx.vin[j].prevout;
1780 const CTxInUndo &undo = txundo.vprevout[j];
1782 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1783 if (undo.nHeight != 0) {
1784 // undo data contains height: this is the last output of the prevout tx being spent
1785 if (!coins.IsPruned())
1786 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1788 coins.fCoinBase = undo.fCoinBase;
1789 coins.nHeight = undo.nHeight;
1790 coins.nVersion = undo.nVersion;
1792 if (coins.IsPruned())
1793 fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1795 if (coins.IsAvailable(out.n))
1796 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1797 if (coins.vout.size() < out.n+1)
1798 coins.vout.resize(out.n+1);
1799 coins.vout[out.n] = undo.txout;
1800 if (!view.SetCoins(out.hash, coins))
1801 return error("DisconnectBlock() : cannot restore coin inputs");
1806 // move best block pointer to prevout block
1807 view.SetBestBlock(pindex->pprev);
1817 void static FlushBlockFile(bool fFinalize = false)
1819 LOCK(cs_LastBlockFile);
1821 CDiskBlockPos posOld(nLastBlockFile, 0);
1823 FILE *fileOld = OpenBlockFile(posOld);
1826 TruncateFile(fileOld, infoLastBlockFile.nSize);
1827 FileCommit(fileOld);
1831 fileOld = OpenUndoFile(posOld);
1834 TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
1835 FileCommit(fileOld);
1840 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1842 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1844 void ThreadScriptCheck() {
1845 RenameThread("bitcoin-scriptch");
1846 scriptcheckqueue.Thread();
1849 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1851 // Check it again in case a previous version let a bad block in
1852 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1855 // verify that the view's current state corresponds to the previous block
1856 assert(pindex->pprev == view.GetBestBlock());
1858 // Special case for the genesis block, skipping connection of its transactions
1859 // (its coinbase is unspendable)
1860 if (block.GetHash() == Params().HashGenesisBlock()) {
1861 view.SetBestBlock(pindex);
1865 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1867 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1868 // unless those are already completely spent.
1869 // If such overwrites are allowed, coinbases and transactions depending upon those
1870 // can be duplicated to remove the ability to spend the first instance -- even after
1871 // being sent to another address.
1872 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1873 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1874 // already refuses previously-known transaction ids entirely.
1875 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1876 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1877 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1878 // initial block download.
1879 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1880 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1881 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1882 if (fEnforceBIP30) {
1883 for (unsigned int i = 0; i < block.vtx.size(); i++) {
1884 uint256 hash = block.GetTxHash(i);
1885 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1886 return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"));
1890 // BIP16 didn't become active until Apr 1 2012
1891 int64 nBIP16SwitchTime = 1333238400;
1892 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1894 unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1895 (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1897 CBlockUndo blockundo;
1899 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1901 int64 nStart = GetTimeMicros();
1904 unsigned int nSigOps = 0;
1905 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1906 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1907 vPos.reserve(block.vtx.size());
1908 for (unsigned int i = 0; i < block.vtx.size(); i++)
1910 const CTransaction &tx = block.vtx[i];
1912 nInputs += tx.vin.size();
1913 nSigOps += GetLegacySigOpCount(tx);
1914 if (nSigOps > MAX_BLOCK_SIGOPS)
1915 return state.DoS(100, error("ConnectBlock() : too many sigops"));
1917 if (!tx.IsCoinBase())
1919 if (!view.HaveInputs(tx))
1920 return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
1922 if (fStrictPayToScriptHash)
1924 // Add in sigops done by pay-to-script-hash inputs;
1925 // this is to prevent a "rogue miner" from creating
1926 // an incredibly-expensive-to-validate block.
1927 nSigOps += GetP2SHSigOpCount(tx, view);
1928 if (nSigOps > MAX_BLOCK_SIGOPS)
1929 return state.DoS(100, error("ConnectBlock() : too many sigops"));
1932 nFees += view.GetValueIn(tx)-GetValueOut(tx);
1934 std::vector<CScriptCheck> vChecks;
1935 if (!CheckInputs(tx, state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1937 control.Add(vChecks);
1941 UpdateCoins(tx, state, view, txundo, pindex->nHeight, block.GetTxHash(i));
1942 if (!tx.IsCoinBase())
1943 blockundo.vtxundo.push_back(txundo);
1945 vPos.push_back(std::make_pair(block.GetTxHash(i), pos));
1946 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1948 int64 nTime = GetTimeMicros() - nStart;
1950 LogPrintf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)block.vtx.size(), 0.001 * nTime, 0.001 * nTime / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1952 if (GetValueOut(block.vtx[0]) > GetBlockValue(pindex->nHeight, nFees))
1953 return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", GetValueOut(block.vtx[0]), GetBlockValue(pindex->nHeight, nFees)));
1955 if (!control.Wait())
1956 return state.DoS(100, false);
1957 int64 nTime2 = GetTimeMicros() - nStart;
1959 LogPrintf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1964 // Write undo information to disk
1965 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1967 if (pindex->GetUndoPos().IsNull()) {
1969 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1970 return error("ConnectBlock() : FindUndoPos failed");
1971 if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1972 return state.Abort(_("Failed to write undo data"));
1974 // update nUndoPos in block index
1975 pindex->nUndoPos = pos.nPos;
1976 pindex->nStatus |= BLOCK_HAVE_UNDO;
1979 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1981 CDiskBlockIndex blockindex(pindex);
1982 if (!pblocktree->WriteBlockIndex(blockindex))
1983 return state.Abort(_("Failed to write block index"));
1987 if (!pblocktree->WriteTxIndex(vPos))
1988 return state.Abort(_("Failed to write transaction index"));
1990 // add this block to the view's block chain
1991 assert(view.SetBestBlock(pindex));
1993 // Watch for transactions paying to me
1994 for (unsigned int i = 0; i < block.vtx.size(); i++)
1995 SyncWithWallets(block.GetTxHash(i), block.vtx[i], &block, true);
2000 bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
2002 mempool.check(pcoinsTip);
2004 // All modifications to the coin state will be done in this cache.
2005 // Only when all have succeeded, we push it to pcoinsTip.
2006 CCoinsViewCache view(*pcoinsTip, true);
2008 // Find the fork (typically, there is none)
2009 CBlockIndex* pfork = view.GetBestBlock();
2010 CBlockIndex* plonger = pindexNew;
2011 while (pfork && pfork != plonger)
2013 while (plonger->nHeight > pfork->nHeight) {
2014 plonger = plonger->pprev;
2015 assert(plonger != NULL);
2017 if (pfork == plonger)
2019 pfork = pfork->pprev;
2020 assert(pfork != NULL);
2023 // List of what to disconnect (typically nothing)
2024 vector<CBlockIndex*> vDisconnect;
2025 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
2026 vDisconnect.push_back(pindex);
2028 // List of what to connect (typically only pindexNew)
2029 vector<CBlockIndex*> vConnect;
2030 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
2031 vConnect.push_back(pindex);
2032 reverse(vConnect.begin(), vConnect.end());
2034 if (vDisconnect.size() > 0) {
2035 LogPrintf("REORGANIZE: Disconnect %"PRIszu" blocks; %s...\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
2036 LogPrintf("REORGANIZE: Connect %"PRIszu" blocks; ...%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
2039 // Disconnect shorter branch
2040 list<CTransaction> vResurrect;
2041 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
2043 if (!ReadBlockFromDisk(block, pindex))
2044 return state.Abort(_("Failed to read block"));
2045 int64 nStart = GetTimeMicros();
2046 if (!DisconnectBlock(block, state, pindex, view))
2047 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
2049 LogPrintf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2051 // Queue memory transactions to resurrect.
2052 // We only do this for blocks after the last checkpoint (reorganisation before that
2053 // point should only happen with -reindex/-loadblock, or a misbehaving peer.
2054 BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx)
2055 if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
2056 vResurrect.push_front(tx);
2059 // Connect longer branch
2060 vector<CTransaction> vDelete;
2061 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
2063 if (!ReadBlockFromDisk(block, pindex))
2064 return state.Abort(_("Failed to read block"));
2065 int64 nStart = GetTimeMicros();
2066 if (!ConnectBlock(block, state, pindex, view)) {
2067 if (state.IsInvalid()) {
2068 InvalidChainFound(pindexNew);
2069 InvalidBlockFound(pindex);
2071 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
2074 LogPrintf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2076 // Queue memory transactions to delete
2077 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2078 vDelete.push_back(tx);
2081 // Flush changes to global coin state
2082 int64 nStart = GetTimeMicros();
2083 int nModified = view.GetCacheSize();
2084 assert(view.Flush());
2085 int64 nTime = GetTimeMicros() - nStart;
2087 LogPrintf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
2089 // Make sure it's successfully written to disk before changing memory structure
2090 bool fIsInitialDownload = IsInitialBlockDownload();
2091 if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
2092 // Typical CCoins structures on disk are around 100 bytes in size.
2093 // Pushing a new one to the database can cause it to be written
2094 // twice (once in the log, and once in the tables). This is already
2095 // an overestimation, as most will delete an existing entry or
2096 // overwrite one. Still, use a conservative safety factor of 2.
2097 if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
2098 return state.Error();
2101 if (!pcoinsTip->Flush())
2102 return state.Abort(_("Failed to write to coin database"));
2105 // At this point, all changes have been done to the database.
2106 // Proceed by updating the memory structures.
2108 // Register new best chain
2109 chainActive.SetTip(pindexNew);
2111 // Resurrect memory transactions that were in the disconnected branch
2112 BOOST_FOREACH(CTransaction& tx, vResurrect) {
2113 // ignore validation errors in resurrected transactions
2114 CValidationState stateDummy;
2115 if (!mempool.accept(stateDummy, tx, false, NULL))
2116 mempool.remove(tx, true);
2119 // Delete redundant memory transactions that are in the connected branch
2120 BOOST_FOREACH(CTransaction& tx, vDelete) {
2122 mempool.removeConflicts(tx);
2125 mempool.check(pcoinsTip);
2127 // Update best block in wallet (so we can detect restored wallets)
2128 if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
2129 ::SetBestChain(chainActive.GetLocator(pindexNew));
2132 nTimeBestReceived = GetTime();
2133 nTransactionsUpdated++;
2134 LogPrintf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
2135 chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2136 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str(),
2137 Checkpoints::GuessVerificationProgress(chainActive.Tip()));
2139 // Check the version of the last 100 blocks to see if we need to upgrade:
2140 if (!fIsInitialDownload)
2143 const CBlockIndex* pindex = chainActive.Tip();
2144 for (int i = 0; i < 100 && pindex != NULL; i++)
2146 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2148 pindex = pindex->pprev;
2151 LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2152 if (nUpgraded > 100/2)
2153 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2154 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2157 std::string strCmd = GetArg("-blocknotify", "");
2159 if (!fIsInitialDownload && !strCmd.empty())
2161 boost::replace_all(strCmd, "%s", chainActive.Tip()->GetBlockHash().GetHex());
2162 boost::thread t(runCommand, strCmd); // thread runs free
2169 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos)
2171 // Check for duplicate
2172 uint256 hash = block.GetHash();
2173 if (mapBlockIndex.count(hash))
2174 return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
2176 // Construct new block index object
2177 CBlockIndex* pindexNew = new CBlockIndex(block);
2179 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2180 pindexNew->phashBlock = &((*mi).first);
2181 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2182 if (miPrev != mapBlockIndex.end())
2184 pindexNew->pprev = (*miPrev).second;
2185 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2187 pindexNew->nTx = block.vtx.size();
2188 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
2189 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
2190 pindexNew->nFile = pos.nFile;
2191 pindexNew->nDataPos = pos.nPos;
2192 pindexNew->nUndoPos = 0;
2193 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
2194 setBlockIndexValid.insert(pindexNew);
2196 if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
2197 return state.Abort(_("Failed to write block index"));
2200 if (!ConnectBestBlock(state))
2203 if (pindexNew == chainActive.Tip())
2205 // Clear fork warning if its no longer applicable
2206 CheckForkWarningConditions();
2207 // Notify UI to display prev block's coinbase if it was ours
2208 static uint256 hashPrevBestCoinBase;
2209 UpdatedTransaction(hashPrevBestCoinBase);
2210 hashPrevBestCoinBase = block.GetTxHash(0);
2212 CheckForkWarningConditionsOnNewFork(pindexNew);
2214 if (!pblocktree->Flush())
2215 return state.Abort(_("Failed to sync block index"));
2217 uiInterface.NotifyBlocksChanged();
2222 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
2224 bool fUpdatedLast = false;
2226 LOCK(cs_LastBlockFile);
2229 if (nLastBlockFile != pos.nFile) {
2230 nLastBlockFile = pos.nFile;
2231 infoLastBlockFile.SetNull();
2232 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
2233 fUpdatedLast = true;
2236 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2237 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2238 FlushBlockFile(true);
2240 infoLastBlockFile.SetNull();
2241 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2242 fUpdatedLast = true;
2244 pos.nFile = nLastBlockFile;
2245 pos.nPos = infoLastBlockFile.nSize;
2248 infoLastBlockFile.nSize += nAddSize;
2249 infoLastBlockFile.AddBlock(nHeight, nTime);
2252 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2253 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2254 if (nNewChunks > nOldChunks) {
2255 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2256 FILE *file = OpenBlockFile(pos);
2258 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2259 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2264 return state.Error();
2268 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2269 return state.Abort(_("Failed to write file info"));
2271 pblocktree->WriteLastBlockFile(nLastBlockFile);
2276 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2280 LOCK(cs_LastBlockFile);
2282 unsigned int nNewSize;
2283 if (nFile == nLastBlockFile) {
2284 pos.nPos = infoLastBlockFile.nUndoSize;
2285 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2286 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2287 return state.Abort(_("Failed to write block info"));
2289 CBlockFileInfo info;
2290 if (!pblocktree->ReadBlockFileInfo(nFile, info))
2291 return state.Abort(_("Failed to read block info"));
2292 pos.nPos = info.nUndoSize;
2293 nNewSize = (info.nUndoSize += nAddSize);
2294 if (!pblocktree->WriteBlockFileInfo(nFile, info))
2295 return state.Abort(_("Failed to write block info"));
2298 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2299 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2300 if (nNewChunks > nOldChunks) {
2301 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2302 FILE *file = OpenUndoFile(pos);
2304 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2305 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2310 return state.Error();
2317 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2319 // These are checks that are independent of context
2320 // that can be verified before saving an orphan block.
2323 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2324 return state.DoS(100, error("CheckBlock() : size limits failed"));
2326 // Check proof of work matches claimed amount
2327 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
2328 return state.DoS(50, error("CheckBlock() : proof of work failed"));
2331 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2332 return state.Invalid(error("CheckBlock() : block timestamp too far in the future"));
2334 // First transaction must be coinbase, the rest must not be
2335 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2336 return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
2337 for (unsigned int i = 1; i < block.vtx.size(); i++)
2338 if (block.vtx[i].IsCoinBase())
2339 return state.DoS(100, error("CheckBlock() : more than one coinbase"));
2341 // Check transactions
2342 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2343 if (!CheckTransaction(tx, state))
2344 return error("CheckBlock() : CheckTransaction failed");
2346 // Build the merkle tree already. We need it anyway later, and it makes the
2347 // block cache the transaction hashes, which means they don't need to be
2348 // recalculated many times during this block's validation.
2349 block.BuildMerkleTree();
2351 // Check for duplicate txids. This is caught by ConnectInputs(),
2352 // but catching it earlier avoids a potential DoS attack:
2353 set<uint256> uniqueTx;
2354 for (unsigned int i = 0; i < block.vtx.size(); i++) {
2355 uniqueTx.insert(block.GetTxHash(i));
2357 if (uniqueTx.size() != block.vtx.size())
2358 return state.DoS(100, error("CheckBlock() : duplicate transaction"));
2360 unsigned int nSigOps = 0;
2361 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2363 nSigOps += GetLegacySigOpCount(tx);
2365 if (nSigOps > MAX_BLOCK_SIGOPS)
2366 return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2368 // Check merkle root
2369 if (fCheckMerkleRoot && block.hashMerkleRoot != block.vMerkleTree.back())
2370 return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2375 bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp)
2377 // Check for duplicate
2378 uint256 hash = block.GetHash();
2379 if (mapBlockIndex.count(hash))
2380 return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
2382 // Get prev block index
2383 CBlockIndex* pindexPrev = NULL;
2385 if (hash != Params().HashGenesisBlock()) {
2386 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2387 if (mi == mapBlockIndex.end())
2388 return state.DoS(10, error("AcceptBlock() : prev block not found"));
2389 pindexPrev = (*mi).second;
2390 nHeight = pindexPrev->nHeight+1;
2392 // Check proof of work
2393 if (block.nBits != GetNextWorkRequired(pindexPrev, &block))
2394 return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
2396 // Check timestamp against prev
2397 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2398 return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
2400 // Check that all transactions are finalized
2401 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2402 if (!IsFinalTx(tx, nHeight, block.GetBlockTime()))
2403 return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2405 // Check that the block chain matches the known block chain up to a checkpoint
2406 if (!Checkpoints::CheckBlock(nHeight, hash))
2407 return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2409 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2410 if (block.nVersion < 2)
2412 if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2413 (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2415 return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
2418 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2419 if (block.nVersion >= 2)
2421 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2422 if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2423 (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2425 CScript expect = CScript() << nHeight;
2426 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2427 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin()))
2428 return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2433 // Write block to history file
2435 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2436 CDiskBlockPos blockPos;
2439 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.nTime, dbp != NULL))
2440 return error("AcceptBlock() : FindBlockPos failed");
2442 if (!WriteBlockToDisk(block, blockPos))
2443 return state.Abort(_("Failed to write block"));
2444 if (!AddToBlockIndex(block, state, blockPos))
2445 return error("AcceptBlock() : AddToBlockIndex failed");
2446 } catch(std::runtime_error &e) {
2447 return state.Abort(_("System error: ") + e.what());
2450 // Relay inventory, but don't relay old inventory during initial block download
2451 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2452 if (chainActive.Tip()->GetBlockHash() == hash)
2455 BOOST_FOREACH(CNode* pnode, vNodes)
2456 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2457 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2463 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2465 unsigned int nFound = 0;
2466 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2468 if (pstart->nVersion >= minVersion)
2470 pstart = pstart->pprev;
2472 return (nFound >= nRequired);
2475 int64 CBlockIndex::GetMedianTime() const
2477 const CBlockIndex* pindex = this;
2478 for (int i = 0; i < nMedianTimeSpan/2; i++)
2480 if (!chainActive.Next(pindex))
2481 return GetBlockTime();
2482 pindex = chainActive.Next(pindex);
2484 return pindex->GetMedianTimePast();
2487 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
2489 // Filter out duplicate requests
2490 if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd)
2492 pnode->pindexLastGetBlocksBegin = pindexBegin;
2493 pnode->hashLastGetBlocksEnd = hashEnd;
2495 pnode->PushMessage("getblocks", chainActive.GetLocator(pindexBegin), hashEnd);
2498 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2500 // Check for duplicate
2501 uint256 hash = pblock->GetHash();
2502 if (mapBlockIndex.count(hash))
2503 return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
2504 if (mapOrphanBlocks.count(hash))
2505 return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
2507 // Preliminary checks
2508 if (!CheckBlock(*pblock, state))
2509 return error("ProcessBlock() : CheckBlock FAILED");
2511 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2512 if (pcheckpoint && pblock->hashPrevBlock != (chainActive.Tip() ? chainActive.Tip()->GetBlockHash() : uint256(0)))
2514 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2515 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2518 return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"));
2521 bnNewBlock.SetCompact(pblock->nBits);
2523 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2524 if (bnNewBlock > bnRequired)
2526 return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"));
2531 // If we don't already have its previous block, shunt it off to holding area until we get it
2532 if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2534 LogPrintf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
2536 // Accept orphans as long as there is a node to request its parents from
2538 CBlock* pblock2 = new CBlock(*pblock);
2539 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2540 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2542 // Ask this guy to fill in what we're missing
2543 PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(pblock2));
2549 if (!AcceptBlock(*pblock, state, dbp))
2550 return error("ProcessBlock() : AcceptBlock FAILED");
2552 // Recursively process any orphan blocks that depended on this one
2553 vector<uint256> vWorkQueue;
2554 vWorkQueue.push_back(hash);
2555 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2557 uint256 hashPrev = vWorkQueue[i];
2558 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2559 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2562 CBlock* pblockOrphan = (*mi).second;
2563 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
2564 CValidationState stateDummy;
2565 if (AcceptBlock(*pblockOrphan, stateDummy))
2566 vWorkQueue.push_back(pblockOrphan->GetHash());
2567 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2568 delete pblockOrphan;
2570 mapOrphanBlocksByPrev.erase(hashPrev);
2573 LogPrintf("ProcessBlock: ACCEPTED\n");
2584 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
2586 header = block.GetBlockHeader();
2588 vector<bool> vMatch;
2589 vector<uint256> vHashes;
2591 vMatch.reserve(block.vtx.size());
2592 vHashes.reserve(block.vtx.size());
2594 for (unsigned int i = 0; i < block.vtx.size(); i++)
2596 uint256 hash = block.vtx[i].GetHash();
2597 if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2599 vMatch.push_back(true);
2600 vMatchedTxn.push_back(make_pair(i, hash));
2603 vMatch.push_back(false);
2604 vHashes.push_back(hash);
2607 txn = CPartialMerkleTree(vHashes, vMatch);
2617 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2619 // hash at height 0 is the txids themself
2622 // calculate left hash
2623 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2624 // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2625 if (pos*2+1 < CalcTreeWidth(height-1))
2626 right = CalcHash(height-1, pos*2+1, vTxid);
2629 // combine subhashes
2630 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2634 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2635 // determine whether this node is the parent of at least one matched txid
2636 bool fParentOfMatch = false;
2637 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2638 fParentOfMatch |= vMatch[p];
2639 // store as flag bit
2640 vBits.push_back(fParentOfMatch);
2641 if (height==0 || !fParentOfMatch) {
2642 // if at height 0, or nothing interesting below, store hash and stop
2643 vHash.push_back(CalcHash(height, pos, vTxid));
2645 // otherwise, don't store any hash, but descend into the subtrees
2646 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2647 if (pos*2+1 < CalcTreeWidth(height-1))
2648 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2652 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2653 if (nBitsUsed >= vBits.size()) {
2654 // overflowed the bits array - failure
2658 bool fParentOfMatch = vBits[nBitsUsed++];
2659 if (height==0 || !fParentOfMatch) {
2660 // if at height 0, or nothing interesting below, use stored hash and do not descend
2661 if (nHashUsed >= vHash.size()) {
2662 // overflowed the hash array - failure
2666 const uint256 &hash = vHash[nHashUsed++];
2667 if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2668 vMatch.push_back(hash);
2671 // otherwise, descend into the subtrees to extract matched txids and hashes
2672 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2673 if (pos*2+1 < CalcTreeWidth(height-1))
2674 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2677 // and combine them before returning
2678 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2682 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2687 // calculate height of tree
2689 while (CalcTreeWidth(nHeight) > 1)
2692 // traverse the partial tree
2693 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2696 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2698 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2700 // An empty set will not work
2701 if (nTransactions == 0)
2703 // check for excessively high numbers of transactions
2704 if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2706 // there can never be more hashes provided than one for every txid
2707 if (vHash.size() > nTransactions)
2709 // there must be at least one bit per node in the partial tree, and at least one node per hash
2710 if (vBits.size() < vHash.size())
2712 // calculate height of tree
2714 while (CalcTreeWidth(nHeight) > 1)
2716 // traverse the partial tree
2717 unsigned int nBitsUsed = 0, nHashUsed = 0;
2718 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2719 // verify that no problems occured during the tree traversal
2722 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2723 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2725 // verify that all hashes were consumed
2726 if (nHashUsed != vHash.size())
2728 return hashMerkleRoot;
2737 bool AbortNode(const std::string &strMessage) {
2738 strMiscWarning = strMessage;
2739 LogPrintf("*** %s\n", strMessage.c_str());
2740 uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
2745 bool CheckDiskSpace(uint64 nAdditionalBytes)
2747 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2749 // Check for nMinDiskSpace bytes (currently 50MB)
2750 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2751 return AbortNode(_("Error: Disk space is low!"));
2756 CCriticalSection cs_LastBlockFile;
2757 CBlockFileInfo infoLastBlockFile;
2758 int nLastBlockFile = 0;
2760 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2764 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2765 boost::filesystem::create_directories(path.parent_path());
2766 FILE* file = fopen(path.string().c_str(), "rb+");
2767 if (!file && !fReadOnly)
2768 file = fopen(path.string().c_str(), "wb+");
2770 LogPrintf("Unable to open file %s\n", path.string().c_str());
2774 if (fseek(file, pos.nPos, SEEK_SET)) {
2775 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2783 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2784 return OpenDiskFile(pos, "blk", fReadOnly);
2787 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2788 return OpenDiskFile(pos, "rev", fReadOnly);
2791 CBlockIndex * InsertBlockIndex(uint256 hash)
2797 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2798 if (mi != mapBlockIndex.end())
2799 return (*mi).second;
2802 CBlockIndex* pindexNew = new CBlockIndex();
2804 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2805 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2806 pindexNew->phashBlock = &((*mi).first);
2811 bool static LoadBlockIndexDB()
2813 if (!pblocktree->LoadBlockIndexGuts())
2816 boost::this_thread::interruption_point();
2818 // Calculate nChainWork
2819 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2820 vSortedByHeight.reserve(mapBlockIndex.size());
2821 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2823 CBlockIndex* pindex = item.second;
2824 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2826 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2827 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2829 CBlockIndex* pindex = item.second;
2830 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
2831 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2832 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2833 setBlockIndexValid.insert(pindex);
2836 // Load block file info
2837 pblocktree->ReadLastBlockFile(nLastBlockFile);
2838 LogPrintf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2839 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2840 LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
2842 // Load nBestInvalidWork, OK if it doesn't exist
2843 CBigNum bnBestInvalidWork;
2844 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2845 nBestInvalidWork = bnBestInvalidWork.getuint256();
2847 // Check whether we need to continue reindexing
2848 bool fReindexing = false;
2849 pblocktree->ReadReindexing(fReindexing);
2850 fReindex |= fReindexing;
2852 // Check whether we have a transaction index
2853 pblocktree->ReadFlag("txindex", fTxIndex);
2854 LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2856 // Load hashBestChain pointer to end of best chain
2857 chainActive.SetTip(pcoinsTip->GetBestBlock());
2858 if (chainActive.Tip() == NULL)
2861 // register best chain
2862 LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
2863 chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(),
2864 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
2869 bool VerifyDB(int nCheckLevel, int nCheckDepth)
2871 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
2874 // Verify blocks in the best chain
2875 if (nCheckDepth <= 0)
2876 nCheckDepth = 1000000000; // suffices until the year 19000
2877 if (nCheckDepth > chainActive.Height())
2878 nCheckDepth = chainActive.Height();
2879 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2880 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2881 CCoinsViewCache coins(*pcoinsTip, true);
2882 CBlockIndex* pindexState = chainActive.Tip();
2883 CBlockIndex* pindexFailure = NULL;
2884 int nGoodTransactions = 0;
2885 CValidationState state;
2886 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
2888 boost::this_thread::interruption_point();
2889 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
2892 // check level 0: read from disk
2893 if (!ReadBlockFromDisk(block, pindex))
2894 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2895 // check level 1: verify block validity
2896 if (nCheckLevel >= 1 && !CheckBlock(block, state))
2897 return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2898 // check level 2: verify undo validity
2899 if (nCheckLevel >= 2 && pindex) {
2901 CDiskBlockPos pos = pindex->GetUndoPos();
2902 if (!pos.IsNull()) {
2903 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2904 return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2907 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2908 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2910 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
2911 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2912 pindexState = pindex->pprev;
2914 nGoodTransactions = 0;
2915 pindexFailure = pindex;
2917 nGoodTransactions += block.vtx.size();
2921 return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
2923 // check level 4: try reconnecting blocks
2924 if (nCheckLevel >= 4) {
2925 CBlockIndex *pindex = pindexState;
2926 while (pindex != chainActive.Tip()) {
2927 boost::this_thread::interruption_point();
2928 pindex = chainActive.Next(pindex);
2930 if (!ReadBlockFromDisk(block, pindex))
2931 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2932 if (!ConnectBlock(block, state, pindex, coins))
2933 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2937 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
2942 void UnloadBlockIndex()
2944 mapBlockIndex.clear();
2945 setBlockIndexValid.clear();
2946 chainActive.SetTip(NULL);
2947 nBestInvalidWork = 0;
2950 bool LoadBlockIndex()
2952 // Load block index from databases
2953 if (!fReindex && !LoadBlockIndexDB())
2959 bool InitBlockIndex() {
2960 // Check whether we're already initialized
2961 if (chainActive.Genesis() != NULL)
2964 // Use the provided setting for -txindex in the new database
2965 fTxIndex = GetBoolArg("-txindex", false);
2966 pblocktree->WriteFlag("txindex", fTxIndex);
2967 LogPrintf("Initializing databases...\n");
2969 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
2972 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
2973 // Start new block file
2974 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2975 CDiskBlockPos blockPos;
2976 CValidationState state;
2977 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
2978 return error("LoadBlockIndex() : FindBlockPos failed");
2979 if (!WriteBlockToDisk(block, blockPos))
2980 return error("LoadBlockIndex() : writing genesis block to disk failed");
2981 if (!AddToBlockIndex(block, state, blockPos))
2982 return error("LoadBlockIndex() : genesis block not accepted");
2983 } catch(std::runtime_error &e) {
2984 return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
2993 void PrintBlockTree()
2995 // pre-compute tree structure
2996 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2997 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2999 CBlockIndex* pindex = (*mi).second;
3000 mapNext[pindex->pprev].push_back(pindex);
3002 //while (rand() % 3 == 0)
3003 // mapNext[pindex->pprev].push_back(pindex);
3006 vector<pair<int, CBlockIndex*> > vStack;
3007 vStack.push_back(make_pair(0, chainActive.Genesis()));
3010 while (!vStack.empty())
3012 int nCol = vStack.back().first;
3013 CBlockIndex* pindex = vStack.back().second;
3016 // print split or gap
3017 if (nCol > nPrevCol)
3019 for (int i = 0; i < nCol-1; i++)
3023 else if (nCol < nPrevCol)
3025 for (int i = 0; i < nCol; i++)
3032 for (int i = 0; i < nCol; i++)
3037 ReadBlockFromDisk(block, pindex);
3038 LogPrintf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
3040 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
3041 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
3044 PrintWallets(block);
3046 // put the main time-chain first
3047 vector<CBlockIndex*>& vNext = mapNext[pindex];
3048 for (unsigned int i = 0; i < vNext.size(); i++)
3050 if (chainActive.Next(vNext[i]))
3052 swap(vNext[0], vNext[i]);
3058 for (unsigned int i = 0; i < vNext.size(); i++)
3059 vStack.push_back(make_pair(nCol+i, vNext[i]));
3063 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3065 int64 nStart = GetTimeMillis();
3069 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3070 uint64 nStartByte = 0;
3072 // (try to) skip already indexed part
3073 CBlockFileInfo info;
3074 if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
3075 nStartByte = info.nSize;
3076 blkdat.Seek(info.nSize);
3079 uint64 nRewind = blkdat.GetPos();
3080 while (blkdat.good() && !blkdat.eof()) {
3081 boost::this_thread::interruption_point();
3083 blkdat.SetPos(nRewind);
3084 nRewind++; // start one byte further next time, in case of failure
3085 blkdat.SetLimit(); // remove former limit
3086 unsigned int nSize = 0;
3089 unsigned char buf[4];
3090 blkdat.FindByte(Params().MessageStart()[0]);
3091 nRewind = blkdat.GetPos()+1;
3092 blkdat >> FLATDATA(buf);
3093 if (memcmp(buf, Params().MessageStart(), 4))
3097 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3099 } catch (std::exception &e) {
3100 // no valid block header found; don't complain
3105 uint64 nBlockPos = blkdat.GetPos();
3106 blkdat.SetLimit(nBlockPos + nSize);
3109 nRewind = blkdat.GetPos();
3112 if (nBlockPos >= nStartByte) {
3115 dbp->nPos = nBlockPos;
3116 CValidationState state;
3117 if (ProcessBlock(state, NULL, &block, dbp))
3119 if (state.IsError())
3122 } catch (std::exception &e) {
3123 LogPrintf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
3127 } catch(std::runtime_error &e) {
3128 AbortNode(_("Error: system error: ") + e.what());
3131 LogPrintf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3144 //////////////////////////////////////////////////////////////////////////////
3149 extern map<uint256, CAlert> mapAlerts;
3150 extern CCriticalSection cs_mapAlerts;
3152 string GetWarnings(string strFor)
3155 string strStatusBar;
3158 if (GetBoolArg("-testsafemode", false))
3161 if (!CLIENT_VERSION_IS_RELEASE)
3162 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3164 // Misc warnings like out of disk space and clock is wrong
3165 if (strMiscWarning != "")
3168 strStatusBar = strMiscWarning;
3171 if (fLargeWorkForkFound)
3174 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3176 else if (fLargeWorkInvalidChainFound)
3179 strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
3185 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3187 const CAlert& alert = item.second;
3188 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3190 nPriority = alert.nPriority;
3191 strStatusBar = alert.strStatusBar;
3196 if (strFor == "statusbar")
3197 return strStatusBar;
3198 else if (strFor == "rpc")
3200 assert(!"GetWarnings() : invalid parameter");
3211 //////////////////////////////////////////////////////////////////////////////
3217 bool static AlreadyHave(const CInv& inv)
3223 bool txInMap = false;
3226 txInMap = mempool.exists(inv.hash);
3228 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3229 pcoinsTip->HaveCoins(inv.hash);
3232 return mapBlockIndex.count(inv.hash) ||
3233 mapOrphanBlocks.count(inv.hash);
3235 // Don't know what it is, just say we already got one
3242 void static ProcessGetData(CNode* pfrom)
3244 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3246 vector<CInv> vNotFound;
3250 while (it != pfrom->vRecvGetData.end()) {
3251 // Don't bother if send buffer is too full to respond anyway
3252 if (pfrom->nSendSize >= SendBufferSize())
3255 const CInv &inv = *it;
3257 boost::this_thread::interruption_point();
3260 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3262 // Send block from disk
3263 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3264 if (mi != mapBlockIndex.end())
3267 ReadBlockFromDisk(block, (*mi).second);
3268 if (inv.type == MSG_BLOCK)
3269 pfrom->PushMessage("block", block);
3270 else // MSG_FILTERED_BLOCK)
3272 LOCK(pfrom->cs_filter);
3275 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3276 pfrom->PushMessage("merkleblock", merkleBlock);
3277 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3278 // This avoids hurting performance by pointlessly requiring a round-trip
3279 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3280 // they must either disconnect and retry or request the full block.
3281 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3282 // however we MUST always provide at least what the remote peer needs
3283 typedef std::pair<unsigned int, uint256> PairType;
3284 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3285 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3286 pfrom->PushMessage("tx", block.vtx[pair.first]);
3292 // Trigger them to send a getblocks request for the next batch of inventory
3293 if (inv.hash == pfrom->hashContinue)
3295 // Bypass PushInventory, this must send even if redundant,
3296 // and we want it right after the last block so they don't
3297 // wait for other stuff first.
3299 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3300 pfrom->PushMessage("inv", vInv);
3301 pfrom->hashContinue = 0;
3305 else if (inv.IsKnownType())
3307 // Send stream from relay memory
3308 bool pushed = false;
3311 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3312 if (mi != mapRelay.end()) {
3313 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3317 if (!pushed && inv.type == MSG_TX) {
3319 if (mempool.exists(inv.hash)) {
3320 CTransaction tx = mempool.lookup(inv.hash);
3321 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3324 pfrom->PushMessage("tx", ss);
3329 vNotFound.push_back(inv);
3333 // Track requests for our stuff.
3334 Inventory(inv.hash);
3338 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3340 if (!vNotFound.empty()) {
3341 // Let the peer know that we didn't find what it asked for, so it doesn't
3342 // have to wait around forever. Currently only SPV clients actually care
3343 // about this message: it's needed when they are recursively walking the
3344 // dependencies of relevant unconfirmed transactions. SPV clients want to
3345 // do that because they want to know about (and store and rebroadcast and
3346 // risk analyze) the dependencies of transactions relevant to them, without
3347 // having to download the entire memory pool.
3348 pfrom->PushMessage("notfound", vNotFound);
3352 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3354 RandAddSeedPerfmon();
3355 LogPrint("net", "received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3356 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3358 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3366 if (strCommand == "version")
3368 // Each connection can only send one version message
3369 if (pfrom->nVersion != 0)
3371 pfrom->Misbehaving(1);
3379 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3380 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3382 // disconnect from peers older than this proto version
3383 LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3384 pfrom->fDisconnect = true;
3388 if (pfrom->nVersion == 10300)
3389 pfrom->nVersion = 300;
3391 vRecv >> addrFrom >> nNonce;
3393 vRecv >> pfrom->strSubVer;
3395 vRecv >> pfrom->nStartingHeight;
3397 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3399 pfrom->fRelayTxes = true;
3401 if (pfrom->fInbound && addrMe.IsRoutable())
3403 pfrom->addrLocal = addrMe;
3407 // Disconnect if we connected to ourself
3408 if (nNonce == nLocalHostNonce && nNonce > 1)
3410 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3411 pfrom->fDisconnect = true;
3415 // Be shy and don't send version until we hear
3416 if (pfrom->fInbound)
3417 pfrom->PushVersion();
3419 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3423 pfrom->PushMessage("verack");
3424 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3426 if (!pfrom->fInbound)
3428 // Advertise our address
3429 if (!fNoListen && !IsInitialBlockDownload())
3431 CAddress addr = GetLocalAddress(&pfrom->addr);
3432 if (addr.IsRoutable())
3433 pfrom->PushAddress(addr);
3436 // Get recent addresses
3437 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3439 pfrom->PushMessage("getaddr");
3440 pfrom->fGetAddr = true;
3442 addrman.Good(pfrom->addr);
3444 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3446 addrman.Add(addrFrom, addrFrom);
3447 addrman.Good(addrFrom);
3454 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3455 item.second.RelayTo(pfrom);
3458 pfrom->fSuccessfullyConnected = true;
3460 LogPrintf("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());
3463 AddTimeData(pfrom->addr, nTime);
3464 cPeerBlockCounts.input(pfrom->nStartingHeight);
3468 else if (pfrom->nVersion == 0)
3470 // Must have a version message before anything else
3471 pfrom->Misbehaving(1);
3476 else if (strCommand == "verack")
3478 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3482 else if (strCommand == "addr")
3484 vector<CAddress> vAddr;
3487 // Don't want addr from older versions unless seeding
3488 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3490 if (vAddr.size() > 1000)
3492 pfrom->Misbehaving(20);
3493 return error("message addr size() = %"PRIszu"", vAddr.size());
3496 // Store the new addresses
3497 vector<CAddress> vAddrOk;
3498 int64 nNow = GetAdjustedTime();
3499 int64 nSince = nNow - 10 * 60;
3500 BOOST_FOREACH(CAddress& addr, vAddr)
3502 boost::this_thread::interruption_point();
3504 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3505 addr.nTime = nNow - 5 * 24 * 60 * 60;
3506 pfrom->AddAddressKnown(addr);
3507 bool fReachable = IsReachable(addr);
3508 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3510 // Relay to a limited number of other nodes
3513 // Use deterministic randomness to send to the same nodes for 24 hours
3514 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3515 static uint256 hashSalt;
3517 hashSalt = GetRandHash();
3518 uint64 hashAddr = addr.GetHash();
3519 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3520 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3521 multimap<uint256, CNode*> mapMix;
3522 BOOST_FOREACH(CNode* pnode, vNodes)
3524 if (pnode->nVersion < CADDR_TIME_VERSION)
3526 unsigned int nPointer;
3527 memcpy(&nPointer, &pnode, sizeof(nPointer));
3528 uint256 hashKey = hashRand ^ nPointer;
3529 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3530 mapMix.insert(make_pair(hashKey, pnode));
3532 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3533 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3534 ((*mi).second)->PushAddress(addr);
3537 // Do not store addresses outside our network
3539 vAddrOk.push_back(addr);
3541 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3542 if (vAddr.size() < 1000)
3543 pfrom->fGetAddr = false;
3544 if (pfrom->fOneShot)
3545 pfrom->fDisconnect = true;
3549 else if (strCommand == "inv")
3553 if (vInv.size() > MAX_INV_SZ)
3555 pfrom->Misbehaving(20);
3556 return error("message inv size() = %"PRIszu"", vInv.size());
3559 // find last block in inv vector
3560 unsigned int nLastBlock = (unsigned int)(-1);
3561 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3562 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3563 nLastBlock = vInv.size() - 1 - nInv;
3570 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3572 const CInv &inv = vInv[nInv];
3574 boost::this_thread::interruption_point();
3575 pfrom->AddInventoryKnown(inv);
3577 bool fAlreadyHave = AlreadyHave(inv);
3578 LogPrint("net", " got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3580 if (!fAlreadyHave) {
3581 if (!fImporting && !fReindex)
3583 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3584 PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3585 } else if (nInv == nLastBlock) {
3586 // In case we are on a very long side-chain, it is possible that we already have
3587 // the last block in an inv bundle sent in response to getblocks. Try to detect
3588 // this situation and push another getblocks to continue.
3589 PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0));
3591 LogPrintf("force request: %s\n", inv.ToString().c_str());
3594 // Track requests for our stuff
3595 Inventory(inv.hash);
3600 else if (strCommand == "getdata")
3604 if (vInv.size() > MAX_INV_SZ)
3606 pfrom->Misbehaving(20);
3607 return error("message getdata size() = %"PRIszu"", vInv.size());
3610 if (fDebugNet || (vInv.size() != 1))
3611 LogPrint("net", "received getdata (%"PRIszu" invsz)\n", vInv.size());
3613 if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
3614 LogPrint("net", "received getdata for: %s\n", vInv[0].ToString().c_str());
3616 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3617 ProcessGetData(pfrom);
3621 else if (strCommand == "getblocks")
3623 CBlockLocator locator;
3625 vRecv >> locator >> hashStop;
3629 // Find the last block the caller has in the main chain
3630 CBlockIndex* pindex = chainActive.FindFork(locator);
3632 // Send the rest of the chain
3634 pindex = chainActive.Next(pindex);
3636 LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
3637 for (; pindex; pindex = chainActive.Next(pindex))
3639 if (pindex->GetBlockHash() == hashStop)
3641 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
3644 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3647 // When this block is requested, we'll send an inv that'll make them
3648 // getblocks the next batch of inventory.
3649 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
3650 pfrom->hashContinue = pindex->GetBlockHash();
3657 else if (strCommand == "getheaders")
3659 CBlockLocator locator;
3661 vRecv >> locator >> hashStop;
3665 CBlockIndex* pindex = NULL;
3666 if (locator.IsNull())
3668 // If locator is null, return the hashStop block
3669 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3670 if (mi == mapBlockIndex.end())
3672 pindex = (*mi).second;
3676 // Find the last block the caller has in the main chain
3677 pindex = chainActive.FindFork(locator);
3679 pindex = chainActive.Next(pindex);
3682 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3683 vector<CBlock> vHeaders;
3685 LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
3686 for (; pindex; pindex = chainActive.Next(pindex))
3688 vHeaders.push_back(pindex->GetBlockHeader());
3689 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3692 pfrom->PushMessage("headers", vHeaders);
3696 else if (strCommand == "tx")
3698 vector<uint256> vWorkQueue;
3699 vector<uint256> vEraseQueue;
3703 CInv inv(MSG_TX, tx.GetHash());
3704 pfrom->AddInventoryKnown(inv);
3708 bool fMissingInputs = false;
3709 CValidationState state;
3710 if (mempool.accept(state, tx, true, &fMissingInputs))
3712 mempool.check(pcoinsTip);
3713 RelayTransaction(tx, inv.hash);
3714 mapAlreadyAskedFor.erase(inv);
3715 vWorkQueue.push_back(inv.hash);
3716 vEraseQueue.push_back(inv.hash);
3718 // Recursively process any orphan transactions that depended on this one
3719 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3721 uint256 hashPrev = vWorkQueue[i];
3722 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3723 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3726 const uint256& orphanHash = *mi;
3727 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash];
3728 bool fMissingInputs2 = false;
3729 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3730 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3731 // anyone relaying LegitTxX banned)
3732 CValidationState stateDummy;
3734 if (mempool.accept(stateDummy, orphanTx, true, &fMissingInputs2))
3736 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString().c_str());
3737 RelayTransaction(orphanTx, orphanHash);
3738 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
3739 vWorkQueue.push_back(orphanHash);
3740 vEraseQueue.push_back(orphanHash);
3742 else if (!fMissingInputs2)
3744 // invalid or too-little-fee orphan
3745 vEraseQueue.push_back(orphanHash);
3746 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString().c_str());
3748 mempool.check(pcoinsTip);
3752 BOOST_FOREACH(uint256 hash, vEraseQueue)
3753 EraseOrphanTx(hash);
3755 else if (fMissingInputs)
3759 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3760 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3762 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3765 if (state.IsInvalid(nDoS))
3767 pfrom->Misbehaving(nDoS);
3771 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3776 LogPrint("net", "received block %s\n", block.GetHash().ToString().c_str());
3779 CInv inv(MSG_BLOCK, block.GetHash());
3780 pfrom->AddInventoryKnown(inv);
3784 CValidationState state;
3785 if (ProcessBlock(state, pfrom, &block))
3786 mapAlreadyAskedFor.erase(inv);
3788 if (state.IsInvalid(nDoS))
3790 pfrom->Misbehaving(nDoS);
3794 else if (strCommand == "getaddr")
3796 pfrom->vAddrToSend.clear();
3797 vector<CAddress> vAddr = addrman.GetAddr();
3798 BOOST_FOREACH(const CAddress &addr, vAddr)
3799 pfrom->PushAddress(addr);
3803 else if (strCommand == "mempool")
3807 std::vector<uint256> vtxid;
3808 LOCK2(mempool.cs, pfrom->cs_filter);
3809 mempool.queryHashes(vtxid);
3811 BOOST_FOREACH(uint256& hash, vtxid) {
3812 CInv inv(MSG_TX, hash);
3813 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
3815 vInv.push_back(inv);
3816 if (vInv.size() == MAX_INV_SZ)
3819 if (vInv.size() > 0)
3820 pfrom->PushMessage("inv", vInv);
3824 else if (strCommand == "ping")
3826 if (pfrom->nVersion > BIP0031_VERSION)
3830 // Echo the message back with the nonce. This allows for two useful features:
3832 // 1) A remote node can quickly check if the connection is operational
3833 // 2) Remote nodes can measure the latency of the network thread. If this node
3834 // is overloaded it won't respond to pings quickly and the remote node can
3835 // avoid sending us more work, like chain download requests.
3837 // The nonce stops the remote getting confused between different pings: without
3838 // it, if the remote node sends a ping once per second and this node takes 5
3839 // seconds to respond to each, the 5th ping the remote sends would appear to
3840 // return very quickly.
3841 pfrom->PushMessage("pong", nonce);
3846 else if (strCommand == "pong")
3848 int64 pingUsecEnd = GetTimeMicros();
3850 size_t nAvail = vRecv.in_avail();
3851 bool bPingFinished = false;
3852 std::string sProblem;
3854 if (nAvail >= sizeof(nonce)) {
3857 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
3858 if (pfrom->nPingNonceSent != 0) {
3859 if (nonce == pfrom->nPingNonceSent) {
3860 // Matching pong received, this ping is no longer outstanding
3861 bPingFinished = true;
3862 int64 pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
3863 if (pingUsecTime > 0) {
3864 // Successful ping time measurement, replace previous
3865 pfrom->nPingUsecTime = pingUsecTime;
3867 // This should never happen
3868 sProblem = "Timing mishap";
3871 // Nonce mismatches are normal when pings are overlapping
3872 sProblem = "Nonce mismatch";
3874 // This is most likely a bug in another implementation somewhere, cancel this ping
3875 bPingFinished = true;
3876 sProblem = "Nonce zero";
3880 sProblem = "Unsolicited pong without ping";
3883 // This is most likely a bug in another implementation somewhere, cancel this ping
3884 bPingFinished = true;
3885 sProblem = "Short payload";
3888 if (!(sProblem.empty())) {
3889 LogPrint("net", "pong %s %s: %s, %"PRI64x" expected, %"PRI64x" received, %"PRIszu" bytes\n",
3890 pfrom->addr.ToString().c_str(),
3891 pfrom->strSubVer.c_str(),
3893 pfrom->nPingNonceSent,
3897 if (bPingFinished) {
3898 pfrom->nPingNonceSent = 0;
3903 else if (strCommand == "alert")
3908 uint256 alertHash = alert.GetHash();
3909 if (pfrom->setKnown.count(alertHash) == 0)
3911 if (alert.ProcessAlert())
3914 pfrom->setKnown.insert(alertHash);
3917 BOOST_FOREACH(CNode* pnode, vNodes)
3918 alert.RelayTo(pnode);
3922 // Small DoS penalty so peers that send us lots of
3923 // duplicate/expired/invalid-signature/whatever alerts
3924 // eventually get banned.
3925 // This isn't a Misbehaving(100) (immediate ban) because the
3926 // peer might be an older or different implementation with
3927 // a different signature key, etc.
3928 pfrom->Misbehaving(10);
3934 else if (strCommand == "filterload")
3936 CBloomFilter filter;
3939 if (!filter.IsWithinSizeConstraints())
3940 // There is no excuse for sending a too-large filter
3941 pfrom->Misbehaving(100);
3944 LOCK(pfrom->cs_filter);
3945 delete pfrom->pfilter;
3946 pfrom->pfilter = new CBloomFilter(filter);
3947 pfrom->pfilter->UpdateEmptyFull();
3949 pfrom->fRelayTxes = true;
3953 else if (strCommand == "filteradd")
3955 vector<unsigned char> vData;
3958 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3959 // and thus, the maximum size any matched object can have) in a filteradd message
3960 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3962 pfrom->Misbehaving(100);
3964 LOCK(pfrom->cs_filter);
3966 pfrom->pfilter->insert(vData);
3968 pfrom->Misbehaving(100);
3973 else if (strCommand == "filterclear")
3975 LOCK(pfrom->cs_filter);
3976 delete pfrom->pfilter;
3977 pfrom->pfilter = new CBloomFilter();
3978 pfrom->fRelayTxes = true;
3984 // Ignore unknown commands for extensibility
3988 // Update the last seen time for this node's address
3989 if (pfrom->fNetworkNode)
3990 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3991 AddressCurrentlyConnected(pfrom->addr);
3997 // requires LOCK(cs_vRecvMsg)
3998 bool ProcessMessages(CNode* pfrom)
4001 // LogPrintf("ProcessMessages(%"PRIszu" messages)\n", pfrom->vRecvMsg.size());
4005 // (4) message start
4013 if (!pfrom->vRecvGetData.empty())
4014 ProcessGetData(pfrom);
4016 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4017 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4018 // Don't bother if send buffer is too full to respond anyway
4019 if (pfrom->nSendSize >= SendBufferSize())
4023 CNetMessage& msg = *it;
4026 // LogPrintf("ProcessMessages(message %u msgsz, %"PRIszu" bytes, complete:%s)\n",
4027 // msg.hdr.nMessageSize, msg.vRecv.size(),
4028 // msg.complete() ? "Y" : "N");
4030 // end, if an incomplete message is found
4031 if (!msg.complete())
4034 // at this point, any failure means we can delete the current message
4037 // Scan for message start
4038 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4039 LogPrintf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
4045 CMessageHeader& hdr = msg.hdr;
4048 LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
4051 string strCommand = hdr.GetCommand();
4054 unsigned int nMessageSize = hdr.nMessageSize;
4057 CDataStream& vRecv = msg.vRecv;
4058 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4059 unsigned int nChecksum = 0;
4060 memcpy(&nChecksum, &hash, sizeof(nChecksum));
4061 if (nChecksum != hdr.nChecksum)
4063 LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4064 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
4072 fRet = ProcessMessage(pfrom, strCommand, vRecv);
4073 boost::this_thread::interruption_point();
4075 catch (std::ios_base::failure& e)
4077 if (strstr(e.what(), "end of data"))
4079 // Allow exceptions from under-length message on vRecv
4080 LogPrintf("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());
4082 else if (strstr(e.what(), "size too large"))
4084 // Allow exceptions from over-long size
4085 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
4089 PrintExceptionContinue(&e, "ProcessMessages()");
4092 catch (boost::thread_interrupted) {
4095 catch (std::exception& e) {
4096 PrintExceptionContinue(&e, "ProcessMessages()");
4098 PrintExceptionContinue(NULL, "ProcessMessages()");
4102 LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
4105 // In case the connection got shut down, its receive buffer was wiped
4106 if (!pfrom->fDisconnect)
4107 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4113 bool SendMessages(CNode* pto, bool fSendTrickle)
4116 // Don't send anything until we get their version message
4117 if (pto->nVersion == 0)
4123 bool pingSend = false;
4124 if (pto->fPingQueued) {
4125 // RPC ping request by user
4128 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
4129 // Ping automatically sent as a keepalive
4134 while (nonce == 0) {
4135 RAND_bytes((unsigned char*)&nonce, sizeof(nonce));
4137 pto->nPingNonceSent = nonce;
4138 pto->fPingQueued = false;
4139 if (pto->nVersion > BIP0031_VERSION) {
4140 // Take timestamp as close as possible before transmitting ping
4141 pto->nPingUsecStart = GetTimeMicros();
4142 pto->PushMessage("ping", nonce);
4144 // Peer is too old to support ping command with nonce, pong will never arrive, disable timing
4145 pto->nPingUsecStart = 0;
4146 pto->PushMessage("ping");
4150 // Address refresh broadcast
4151 static int64 nLastRebroadcast;
4152 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4156 BOOST_FOREACH(CNode* pnode, vNodes)
4158 // Periodically clear setAddrKnown to allow refresh broadcasts
4159 if (nLastRebroadcast)
4160 pnode->setAddrKnown.clear();
4162 // Rebroadcast our address
4165 CAddress addr = GetLocalAddress(&pnode->addr);
4166 if (addr.IsRoutable())
4167 pnode->PushAddress(addr);
4171 nLastRebroadcast = GetTime();
4179 vector<CAddress> vAddr;
4180 vAddr.reserve(pto->vAddrToSend.size());
4181 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4183 // returns true if wasn't already contained in the set
4184 if (pto->setAddrKnown.insert(addr).second)
4186 vAddr.push_back(addr);
4187 // receiver rejects addr messages larger than 1000
4188 if (vAddr.size() >= 1000)
4190 pto->PushMessage("addr", vAddr);
4195 pto->vAddrToSend.clear();
4197 pto->PushMessage("addr", vAddr);
4200 TRY_LOCK(cs_main, lockMain);
4205 if (pto->fStartSync && !fImporting && !fReindex) {
4206 pto->fStartSync = false;
4207 PushGetBlocks(pto, chainActive.Tip(), uint256(0));
4210 // Resend wallet transactions that haven't gotten in a block yet
4211 // Except during reindex, importing and IBD, when old wallet
4212 // transactions become unconfirmed and spams other nodes.
4213 if (!fReindex && !fImporting && !IsInitialBlockDownload())
4215 ResendWalletTransactions();
4219 // Message: inventory
4222 vector<CInv> vInvWait;
4224 LOCK(pto->cs_inventory);
4225 vInv.reserve(pto->vInventoryToSend.size());
4226 vInvWait.reserve(pto->vInventoryToSend.size());
4227 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4229 if (pto->setInventoryKnown.count(inv))
4232 // trickle out tx inv to protect privacy
4233 if (inv.type == MSG_TX && !fSendTrickle)
4235 // 1/4 of tx invs blast to all immediately
4236 static uint256 hashSalt;
4238 hashSalt = GetRandHash();
4239 uint256 hashRand = inv.hash ^ hashSalt;
4240 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4241 bool fTrickleWait = ((hashRand & 3) != 0);
4243 // always trickle our own transactions
4247 if (GetTransaction(inv.hash, wtx))
4249 fTrickleWait = true;
4254 vInvWait.push_back(inv);
4259 // returns true if wasn't already contained in the set
4260 if (pto->setInventoryKnown.insert(inv).second)
4262 vInv.push_back(inv);
4263 if (vInv.size() >= 1000)
4265 pto->PushMessage("inv", vInv);
4270 pto->vInventoryToSend = vInvWait;
4273 pto->PushMessage("inv", vInv);
4279 vector<CInv> vGetData;
4280 int64 nNow = GetTime() * 1000000;
4281 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4283 const CInv& inv = (*pto->mapAskFor.begin()).second;
4284 if (!AlreadyHave(inv))
4287 LogPrint("net", "sending getdata: %s\n", inv.ToString().c_str());
4288 vGetData.push_back(inv);
4289 if (vGetData.size() >= 1000)
4291 pto->PushMessage("getdata", vGetData);
4295 pto->mapAskFor.erase(pto->mapAskFor.begin());
4297 if (!vGetData.empty())
4298 pto->PushMessage("getdata", vGetData);
4315 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4316 for (; it1 != mapBlockIndex.end(); it1++)
4317 delete (*it1).second;
4318 mapBlockIndex.clear();
4321 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4322 for (; it2 != mapOrphanBlocks.end(); it2++)
4323 delete (*it2).second;
4324 mapOrphanBlocks.clear();
4326 // orphan transactions
4327 mapOrphanTransactions.clear();
4329 } instance_of_cmaincleanup;