LCOV - code coverage report
Current view: top level - src/common - bloom.cpp (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 166 190 87.4 %
Date: 2026-06-25 07:23:51 Functions: 17 18 94.4 %

          Line data    Source code
       1             : // Copyright (c) 2012-2021 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 <evo/assetlocktx.h>
       8             : #include <evo/providertx.h>
       9             : #include <evo/specialtx.h>
      10             : #include <hash.h>
      11             : #include <logging.h>
      12             : #include <primitives/transaction.h>
      13             : #include <random.h>
      14             : #include <script/script.h>
      15             : #include <script/standard.h>
      16             : #include <span.h>
      17             : #include <streams.h>
      18             : #include <util/fastrange.h>
      19             : 
      20             : #include <algorithm>
      21             : #include <cmath>
      22             : #include <cstdlib>
      23             : #include <limits>
      24             : #include <vector>
      25             : 
      26             : static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
      27             : static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
      28             : 
      29          70 : CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
      30             :     /**
      31             :      * The ideal size for a bloom filter with a given number of elements and false positive rate is:
      32             :      * - nElements * log(fp rate) / ln(2)^2
      33             :      * We ignore filter parameters which will create a bloom filter larger than the protocol limits
      34             :      */
      35          35 :     vData(std::min((unsigned int)(-1  / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
      36             :     /**
      37             :      * The ideal number of hash functions is filter size * ln(2) / number of elements
      38             :      * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
      39             :      * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
      40             :      */
      41          35 :     nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
      42          35 :     nTweak(nTweakIn),
      43          35 :     nFlags(nFlagsIn)
      44          35 : {
      45          70 : }
      46             : 
      47        2536 : inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, Span<const unsigned char> vDataToHash) const
      48             : {
      49             :     // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
      50        2536 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
      51             : }
      52             : 
      53          65 : void CBloomFilter::insert(Span<const unsigned char> vKey)
      54             : {
      55          65 :     if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
      56           0 :         return;
      57        1194 :     for (unsigned int i = 0; i < nHashFuncs; i++)
      58             :     {
      59        1129 :         unsigned int nIndex = Hash(i, vKey);
      60             :         // Sets bit nIndex of vData
      61        1129 :         vData[nIndex >> 3] |= (1 << (7 & nIndex));
      62        1129 :     }
      63          65 : }
      64             : 
      65          13 : void CBloomFilter::insert(const COutPoint& outpoint)
      66             : {
      67          13 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
      68          13 :     stream << outpoint;
      69          13 :     insert(MakeUCharSpan(stream));
      70          13 : }
      71             : 
      72         505 : bool CBloomFilter::contains(Span<const unsigned char> vKey) const
      73             : {
      74         505 :     if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
      75           0 :         return true;
      76        1460 :     for (unsigned int i = 0; i < nHashFuncs; i++)
      77             :     {
      78        1407 :         unsigned int nIndex = Hash(i, vKey);
      79             :         // Checks bit nIndex of vData
      80        1407 :         if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
      81         452 :             return false;
      82         955 :     }
      83          53 :     return true;
      84         505 : }
      85             : 
      86          97 : bool CBloomFilter::contains(const COutPoint& outpoint) const
      87             : {
      88          97 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
      89          97 :     stream << outpoint;
      90          97 :     return contains(MakeUCharSpan(stream));
      91          97 : }
      92             : 
      93           0 : bool CBloomFilter::IsWithinSizeConstraints() const
      94             : {
      95           0 :     return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
      96             : }
      97             : 
      98             : // Match if the filter contains any arbitrary script data element in script
      99         231 : bool CBloomFilter::CheckScript(const CScript &script) const
     100             : {
     101         231 :     CScript::const_iterator pc = script.begin();
     102         231 :     std::vector<unsigned char> data;
     103         937 :     while (pc < script.end()) {
     104             :         opcodetype opcode;
     105         723 :         if (!script.GetOp(pc, opcode, data))
     106           0 :             break;
     107         723 :         if (data.size() != 0 && contains(data))
     108          17 :             return true;
     109             :     }
     110         214 :     return false;
     111         231 : }
     112             : 
     113             : // If the transaction is a special transaction that has a registration
     114             : // transaction hash, test the registration transaction hash.
     115             : // If the transaction is a special transaction with any public keys or any
     116             : // public key hashes test them.
     117             : // If the transaction is a special transaction with payout addresses test
     118             : // the hash160 of those addresses.
     119             : // Filter is updated only if it has BLOOM_UPDATE_ALL flag to be able to have
     120             : // simple SPV wallets that doesn't work with DIP2 transactions (multicoin
     121             : // wallets, etc.)
     122             : // NOTE(maintenance): Keep this implementation in sync with
     123             : // ExtractSpecialTxFilterElements in src/evo/specialtx_filter.cpp.
     124             : // Both routines must handle the same set of special-transaction fields.
     125             : // If you modify one, update the other to prevent mismatches between
     126             : // bloom filter relevance and compact filter element extraction.
     127          81 : bool CBloomFilter::CheckSpecialTransactionMatchesAndUpdate(const CTransaction &tx)
     128             : {
     129          81 :     if (!tx.HasExtraPayloadField()) {
     130          63 :         return false; // it is not a special transaction
     131             :     }
     132          18 :     switch(tx.nType) {
     133             :     case(TRANSACTION_PROVIDER_REGISTER): {
     134          10 :         if (const auto opt_proTx = GetTxPayload<CProRegTx>(tx)) {
     135           6 :             if(contains(opt_proTx->collateralOutpoint) ||
     136           3 :                     contains(opt_proTx->keyIDOwner) ||
     137           2 :                     contains(opt_proTx->keyIDVoting) ||
     138           1 :                     CheckScript(opt_proTx->scriptPayout)) {
     139           5 :                 if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     140           5 :                     insert(tx.GetHash());
     141           5 :                 return true;
     142             :             }
     143           0 :         }
     144           0 :         return false;
     145             :     }
     146             :     case(TRANSACTION_PROVIDER_UPDATE_SERVICE): {
     147          12 :         if (const auto opt_proTx = GetTxPayload<CProUpServTx>(tx)) {
     148           6 :             if(contains(opt_proTx->proTxHash)) {
     149           3 :                 return true;
     150             :             }
     151           3 :             if(CheckScript(opt_proTx->scriptOperatorPayout)) {
     152           0 :                 if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     153           0 :                     insert(opt_proTx->proTxHash);
     154           0 :                 return true;
     155             :             }
     156           3 :         }
     157           3 :         return false;
     158             :     }
     159             :     case(TRANSACTION_PROVIDER_UPDATE_REGISTRAR): {
     160          10 :         if (const auto opt_proTx = GetTxPayload<CProUpRegTx>(tx)) {
     161           5 :             if(contains(opt_proTx->proTxHash))
     162           1 :                 return true;
     163           6 :             if(contains(opt_proTx->keyIDVoting) ||
     164           2 :                     CheckScript(opt_proTx->scriptPayout)) {
     165           3 :                 if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     166           3 :                     insert(opt_proTx->proTxHash);
     167           3 :                 return true;
     168             :             }
     169           1 :         }
     170           1 :         return false;
     171             :     }
     172             :     case(TRANSACTION_PROVIDER_UPDATE_REVOKE): {
     173           4 :         if (const auto opt_proTx = GetTxPayload<CProUpRevTx>(tx)) {
     174           2 :             if(contains(opt_proTx->proTxHash))
     175           1 :                 return true;
     176           1 :         }
     177           1 :         return false;
     178             :     }
     179             :     case(TRANSACTION_ASSET_LOCK): {
     180             :         // inputs of Asset Lock transactions are standard. But some outputs are special
     181           0 :         if (const auto opt_assetlockTx = GetTxPayload<CAssetLockPayload>(tx)) {
     182           0 :             bool fFound = false;
     183           0 :             const auto& extraOuts = opt_assetlockTx->getCreditOutputs();
     184           0 :             for (unsigned int i = 0; i < extraOuts.size(); ++i)
     185             :             {
     186           0 :                 fFound = ProcessTxOut(extraOuts[i], tx.GetHash(), i) || fFound;
     187           0 :             }
     188           0 :             if (fFound) return true;
     189           0 :         }
     190           0 :         return false;
     191             :     }
     192             :     case(TRANSACTION_ASSET_UNLOCK): // Outputs are standard and no inputs.
     193             :     case(TRANSACTION_COINBASE):
     194             :     case(TRANSACTION_QUORUM_COMMITMENT):
     195             :     case(TRANSACTION_MNHF_SIGNAL):
     196             :         // No additional checks for this transaction types
     197           0 :         return false;
     198             :     }
     199             : 
     200           0 :     LogPrintf("Unknown special transaction type in Bloom filter check.\n");
     201           0 :     return false;
     202          81 : }
     203             : 
     204         141 : bool CBloomFilter::ProcessTxOut(const CTxOut& txout, const uint256& hash, unsigned int index)
     205             : {
     206             :     // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
     207             :     // If this matches, also add the specific output that was matched.
     208             :     // This means clients don't have to update the filter themselves when a new relevant tx
     209             :     // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
     210         141 :     bool fFound = false;
     211         141 :     if(CheckScript(txout.scriptPubKey)) {
     212          13 :         fFound = true;
     213          13 :         if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
     214           7 :             insert(COutPoint(hash, index));
     215           6 :         else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
     216             :         {
     217           2 :             std::vector<std::vector<unsigned char> > vSolutions;
     218           2 :             TxoutType type = Solver(txout.scriptPubKey, vSolutions);
     219           2 :             if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
     220           1 :                 insert(COutPoint(hash, index));
     221           1 :             }
     222           2 :         }
     223          13 :     }
     224         141 :     return fFound;
     225           0 : }
     226             : 
     227          94 : bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
     228             : {
     229          94 :     bool fFound = false;
     230             :     // Match if the filter contains the hash of tx
     231             :     //  for finding tx when they appear in a block
     232          94 :     if (vData.empty()) // zero-size = "match-all" filter
     233           0 :         return true;
     234          94 :     const uint256& hash = tx.GetHash();
     235          94 :     if (contains(hash))
     236          13 :         fFound = true;
     237             : 
     238             :     // Check additional matches for special transactions
     239          94 :     fFound = fFound || CheckSpecialTransactionMatchesAndUpdate(tx);
     240             : 
     241         235 :     for (unsigned int i = 0; i < tx.vout.size(); i++)
     242             :     {
     243         141 :         fFound = ProcessTxOut(tx.vout[i], hash, i) || fFound;
     244         141 :     }
     245             : 
     246          94 :     if (fFound)
     247          37 :         return true;
     248             : 
     249         139 :     for (const CTxIn& txin : tx.vin)
     250             :     {
     251             :         // Match if the filter contains an outpoint tx spends
     252          88 :         if (contains(txin.prevout))
     253           4 :             return true;
     254             : 
     255             :         // Match if the filter contains any arbitrary script data element in any scriptSig in tx
     256          84 :         if(CheckScript(txin.scriptSig))
     257           2 :             return true;
     258             :     }
     259             : 
     260          51 :     return false;
     261          94 : }
     262             : 
     263        1206 : CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
     264         603 : {
     265         603 :     double logFpRate = log(fpRate);
     266             :     /* The optimal number of hash functions is log(fpRate) / log(0.5), but
     267             :      * restrict it to the range 1-50. */
     268         603 :     nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
     269             :     /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
     270         603 :     nEntriesPerGeneration = (nElements + 1) / 2;
     271         603 :     uint32_t nMaxElements = nEntriesPerGeneration * 3;
     272             :     /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
     273             :      * =>          pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
     274             :      * =>          1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
     275             :      * =>          log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
     276             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
     277             :      * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
     278             :      */
     279         603 :     uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
     280         603 :     data.clear();
     281             :     /* For each data element we need to store 2 bits. If both bits are 0, the
     282             :      * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
     283             :      * treated as set in generation 1, 2, or 3 respectively.
     284             :      * These bits are stored in separate integers: position P corresponds to bit
     285             :      * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
     286         603 :     data.resize(((nFilterBits + 63) / 64) << 1);
     287         603 :     reset();
     288        1206 : }
     289             : 
     290             : /* Similar to CBloomFilter::Hash */
     291       54059 : static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, Span<const unsigned char> vDataToHash)
     292             : {
     293       54059 :     return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
     294             : }
     295             : 
     296        2201 : void CRollingBloomFilter::insert(Span<const unsigned char> vKey)
     297             : {
     298        2201 :     if (nEntriesThisGeneration == nEntriesPerGeneration) {
     299          34 :         nEntriesThisGeneration = 0;
     300          34 :         nGeneration++;
     301          34 :         if (nGeneration == 4) {
     302          11 :             nGeneration = 1;
     303          11 :         }
     304          34 :         uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
     305          34 :         uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
     306             :         /* Wipe old entries that used this generation number. */
     307         816 :         for (uint32_t p = 0; p < data.size(); p += 2) {
     308         782 :             uint64_t p1 = data[p], p2 = data[p + 1];
     309         782 :             uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
     310         782 :             data[p] = p1 & mask;
     311         782 :             data[p + 1] = p2 & mask;
     312         782 :         }
     313          34 :     }
     314        2201 :     nEntriesThisGeneration++;
     315             : 
     316       18860 :     for (int n = 0; n < nHashFuncs; n++) {
     317       16659 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     318       16659 :         int bit = h & 0x3F;
     319             :         /* 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. */
     320       16659 :         uint32_t pos = FastRange32(h, data.size());
     321             :         /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
     322       16659 :         data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
     323       16659 :         data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
     324       16659 :     }
     325        2201 : }
     326             : 
     327       12610 : bool CRollingBloomFilter::contains(Span<const unsigned char> vKey) const
     328             : {
     329       39686 :     for (int n = 0; n < nHashFuncs; n++) {
     330       37400 :         uint32_t h = RollingBloomHash(n, nTweak, vKey);
     331       37400 :         int bit = h & 0x3F;
     332       37400 :         uint32_t pos = FastRange32(h, data.size());
     333             :         /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
     334       37400 :         if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
     335       10324 :             return false;
     336             :         }
     337       27076 :     }
     338        2286 :     return true;
     339       12610 : }
     340             : 
     341         605 : void CRollingBloomFilter::reset()
     342             : {
     343         605 :     nTweak = GetRand<unsigned int>();
     344         605 :     nEntriesThisGeneration = 0;
     345         605 :     nGeneration = 1;
     346         605 :     std::fill(data.begin(), data.end(), 0);
     347         605 : }

Generated by: LCOV version 1.16