LCOV - code coverage report
Current view: top level - src/common - bloom.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 98.2 % 110 108
Test Date: 2024-08-28 04:44:32 Functions: 91.7 % 12 11
Branches: 74.1 % 108 80

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2012-2022 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/fastrange.h>
      15                 :             : 
      16                 :             : #include <algorithm>
      17                 :             : #include <cmath>
      18                 :             : #include <cstdlib>
      19                 :             : #include <limits>
      20                 :             : #include <vector>
      21                 :             : 
      22                 :             : static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
      23                 :             : static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
      24                 :             : 
      25                 :          22 : CBloomFilter::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)^2
      29                 :             :      * We ignore filter parameters which will create a bloom filter larger than the protocol limits
      30                 :             :      */
      31         [ +  - ]:          44 :     vData(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 elements
      34                 :             :      * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
      35                 :             :      * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
      36                 :             :      */
      37         [ +  - ]:          22 :     nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
      38                 :          22 :     nTweak(nTweakIn),
      39                 :          22 :     nFlags(nFlagsIn)
      40                 :             : {
      41                 :          22 : }
      42                 :             : 
      43                 :        1650 : inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, Span<const unsigned char> vDataToHash) const
      44                 :             : {
      45                 :             :     // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
      46                 :        1650 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
      47                 :             : }
      48                 :             : 
      49                 :          38 : void CBloomFilter::insert(Span<const unsigned char> vKey)
      50                 :             : {
      51         [ +  - ]:          38 :     if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
      52                 :             :         return;
      53         [ +  + ]:         654 :     for (unsigned int i = 0; i < nHashFuncs; i++)
      54                 :             :     {
      55                 :         616 :         unsigned int nIndex = Hash(i, vKey);
      56                 :             :         // Sets bit nIndex of vData
      57                 :         616 :         vData[nIndex >> 3] |= (1 << (7 & nIndex));
      58                 :             :     }
      59                 :             : }
      60                 :             : 
      61                 :           8 : void CBloomFilter::insert(const COutPoint& outpoint)
      62                 :             : {
      63                 :           8 :     DataStream stream{};
      64         [ +  - ]:           8 :     stream << outpoint;
      65         [ +  - ]:           8 :     insert(MakeUCharSpan(stream));
      66                 :           8 : }
      67                 :             : 
      68                 :         427 : bool CBloomFilter::contains(Span<const unsigned char> vKey) const
      69                 :             : {
      70         [ +  - ]:         427 :     if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
      71                 :             :         return true;
      72         [ +  + ]:        1071 :     for (unsigned int i = 0; i < nHashFuncs; i++)
      73                 :             :     {
      74                 :        1034 :         unsigned int nIndex = Hash(i, vKey);
      75                 :             :         // Checks bit nIndex of vData
      76         [ +  + ]:        1034 :         if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
      77                 :             :             return false;
      78                 :             :     }
      79                 :             :     return true;
      80                 :             : }
      81                 :             : 
      82                 :          88 : bool CBloomFilter::contains(const COutPoint& outpoint) const
      83                 :             : {
      84                 :          88 :     DataStream stream{};
      85         [ +  - ]:          88 :     stream << outpoint;
      86         [ +  - ]:          88 :     return contains(MakeUCharSpan(stream));
      87                 :          88 : }
      88                 :             : 
      89                 :           0 : bool CBloomFilter::IsWithinSizeConstraints() const
      90                 :             : {
      91   [ #  #  #  # ]:           0 :     return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
      92                 :             : }
      93                 :             : 
      94                 :          76 : bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
      95                 :             : {
      96                 :          76 :     bool fFound = false;
      97                 :             :     // Match if the filter contains the hash of tx
      98                 :             :     //  for finding tx when they appear in a block
      99         [ +  - ]:          76 :     if (vData.empty()) // zero-size = "match-all" filter
     100                 :             :         return true;
     101                 :          76 :     const Txid& hash = tx.GetHash();
     102         [ +  + ]:          76 :     if (contains(hash.ToUint256()))
     103                 :          13 :         fFound = true;
     104                 :             : 
     105         [ +  + ]:         199 :     for (unsigned int i = 0; i < tx.vout.size(); i++)
     106                 :             :     {
     107         [ +  + ]:         123 :         const CTxOut& txout = tx.vout[i];
     108                 :             :         // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
     109                 :             :         // 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 tx
     111                 :             :         // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
     112         [ +  + ]:         123 :         CScript::const_iterator pc = txout.scriptPubKey.begin();
     113                 :         123 :         std::vector<unsigned char> data;
     114         [ +  + ]:         603 :         while (pc < txout.scriptPubKey.end())
     115                 :             :         {
     116                 :         490 :             opcodetype opcode;
     117   [ +  -  +  - ]:         490 :             if (!txout.scriptPubKey.GetOp(pc, opcode, data))
     118                 :             :                 break;
     119   [ +  +  +  -  :         603 :             if (data.size() != 0 && contains(data))
             +  +  +  + ]
     120                 :             :             {
     121                 :          10 :                 fFound = true;
     122         [ +  + ]:          10 :                 if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     123         [ +  - ]:           4 :                     insert(COutPoint(hash, i));
     124         [ +  + ]:           6 :                 else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
     125                 :             :                 {
     126                 :           2 :                     std::vector<std::vector<unsigned char> > vSolutions;
     127         [ +  - ]:           2 :                     TxoutType type = Solver(txout.scriptPubKey, vSolutions);
     128         [ +  + ]:           2 :                     if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
     129         [ +  - ]:           1 :                         insert(COutPoint(hash, i));
     130                 :             :                     }
     131                 :           2 :                 }
     132                 :             :                 break;
     133                 :             :             }
     134                 :             :         }
     135                 :         123 :     }
     136                 :             : 
     137         [ +  + ]:          76 :     if (fFound)
     138                 :             :         return true;
     139                 :             : 
     140         [ +  + ]:         131 :     for (const CTxIn& txin : tx.vin)
     141                 :             :     {
     142                 :             :         // Match if the filter contains an outpoint tx spends
     143         [ +  + ]:          84 :         if (contains(txin.prevout))
     144                 :             :             return true;
     145                 :             : 
     146                 :             :         // Match if the filter contains any arbitrary script data element in any scriptSig in tx
     147         [ +  + ]:          80 :         CScript::const_iterator pc = txin.scriptSig.begin();
     148                 :          80 :         std::vector<unsigned char> data;
     149         [ +  + ]:         208 :         while (pc < txin.scriptSig.end())
     150                 :             :         {
     151                 :         130 :             opcodetype opcode;
     152   [ +  -  +  - ]:         130 :             if (!txin.scriptSig.GetOp(pc, opcode, data))
     153                 :             :                 break;
     154   [ +  -  +  -  :         258 :             if (data.size() != 0 && contains(data))
             +  +  +  + ]
     155                 :           2 :                 return true;
     156                 :             :         }
     157                 :          80 :     }
     158                 :             : 
     159                 :             :     return false;
     160                 :             : }
     161                 :             : 
     162         [ -  + ]:         174 : CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
     163                 :             : {
     164                 :         174 :     double logFpRate = log(fpRate);
     165                 :             :     /* The optimal number of hash functions is log(fpRate) / log(0.5), but
     166                 :             :      * restrict it to the range 1-50. */
     167   [ -  +  +  - ]:         174 :     nHashFuncs = 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. */
     169                 :         174 :     nEntriesPerGeneration = (nElements + 1) / 2;
     170                 :         174 :     uint32_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 / nFilterBits
     175                 :             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
     176                 :             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
     177                 :             :      */
     178                 :         174 :     uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
     179         [ +  - ]:         174 :     data.clear();
     180                 :             :     /* For each data element we need to store 2 bits. If both bits are 0, the
     181                 :             :      * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
     182                 :             :      * treated as set in generation 1, 2, or 3 respectively.
     183                 :             :      * These bits are stored in separate integers: position P corresponds to bit
     184                 :             :      * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
     185         [ +  - ]:         174 :     data.resize(((nFilterBits + 63) / 64) << 1);
     186                 :         174 :     reset();
     187                 :         174 : }
     188                 :             : 
     189                 :             : /* Similar to CBloomFilter::Hash */
     190                 :       54200 : static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, Span<const unsigned char> vDataToHash)
     191                 :             : {
     192                 :       54200 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
     193                 :             : }
     194                 :             : 
     195                 :        2205 : void CRollingBloomFilter::insert(Span<const unsigned char> vKey)
     196                 :             : {
     197         [ +  + ]:        2205 :     if (nEntriesThisGeneration == nEntriesPerGeneration) {
     198                 :          34 :         nEntriesThisGeneration = 0;
     199                 :          34 :         nGeneration++;
     200         [ +  + ]:          34 :         if (nGeneration == 4) {
     201                 :          11 :             nGeneration = 1;
     202                 :             :         }
     203                 :          34 :         uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
     204                 :          34 :         uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
     205                 :             :         /* Wipe old entries that used this generation number. */
     206         [ +  + ]:         816 :         for (uint32_t p = 0; p < data.size(); p += 2) {
     207                 :         782 :             uint64_t p1 = data[p], p2 = data[p + 1];
     208                 :         782 :             uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
     209                 :         782 :             data[p] = p1 & mask;
     210                 :         782 :             data[p + 1] = p2 & mask;
     211                 :             :         }
     212                 :             :     }
     213                 :        2205 :     nEntriesThisGeneration++;
     214                 :             : 
     215         [ +  + ]:       18944 :     for (int n = 0; n < nHashFuncs; n++) {
     216                 :       16739 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     217                 :       16739 :         int 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. */
     219                 :       16739 :         uint32_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. */
     221                 :       16739 :         data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
     222                 :       16739 :         data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
     223                 :             :     }
     224                 :        2205 : }
     225                 :             : 
     226                 :       12609 : bool CRollingBloomFilter::contains(Span<const unsigned char> vKey) const
     227                 :             : {
     228         [ +  + ]:       39740 :     for (int n = 0; n < nHashFuncs; n++) {
     229                 :       37461 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     230                 :       37461 :         int bit = h & 0x3F;
     231         [ +  + ]:       37461 :         uint32_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 */
     233         [ +  + ]:       37461 :         if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
     234                 :             :             return false;
     235                 :             :         }
     236                 :             :     }
     237                 :             :     return true;
     238                 :             : }
     239                 :             : 
     240                 :         177 : void CRollingBloomFilter::reset()
     241                 :             : {
     242                 :         177 :     nTweak = FastRandomContext().rand<unsigned int>();
     243                 :         177 :     nEntriesThisGeneration = 0;
     244                 :         177 :     nGeneration = 1;
     245                 :         177 :     std::fill(data.begin(), data.end(), 0);
     246                 :         177 : }
        

Generated by: LCOV version 2.0-1