LCOV - code coverage report
Current view: top level - src/common - bloom.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 100.0 % 115 115
Test Date: 2026-11-13 06:27:04 Functions: 100.0 % 13 13
Branches: 80.1 % 146 117

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2012-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <common/bloom.h>
       6                 :             : 
       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/check.h>
      15                 :             : #include <util/fastrange.h>
      16                 :             : #include <util/overflow.h>
      17                 :             : 
      18                 :             : #include <algorithm>
      19                 :             : #include <cmath>
      20                 :             : #include <compare>
      21                 :             : #include <vector>
      22                 :             : 
      23                 :             : static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
      24                 :             : static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
      25                 :             : 
      26                 :         804 : static unsigned int BloomFilterSize(const unsigned int elements, const double false_positive_rate)
      27                 :             : {
      28   [ +  -  +  -  :         804 :     Assert(std::isfinite(false_positive_rate) && false_positive_rate >= 0 && false_positive_rate <= 1);
                   -  + ]
      29         [ +  + ]:         804 :     if (elements == 0) return 0; // Must precede the zero-rate case to preserve empty-filter semantics.
      30         [ +  + ]:         772 :     if (false_positive_rate == 0) return MAX_BLOOM_FILTER_SIZE; // Avoid log(0) raising FE_DIVBYZERO.
      31         [ +  + ]:         664 :     return std::min(-1 / LN2SQUARED * elements * log(false_positive_rate), MAX_BLOOM_FILTER_SIZE * 8.0) / 8;
      32                 :             : }
      33                 :             : 
      34                 :         804 : CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
      35                 :             :     /**
      36                 :             :      * The ideal size for a bloom filter with a given number of elements and false positive rate is:
      37                 :             :      * - nElements * log(fp rate) / ln(2)^2
      38                 :             :      * We ignore filter parameters which will create a bloom filter larger than the protocol limits
      39                 :             :      */
      40                 :         804 :     vData(BloomFilterSize(nElements, nFPRate)),
      41                 :             :     /**
      42                 :             :      * The ideal number of hash functions is filter size * ln(2) / number of elements
      43                 :             :      * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
      44                 :             :      * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
      45                 :             :      */
      46   [ +  +  -  +  :         804 :     nHashFuncs(nElements == 0 ? 0 : std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
                   +  + ]
      47                 :         804 :     nTweak(nTweakIn),
      48                 :         804 :     nFlags(nFlagsIn)
      49                 :             : {
      50                 :         804 : }
      51                 :             : 
      52                 :       83532 : inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, std::span<const unsigned char> vDataToHash) const
      53                 :             : {
      54                 :             :     // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
      55         [ -  + ]:       83532 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
      56                 :             : }
      57                 :             : 
      58                 :       31769 : void CBloomFilter::insert(std::span<const unsigned char> vKey)
      59                 :             : {
      60         [ +  + ]:       31769 :     if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
      61                 :             :         return;
      62         [ +  + ]:       39851 :     for (unsigned int i = 0; i < nHashFuncs; i++)
      63                 :             :     {
      64                 :       12062 :         unsigned int nIndex = Hash(i, vKey);
      65                 :             :         // Sets bit nIndex of vData
      66                 :       12062 :         vData[nIndex >> 3] |= (1 << (7 & nIndex));
      67                 :             :     }
      68                 :             : }
      69                 :             : 
      70                 :        3764 : void CBloomFilter::insert(const COutPoint& outpoint)
      71                 :             : {
      72                 :        3764 :     DataStream stream{};
      73         [ +  - ]:        3764 :     stream << outpoint;
      74         [ +  - ]:        3764 :     insert(MakeUCharSpan(stream));
      75                 :        3764 : }
      76                 :             : 
      77                 :      140651 : bool CBloomFilter::contains(std::span<const unsigned char> vKey) const
      78                 :             : {
      79         [ +  + ]:      140651 :     if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
      80                 :             :         return true;
      81         [ +  + ]:      164529 :     for (unsigned int i = 0; i < nHashFuncs; i++)
      82                 :             :     {
      83                 :       71470 :         unsigned int nIndex = Hash(i, vKey);
      84                 :             :         // Checks bit nIndex of vData
      85         [ +  + ]:       71470 :         if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
      86                 :             :             return false;
      87                 :             :     }
      88                 :             :     return true;
      89                 :             : }
      90                 :             : 
      91                 :       20949 : bool CBloomFilter::contains(const COutPoint& outpoint) const
      92                 :             : {
      93                 :       20949 :     DataStream stream{};
      94         [ +  - ]:       20949 :     stream << outpoint;
      95         [ +  - ]:       20949 :     return contains(MakeUCharSpan(stream));
      96                 :       20949 : }
      97                 :             : 
      98                 :       56992 : bool CBloomFilter::IsWithinSizeConstraints() const
      99                 :             : {
     100   [ -  +  +  +  :       56992 :     return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
                   +  + ]
     101                 :             : }
     102                 :             : 
     103                 :      132958 : bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
     104                 :             : {
     105                 :      132958 :     bool fFound = false;
     106                 :             :     // Match if the filter contains the hash of tx
     107                 :             :     //  for finding tx when they appear in a block
     108         [ +  + ]:      132958 :     if (vData.empty()) // zero-size = "match-all" filter
     109                 :             :         return true;
     110                 :       21447 :     const Txid& hash = tx.GetHash();
     111         [ +  + ]:       21447 :     if (contains(hash.ToUint256()))
     112                 :       17179 :         fFound = true;
     113                 :             : 
     114   [ -  +  +  + ]:       76501 :     for (unsigned int i = 0; i < tx.vout.size(); i++)
     115                 :             :     {
     116         [ +  + ]:       55054 :         const CTxOut& txout = tx.vout[i];
     117                 :             :         // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
     118                 :             :         // If this matches, also add the specific output that was matched.
     119                 :             :         // This means clients don't have to update the filter themselves when a new relevant tx
     120                 :             :         // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
     121         [ +  + ]:       55054 :         CScript::const_iterator pc = txout.scriptPubKey.begin();
     122                 :       55054 :         std::vector<unsigned char> data;
     123   [ +  +  +  + ]:      366494 :         while (pc < txout.scriptPubKey.end())
     124                 :             :         {
     125                 :      165345 :             opcodetype opcode;
     126   [ +  -  +  + ]:      165345 :             if (!txout.scriptPubKey.GetOp(pc, opcode, data))
     127                 :             :                 break;
     128   [ -  +  +  +  :      164683 :             if (data.size() != 0 && contains(data))
          +  -  +  +  +  
                      + ]
     129                 :             :             {
     130                 :       22673 :                 fFound = true;
     131         [ +  + ]:       22673 :                 if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     132         [ +  - ]:         646 :                     insert(COutPoint(hash, i));
     133         [ +  + ]:       22027 :                 else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
     134                 :             :                 {
     135                 :        1165 :                     std::vector<std::vector<unsigned char> > vSolutions;
     136         [ +  - ]:        1165 :                     TxoutType type = Solver(txout.scriptPubKey, vSolutions);
     137         [ +  + ]:        1165 :                     if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
     138         [ +  - ]:         139 :                         insert(COutPoint(hash, i));
     139                 :             :                     }
     140                 :        1165 :                 }
     141                 :             :                 break;
     142                 :             :             }
     143                 :             :         }
     144                 :       55054 :     }
     145                 :             : 
     146         [ +  + ]:       21447 :     if (fFound)
     147                 :             :         return true;
     148                 :             : 
     149         [ +  + ]:       19049 :     for (const CTxIn& txin : tx.vin)
     150                 :             :     {
     151                 :             :         // Match if the filter contains an outpoint tx spends
     152         [ +  + ]:       14991 :         if (contains(txin.prevout))
     153                 :             :             return true;
     154                 :             : 
     155                 :             :         // Match if the filter contains any arbitrary script data element in any scriptSig in tx
     156         [ +  + ]:       14914 :         CScript::const_iterator pc = txin.scriptSig.begin();
     157                 :       14914 :         std::vector<unsigned char> data;
     158   [ +  +  +  + ]:      100268 :         while (pc < txin.scriptSig.end())
     159                 :             :         {
     160                 :       41053 :             opcodetype opcode;
     161   [ +  -  +  + ]:       41053 :             if (!txin.scriptSig.GetOp(pc, opcode, data))
     162                 :             :                 break;
     163   [ -  +  +  +  :       41713 :             if (data.size() != 0 && contains(data))
          +  -  +  +  +  
                      + ]
     164                 :         118 :                 return true;
     165                 :             :         }
     166                 :       14914 :     }
     167                 :             : 
     168                 :             :     return false;
     169                 :             : }
     170                 :             : 
     171         [ -  + ]:       46375 : CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
     172                 :             : {
     173                 :       46375 :     double logFpRate = log(fpRate);
     174                 :             :     /* The optimal number of hash functions is log(fpRate) / log(0.5), but
     175                 :             :      * restrict it to the range 1-50. */
     176   [ -  +  +  + ]:       46375 :     nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
     177                 :             :     /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
     178         [ +  - ]:       46375 :     nEntriesPerGeneration = CeilDiv(nElements, 2u);
     179                 :       46375 :     uint32_t nMaxElements = nEntriesPerGeneration * 3;
     180                 :             :     /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
     181                 :             :      * =>          pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
     182                 :             :      * =>          1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
     183                 :             :      * =>          log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
     184                 :             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
     185                 :             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
     186                 :             :      */
     187                 :       46375 :     uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
     188         [ +  - ]:       46375 :     data.clear();
     189                 :             :     /* For each data element we need to store 2 bits. If both bits are 0, the
     190                 :             :      * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
     191                 :             :      * treated as set in generation 1, 2, or 3 respectively.
     192                 :             :      * These bits are stored in separate integers: position P corresponds to bit
     193                 :             :      * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
     194         [ +  - ]:       46375 :     data.resize(CeilDiv(nFilterBits, 64u) << 1);
     195         [ +  - ]:       46375 :     reset();
     196                 :       46375 : }
     197                 :             : 
     198                 :             : /* Similar to CBloomFilter::Hash */
     199                 :    16123669 : static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, std::span<const unsigned char> vDataToHash)
     200                 :             : {
     201                 :    16123669 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
     202                 :             : }
     203                 :             : 
     204                 :      695112 : void CRollingBloomFilter::insert(std::span<const unsigned char> vKey)
     205                 :             : {
     206         [ +  + ]:      695112 :     if (nEntriesThisGeneration == nEntriesPerGeneration) {
     207                 :       21068 :         nEntriesThisGeneration = 0;
     208                 :       21068 :         nGeneration++;
     209         [ +  + ]:       21068 :         if (nGeneration == 4) {
     210                 :        6136 :             nGeneration = 1;
     211                 :             :         }
     212                 :       21068 :         uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
     213                 :       21068 :         uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
     214                 :             :         /* Wipe old entries that used this generation number. */
     215   [ -  +  +  + ]:      130520 :         for (uint32_t p = 0; p < data.size(); p += 2) {
     216                 :      109452 :             uint64_t p1 = data[p], p2 = data[p + 1];
     217                 :      109452 :             uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
     218                 :      109452 :             data[p] = p1 & mask;
     219                 :      109452 :             data[p + 1] = p2 & mask;
     220                 :             :         }
     221                 :             :     }
     222                 :      695112 :     nEntriesThisGeneration++;
     223                 :             : 
     224         [ +  + ]:    11435166 :     for (int n = 0; n < nHashFuncs; n++) {
     225                 :    10740054 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     226                 :    10740054 :         int bit = h & 0x3F;
     227                 :             :         /* 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. */
     228         [ -  + ]:    10740054 :         uint32_t pos = FastRange32(h, data.size());
     229                 :             :         /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
     230                 :    10740054 :         data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
     231                 :    10740054 :         data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
     232                 :             :     }
     233                 :      695112 : }
     234                 :             : 
     235                 :     1803681 : bool CRollingBloomFilter::contains(std::span<const unsigned char> vKey) const
     236                 :             : {
     237         [ +  + ]:     5556761 :     for (int n = 0; n < nHashFuncs; n++) {
     238                 :     5383615 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     239                 :     5383615 :         int bit = h & 0x3F;
     240   [ -  +  +  + ]:     5383615 :         uint32_t pos = FastRange32(h, data.size());
     241                 :             :         /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
     242         [ +  + ]:     5383615 :         if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
     243                 :             :             return false;
     244                 :             :         }
     245                 :             :     }
     246                 :             :     return true;
     247                 :             : }
     248                 :             : 
     249                 :      171873 : void CRollingBloomFilter::reset()
     250                 :             : {
     251                 :      171873 :     nTweak = FastRandomContext().rand<unsigned int>();
     252                 :      171873 :     nEntriesThisGeneration = 0;
     253                 :      171873 :     nGeneration = 1;
     254                 :      171873 :     std::fill(data.begin(), data.end(), 0);
     255                 :      171873 : }
        

Generated by: LCOV version 2.5.0-full