Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2012-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <common/bloom.h>7#include <hash.h>8#include <primitives/transaction.h>9#include <random.h>10#include <script/script.h>11#include <script/solver.h>12#include <span.h>13#include <streams.h>14#include <util/fastrange.h>15#include <util/overflow.h>17#include <algorithm>18#include <cmath>19#include <compare>20#include <vector>22static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;23static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;25CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :26/**27* The ideal size for a bloom filter with a given number of elements and false positive rate is:28* - nElements * log(fp rate) / ln(2)^229* We ignore filter parameters which will create a bloom filter larger than the protocol limits30*/31vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),32/**33* The ideal number of hash functions is filter size * ln(2) / number of elements34* Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits35* See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas36*/37nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),38nTweak(nTweakIn),39nFlags(nFlagsIn)40{41}43inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, std::span<const unsigned char> vDataToHash) const44{45// 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.46return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);47}49void CBloomFilter::insert(std::span<const unsigned char> vKey)50{51if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)52return;53for (unsigned int i = 0; i < nHashFuncs; i++)54{55unsigned int nIndex = Hash(i, vKey);56// Sets bit nIndex of vData57vData[nIndex >> 3] |= (1 << (7 & nIndex));58}59}61void CBloomFilter::insert(const COutPoint& outpoint)62{63DataStream stream{};64stream << outpoint;65insert(MakeUCharSpan(stream));66}68bool CBloomFilter::contains(std::span<const unsigned char> vKey) const69{70if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)71return true;72for (unsigned int i = 0; i < nHashFuncs; i++)73{74unsigned int nIndex = Hash(i, vKey);75// Checks bit nIndex of vData76if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))77return false;78}79return true;80}82bool CBloomFilter::contains(const COutPoint& outpoint) const83{84DataStream stream{};85stream << outpoint;86return contains(MakeUCharSpan(stream));87}89bool CBloomFilter::IsWithinSizeConstraints() const90{91return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;92}94bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)95{96bool fFound = false;97// Match if the filter contains the hash of tx98// for finding tx when they appear in a block99if (vData.empty()) // zero-size = "match-all" filter100return true;101const Txid& hash = tx.GetHash();102if (contains(hash.ToUint256()))103fFound = true;105for (unsigned int i = 0; i < tx.vout.size(); i++)106{107const CTxOut& txout = tx.vout[i];108// Match if the filter contains any arbitrary script data element in any scriptPubKey in tx109// If this matches, also add the specific output that was matched.110// This means clients don't have to update the filter themselves when a new relevant tx111// is discovered in order to find spending transactions, which avoids round-tripping and race conditions.112CScript::const_iterator pc = txout.scriptPubKey.begin();113std::vector<unsigned char> data;114while (pc < txout.scriptPubKey.end())115{116opcodetype opcode;117if (!txout.scriptPubKey.GetOp(pc, opcode, data))118break;119if (data.size() != 0 && contains(data))120{121fFound = true;122if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)123insert(COutPoint(hash, i));124else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)125{126std::vector<std::vector<unsigned char> > vSolutions;127TxoutType type = Solver(txout.scriptPubKey, vSolutions);128if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {129insert(COutPoint(hash, i));130}131}132break;133}134}135}137if (fFound)138return true;140for (const CTxIn& txin : tx.vin)141{142// Match if the filter contains an outpoint tx spends143if (contains(txin.prevout))144return true;146// Match if the filter contains any arbitrary script data element in any scriptSig in tx147CScript::const_iterator pc = txin.scriptSig.begin();148std::vector<unsigned char> data;149while (pc < txin.scriptSig.end())150{151opcodetype opcode;152if (!txin.scriptSig.GetOp(pc, opcode, data))153break;154if (data.size() != 0 && contains(data))155return true;156}157}159return false;160}162CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)163{164double logFpRate = log(fpRate);165/* The optimal number of hash functions is log(fpRate) / log(0.5), but166* restrict it to the range 1-50. */167nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));168/* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */169nEntriesPerGeneration = CeilDiv(nElements, 2u);170uint32_t nMaxElements = nEntriesPerGeneration * 3;171/* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)172* => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)173* => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)174* => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits175* => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))176* => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))177*/178uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));179data.clear();180/* For each data element we need to store 2 bits. If both bits are 0, the181* bit is treated as unset. If the bits are (01), (10), or (11), the bit is182* treated as set in generation 1, 2, or 3 respectively.183* These bits are stored in separate integers: position P corresponds to bit184* (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */185data.resize(CeilDiv(nFilterBits, 64u) << 1);186reset();187}189/* Similar to CBloomFilter::Hash */190static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, std::span<const unsigned char> vDataToHash)191{192return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);193}195void CRollingBloomFilter::insert(std::span<const unsigned char> vKey)196{197if (nEntriesThisGeneration == nEntriesPerGeneration) {198nEntriesThisGeneration = 0;199nGeneration++;200if (nGeneration == 4) {201nGeneration = 1;202}203uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);204uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);205/* Wipe old entries that used this generation number. */206for (uint32_t p = 0; p < data.size(); p += 2) {207uint64_t p1 = data[p], p2 = data[p + 1];208uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);209data[p] = p1 & mask;210data[p + 1] = p2 & mask;211}212}213nEntriesThisGeneration++;215for (int n = 0; n < nHashFuncs; n++) {216uint32_t h = RollingBloomHash(n, nTweak, vKey);217int bit = h & 0x3F;218/* FastMod works with the upper bits of h, so it is safe to ignore that the lower bits of h are already used for bit. */219uint32_t pos = FastRange32(h, data.size());220/* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */221data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;222data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;223}224}226bool CRollingBloomFilter::contains(std::span<const unsigned char> vKey) const227{228for (int n = 0; n < nHashFuncs; n++) {229uint32_t h = RollingBloomHash(n, nTweak, vKey);230int bit = h & 0x3F;231uint32_t pos = FastRange32(h, data.size());232/* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */233if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {234return false;235}236}237return true;238}240void CRollingBloomFilter::reset()241{242nTweak = FastRandomContext().rand<unsigned int>();243nEntriesThisGeneration = 0;244nGeneration = 1;245std::fill(data.begin(), data.end(), 0);246}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.