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

Generated by: LCOV version 1.14