LCOV - code coverage report
Current view: top level - src - bloom.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 133 162 82.1 %
Date: 2025-04-02 01:23:23 Functions: 15 20 75.0 %

          Line data    Source code
       1             : // Copyright (c) 2012-2014 The Bitcoin developers
       2             : // Copyright (c) 2017-2020 The PIVX Core developers
       3             : // Distributed under the MIT software license, see the accompanying
       4             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5             : 
       6             : #include "bloom.h"
       7             : 
       8             : #include "hash.h"
       9             : #include "primitives/transaction.h"
      10             : #include "script/script.h"
      11             : #include "script/standard.h"
      12             : #include "random.h"
      13             : #include "streams.h"
      14             : 
      15             : #include <math.h>
      16             : #include <stdlib.h>
      17             : 
      18             : 
      19             : #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
      20             : #define LN2 0.6931471805599453094172321214581765680755001343602552
      21             : 
      22         502 : CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
      23             :     /**
      24             :      * The ideal size for a bloom filter with a given number of elements and false positive rate is:
      25             :      * - nElements * log(fp rate) / ln(2)^2
      26             :      * We ignore filter parameters which will create a bloom filter larger than the protocol limits
      27             :      */
      28        1004 :     vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
      29             :     /**
      30             :      * The ideal number of hash functions is filter size * ln(2) / number of elements
      31             :      * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
      32             :      * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
      33             :      */
      34             :     isFull(false),
      35             :     isEmpty(false),
      36        1004 :     nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
      37             :     nTweak(nTweakIn),
      38         502 :     nFlags(nFlagsIn)
      39             : {
      40         502 : }
      41             : 
      42        7131 : inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
      43             : {
      44             :     // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
      45        7131 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
      46             : }
      47             : 
      48         343 : void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
      49             : {
      50         343 :     if (isFull)
      51             :         return;
      52        3704 :     for (unsigned int i = 0; i < nHashFuncs; i++) {
      53        3361 :         unsigned int nIndex = Hash(i, vKey);
      54             :         // Sets bit nIndex of vData
      55        3361 :         vData[nIndex >> 3] |= (1 << (7 & nIndex));
      56             :     }
      57         343 :     isEmpty = false;
      58             : }
      59             : 
      60           8 : void CBloomFilter::insert(const COutPoint& outpoint)
      61             : {
      62           8 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
      63           8 :     stream << outpoint;
      64          16 :     std::vector<unsigned char> data(stream.begin(), stream.end());
      65           8 :     insert(data);
      66           8 : }
      67             : 
      68           9 : void CBloomFilter::insert(const uint256& hash)
      69             : {
      70           9 :     std::vector<unsigned char> data(hash.begin(), hash.end());
      71           9 :     insert(data);
      72           9 : }
      73             : 
      74         737 : bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
      75             : {
      76         737 :     if (isFull) {
      77             :         return true;
      78             :     }
      79         737 :     if (isEmpty) {
      80             :         return false;
      81             :     }
      82        4111 :     for (unsigned int i = 0; i < nHashFuncs; i++) {
      83        3770 :         unsigned int nIndex = Hash(i, vKey);
      84             :         // Checks bit nIndex of vData
      85        3770 :         if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
      86             :             return false;
      87             :     }
      88             :     return true;
      89             : }
      90             : 
      91          88 : bool CBloomFilter::contains(const COutPoint& outpoint) const
      92             : {
      93          88 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
      94          88 :     stream << outpoint;
      95         176 :     std::vector<unsigned char> data(stream.begin(), stream.end());
      96         176 :     return contains(data);
      97             : }
      98             : 
      99          76 : bool CBloomFilter::contains(const uint256& hash) const
     100             : {
     101          76 :     std::vector<unsigned char> data(hash.begin(), hash.end());
     102         152 :     return contains(data);
     103             : }
     104             : 
     105         109 : void CBloomFilter::clear()
     106             : {
     107         109 :     vData.assign(vData.size(), 0);
     108         109 :     isFull = false;
     109         109 :     isEmpty = true;
     110         109 : }
     111             : 
     112           0 : void CBloomFilter::reset(const unsigned int nNewTweak)
     113             : {
     114           0 :     clear();
     115           0 :     nTweak = nNewTweak;
     116           0 : }
     117             : 
     118           0 : bool CBloomFilter::IsWithinSizeConstraints() const
     119             : {
     120           0 :     return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
     121             : }
     122             : 
     123             : /**
     124             :  * Returns true if this filter will match anything. See {@link org.pivxj.core.BloomFilter#setMatchAll()}
     125             :  * for when this can be a useful thing to do.
     126             :  */
     127           0 : bool CBloomFilter::MatchesAll() const {
     128           0 :     for (unsigned char b : vData)
     129           0 :         if (b !=  0xff)
     130           0 :             return false;
     131           0 :     return true;
     132             : }
     133             : 
     134             : /**
     135             :  * Copies filter into this. Filter must have the same size, hash function count and nTweak or an
     136             :  * IllegalArgumentException will be thrown.
     137             :  */
     138           0 : bool CBloomFilter::Merge(const CBloomFilter& filter) {
     139           0 :     if (!this->MatchesAll() && !filter.MatchesAll()) {
     140           0 :         if(! (filter.vData.size() == this->vData.size() &&
     141           0 :                 filter.nHashFuncs == this->nHashFuncs &&
     142           0 :                 filter.nTweak == this->nTweak)){
     143             :             return false;
     144             :         }
     145           0 :         for (unsigned int i = 0; i < vData.size(); i++)
     146           0 :             this->vData[i] |= filter.vData[i];
     147             :     } else {
     148             :         // TODO: Check this.
     149           0 :         this->vData.clear();
     150           0 :         this->vData[0] = 0xff;
     151             :     }
     152             :     return true;
     153             : }
     154             : 
     155       13262 : bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
     156             : {
     157       13262 :     bool fFound = false;
     158             :     // Match if the filter contains the hash of tx
     159             :     //  for finding tx when they appear in a block
     160       13262 :     if (isFull)
     161             :         return true;
     162          76 :     if (isEmpty)
     163             :         return false;
     164          76 :     const uint256& hash = tx.GetHash();
     165          76 :     if (contains(hash))
     166          13 :         fFound = true;
     167             : 
     168         199 :     for (unsigned int i = 0; i < tx.vout.size(); i++) {
     169         123 :         const CTxOut& txout = tx.vout[i];
     170             :         // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
     171             :         // If this matches, also add the specific output that was matched.
     172             :         // This means clients don't have to update the filter themselves when a new relevant tx
     173             :         // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
     174         123 :         CScript::const_iterator pc = txout.scriptPubKey.begin();
     175         246 :         std::vector<unsigned char> data;
     176        1206 :         while (pc < txout.scriptPubKey.end()) {
     177         490 :             opcodetype opcode;
     178         490 :             if (!txout.scriptPubKey.GetOp(pc, opcode, data)){
     179             :                 break;
     180             :             }
     181             : 
     182         490 :             if (data.size() != 0 && contains(data)) {
     183          10 :                 fFound = true;
     184          10 :                 if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     185           4 :                     insert(COutPoint(hash, i));
     186           6 :                 else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) {
     187           2 :                     txnouttype type;
     188           4 :                     std::vector<std::vector<unsigned char> > vSolutions;
     189           2 :                     if (Solver(txout.scriptPubKey, type, vSolutions) &&
     190           2 :                         (type == TX_PUBKEY || type == TX_MULTISIG))
     191           1 :                         insert(COutPoint(hash, i));
     192             :                 }
     193             :                 break;
     194             :             }
     195             :         }
     196             :     }
     197             : 
     198          76 :     if (fFound)
     199             :         return true;
     200             : 
     201         131 :     for (const CTxIn& txin : tx.vin) {
     202             :         // Match if the filter contains an outpoint tx spends
     203          84 :         if (contains(txin.prevout))
     204           6 :             return true;
     205             : 
     206             :         // Match if the filter contains any arbitrary script data element in any scriptSig in tx
     207          80 :         CScript::const_iterator pc = txin.scriptSig.begin();
     208         158 :         std::vector<unsigned char> data;
     209         416 :         while (pc < txin.scriptSig.end()) {
     210         130 :             opcodetype opcode;
     211         130 :             if (!txin.scriptSig.GetOp(pc, opcode, data))
     212             :                 break;
     213         130 :             if (data.size() != 0 && contains(data)) {
     214           2 :                 return true;
     215             :             }
     216             :         }
     217             :     }
     218             : 
     219          47 :     return false;
     220             : }
     221             : 
     222           0 : void CBloomFilter::UpdateEmptyFull()
     223             : {
     224           0 :     bool full = true;
     225           0 :     bool empty = true;
     226           0 :     for (unsigned int i = 0; i < vData.size(); i++) {
     227           0 :         full &= vData[i] == 0xff;
     228           0 :         empty &= vData[i] == 0;
     229             :     }
     230           0 :     isFull = full;
     231           0 :     isEmpty = empty;
     232           0 : }
     233             : 
     234        3358 : CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
     235             : {
     236        3358 :     double logFpRate = log(fpRate);
     237             :     /* The optimal number of hash functions is log(fpRate) / log(0.5), but
     238             :      * restrict it to the range 1-50. */
     239        3358 :     nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
     240             :     /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
     241        3358 :     nEntriesPerGeneration = (nElements + 1) / 2;
     242        3358 :     uint32_t nMaxElements = nEntriesPerGeneration * 3;
     243             :     /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
     244             :      * =>          pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
     245             :      * =>          1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
     246             :      * =>          log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
     247             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
     248             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
     249             :      */
     250        3358 :     uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
     251        3358 :     data.clear();
     252             :     /* For each data element we need to store 2 bits. If both bits are 0, the
     253             :      * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
     254             :      * treated as set in generation 1, 2, or 3 respectively.
     255             :      * These bits are stored in separate integers: position P corresponds to bit
     256             :      * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
     257        3358 :     data.resize(((nFilterBits + 63) / 64) << 1);
     258        3358 :     reset();
     259        3358 : }
     260             : 
     261             : /* Similar to CBloomFilter::Hash */
     262     7553205 : static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
     263     7553205 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
     264             : }
     265             : 
     266             : 
     267             : // A replacement for x % n. This assumes that x and n are 32bit integers, and x is a uniformly random distributed 32bit value
     268             : // which should be the case for a good hash.
     269             : // See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
     270     7553205 : static inline uint32_t FastMod(uint32_t x, size_t n) {
     271     7553205 :     return ((uint64_t)x * (uint64_t)n) >> 32;
     272             : }
     273             : 
     274      360996 : void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
     275             : {
     276      360996 :     if (nEntriesThisGeneration == nEntriesPerGeneration) {
     277          36 :         nEntriesThisGeneration = 0;
     278          36 :         nGeneration++;
     279          36 :         if (nGeneration == 4) {
     280          11 :             nGeneration = 1;
     281             :         }
     282          36 :         uint64_t nGenerationMask1 = -(uint64_t)(nGeneration & 1);
     283          36 :         uint64_t nGenerationMask2 = -(uint64_t)(nGeneration >> 1);
     284             :         /* Wipe old entries that used this generation number. */
     285       68214 :         for (uint32_t p = 0; p < data.size(); p += 2) {
     286       68178 :             uint64_t p1 = data[p], p2 = data[p + 1];
     287       68178 :             uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
     288       68178 :             data[p] = p1 & mask;
     289       68178 :             data[p + 1] = p2 & mask;
     290             :         }
     291             :     }
     292      360996 :     nEntriesThisGeneration++;
     293             : 
     294     7551945 :     for (int n = 0; n < nHashFuncs; n++) {
     295     7190949 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     296     7190949 :         int bit = h & 0x3F;
     297             :         /* 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. */
     298     7190949 :         uint32_t pos = FastMod(h, data.size());
     299             :         /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
     300     7190949 :         data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
     301     7190949 :         data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
     302             :     }
     303      360996 : }
     304             : 
     305      358638 : void CRollingBloomFilter::insert(const uint256& hash)
     306             : {
     307      358638 :     std::vector<unsigned char> data(hash.begin(), hash.end());
     308      358638 :     insert(data);
     309      358638 : }
     310             : 
     311       87217 : bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
     312             : {
     313      377700 :     for (int n = 0; n < nHashFuncs; n++) {
     314      362257 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     315      362257 :         int bit = h & 0x3F;
     316      362257 :         uint32_t pos = FastMod(h, data.size());
     317             :         /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
     318      362257 :         if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
     319             :             return false;
     320             :         }
     321             :     }
     322             :     return true;
     323             : }
     324             : 
     325       74558 : bool CRollingBloomFilter::contains(const uint256& hash) const
     326             : {
     327       74558 :     std::vector<unsigned char> data(hash.begin(), hash.end());
     328      149116 :     return contains(data);
     329             : }
     330             : 
     331        5440 : void CRollingBloomFilter::reset()
     332             : {
     333        5440 :     nTweak = GetRand(std::numeric_limits<unsigned int>::max());
     334        5440 :     nEntriesThisGeneration = 0;
     335        5440 :     nGeneration = 1;
     336   381022700 :     for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
     337   381017600 :         *it = 0;
     338             :     }
     339        5440 : }

Generated by: LCOV version 1.14