Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/common/bloom.cpp
Line
Count
Source
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/fastrange.h>
15
#include <util/overflow.h>
16
17
#include <algorithm>
18
#include <cmath>
19
#include <cstdlib>
20
#include <limits>
21
#include <vector>
22
23
static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
24
static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
25
26
CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
27
    /**
28
     * The ideal size for a bloom filter with a given number of elements and false positive rate is:
29
     * - nElements * log(fp rate) / ln(2)^2
30
     * We ignore filter parameters which will create a bloom filter larger than the protocol limits
31
     */
32
0
    vData(std::min((unsigned int)(-1  / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
33
    /**
34
     * The ideal number of hash functions is filter size * ln(2) / number of elements
35
     * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
36
     * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
37
     */
38
0
    nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
39
0
    nTweak(nTweakIn),
40
0
    nFlags(nFlagsIn)
41
0
{
42
0
}
43
44
inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, std::span<const unsigned char> vDataToHash) const
45
252k
{
46
    // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
47
252k
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
48
252k
}
49
50
void CBloomFilter::insert(std::span<const unsigned char> vKey)
51
3.61k
{
52
3.61k
    if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
  Branch (52:9): [True: 65, False: 3.55k]
53
65
        return;
54
76.2k
    for (unsigned int i = 0; i < nHashFuncs; i++)
  Branch (54:30): [True: 72.6k, False: 3.55k]
55
72.6k
    {
56
72.6k
        unsigned int nIndex = Hash(i, vKey);
57
        // Sets bit nIndex of vData
58
72.6k
        vData[nIndex >> 3] |= (1 << (7 & nIndex));
59
72.6k
    }
60
3.55k
}
61
62
void CBloomFilter::insert(const COutPoint& outpoint)
63
1.16k
{
64
1.16k
    DataStream stream{};
65
1.16k
    stream << outpoint;
66
1.16k
    insert(MakeUCharSpan(stream));
67
1.16k
}
68
69
bool CBloomFilter::contains(std::span<const unsigned char> vKey) const
70
131k
{
71
131k
    if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
  Branch (71:9): [True: 0, False: 131k]
72
0
        return true;
73
188k
    for (unsigned int i = 0; i < nHashFuncs; i++)
  Branch (73:30): [True: 179k, False: 8.45k]
74
179k
    {
75
179k
        unsigned int nIndex = Hash(i, vKey);
76
        // Checks bit nIndex of vData
77
179k
        if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
  Branch (77:13): [True: 123k, False: 56.7k]
78
123k
            return false;
79
179k
    }
80
8.45k
    return true;
81
131k
}
82
83
bool CBloomFilter::contains(const COutPoint& outpoint) const
84
38.2k
{
85
38.2k
    DataStream stream{};
86
38.2k
    stream << outpoint;
87
38.2k
    return contains(MakeUCharSpan(stream));
88
38.2k
}
89
90
bool CBloomFilter::IsWithinSizeConstraints() const
91
21.2k
{
92
21.2k
    return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
  Branch (92:12): [True: 21.2k, False: 0]
  Branch (92:53): [True: 21.1k, False: 74]
93
21.2k
}
94
95
bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
96
43.1k
{
97
43.1k
    bool fFound = false;
98
    // Match if the filter contains the hash of tx
99
    //  for finding tx when they appear in a block
100
43.1k
    if (vData.empty()) // zero-size = "match-all" filter
  Branch (100:9): [True: 321, False: 42.8k]
101
321
        return true;
102
42.8k
    const Txid& hash = tx.GetHash();
103
42.8k
    if (contains(hash.ToUint256()))
  Branch (103:9): [True: 2.97k, False: 39.8k]
104
2.97k
        fFound = true;
105
106
92.6k
    for (unsigned int i = 0; i < tx.vout.size(); i++)
  Branch (106:30): [True: 49.7k, False: 42.8k]
107
49.7k
    {
108
49.7k
        const CTxOut& txout = tx.vout[i];
109
        // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
110
        // If this matches, also add the specific output that was matched.
111
        // This means clients don't have to update the filter themselves when a new relevant tx
112
        // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
113
49.7k
        CScript::const_iterator pc = txout.scriptPubKey.begin();
114
49.7k
        std::vector<unsigned char> data;
115
146k
        while (pc < txout.scriptPubKey.end())
  Branch (115:16): [True: 101k, False: 44.9k]
116
101k
        {
117
101k
            opcodetype opcode;
118
101k
            if (!txout.scriptPubKey.GetOp(pc, opcode, data))
  Branch (118:17): [True: 0, False: 101k]
119
0
                break;
120
101k
            if (data.size() != 0 && contains(data))
  Branch (120:17): [True: 48.9k, False: 52.2k]
  Branch (120:37): [True: 4.88k, False: 44.0k]
121
4.88k
            {
122
4.88k
                fFound = true;
123
4.88k
                if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
  Branch (123:21): [True: 1.04k, False: 3.83k]
124
1.04k
                    insert(COutPoint(hash, i));
125
3.83k
                else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
  Branch (125:26): [True: 1.63k, False: 2.20k]
126
1.63k
                {
127
1.63k
                    std::vector<std::vector<unsigned char> > vSolutions;
128
1.63k
                    TxoutType type = Solver(txout.scriptPubKey, vSolutions);
129
1.63k
                    if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
  Branch (129:25): [True: 118, False: 1.51k]
  Branch (129:54): [True: 0, False: 1.51k]
130
118
                        insert(COutPoint(hash, i));
131
118
                    }
132
1.63k
                }
133
4.88k
                break;
134
4.88k
            }
135
101k
        }
136
49.7k
    }
137
138
42.8k
    if (fFound)
  Branch (138:9): [True: 5.15k, False: 37.6k]
139
5.15k
        return true;
140
141
37.6k
    for (const CTxIn& txin : tx.vin)
  Branch (141:28): [True: 38.2k, False: 37.0k]
142
38.2k
    {
143
        // Match if the filter contains an outpoint tx spends
144
38.2k
        if (contains(txin.prevout))
  Branch (144:13): [True: 375, False: 37.8k]
145
375
            return true;
146
147
        // Match if the filter contains any arbitrary script data element in any scriptSig in tx
148
37.8k
        CScript::const_iterator pc = txin.scriptSig.begin();
149
37.8k
        std::vector<unsigned char> data;
150
39.2k
        while (pc < txin.scriptSig.end())
  Branch (150:16): [True: 1.56k, False: 37.6k]
151
1.56k
        {
152
1.56k
            opcodetype opcode;
153
1.56k
            if (!txin.scriptSig.GetOp(pc, opcode, data))
  Branch (153:17): [True: 0, False: 1.56k]
154
0
                break;
155
1.56k
            if (data.size() != 0 && contains(data))
  Branch (155:17): [True: 1.56k, False: 7]
  Branch (155:37): [True: 230, False: 1.33k]
156
230
                return true;
157
1.56k
        }
158
37.8k
    }
159
160
37.0k
    return false;
161
37.6k
}
162
163
CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
164
26.9k
{
165
26.9k
    double logFpRate = log(fpRate);
166
    /* The optimal number of hash functions is log(fpRate) / log(0.5), but
167
     * restrict it to the range 1-50. */
168
26.9k
    nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
169
    /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
170
26.9k
    nEntriesPerGeneration = CeilDiv(nElements, 2u);
171
26.9k
    uint32_t nMaxElements = nEntriesPerGeneration * 3;
172
    /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
173
     * =>          pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
174
     * =>          1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
175
     * =>          log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
176
     * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
177
     * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
178
     */
179
26.9k
    uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
180
26.9k
    data.clear();
181
    /* For each data element we need to store 2 bits. If both bits are 0, the
182
     * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
183
     * treated as set in generation 1, 2, or 3 respectively.
184
     * These bits are stored in separate integers: position P corresponds to bit
185
     * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
186
26.9k
    data.resize(CeilDiv(nFilterBits, 64u) << 1);
187
26.9k
    reset();
188
26.9k
}
189
190
/* Similar to CBloomFilter::Hash */
191
static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, std::span<const unsigned char> vDataToHash)
192
151M
{
193
151M
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
194
151M
}
195
196
void CRollingBloomFilter::insert(std::span<const unsigned char> vKey)
197
6.31M
{
198
6.31M
    if (nEntriesThisGeneration == nEntriesPerGeneration) {
  Branch (198:9): [True: 0, False: 6.31M]
199
0
        nEntriesThisGeneration = 0;
200
0
        nGeneration++;
201
0
        if (nGeneration == 4) {
  Branch (201:13): [True: 0, False: 0]
202
0
            nGeneration = 1;
203
0
        }
204
0
        uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
205
0
        uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
206
        /* Wipe old entries that used this generation number. */
207
0
        for (uint32_t p = 0; p < data.size(); p += 2) {
  Branch (207:30): [True: 0, False: 0]
208
0
            uint64_t p1 = data[p], p2 = data[p + 1];
209
0
            uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
210
0
            data[p] = p1 & mask;
211
0
            data[p + 1] = p2 & mask;
212
0
        }
213
0
    }
214
6.31M
    nEntriesThisGeneration++;
215
216
126M
    for (int n = 0; n < nHashFuncs; n++) {
  Branch (216:21): [True: 119M, False: 6.31M]
217
119M
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
218
119M
        int bit = h & 0x3F;
219
        /* 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. */
220
119M
        uint32_t pos = FastRange32(h, data.size());
221
        /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
222
119M
        data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
223
119M
        data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
224
119M
    }
225
6.31M
}
226
227
bool CRollingBloomFilter::contains(std::span<const unsigned char> vKey) const
228
22.5M
{
229
32.3M
    for (int n = 0; n < nHashFuncs; n++) {
  Branch (229:21): [True: 31.8M, False: 492k]
230
31.8M
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
231
31.8M
        int bit = h & 0x3F;
232
31.8M
        uint32_t pos = FastRange32(h, data.size());
233
        /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
234
31.8M
        if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
  Branch (234:13): [True: 22.0M, False: 9.82M]
235
22.0M
            return false;
236
22.0M
        }
237
31.8M
    }
238
492k
    return true;
239
22.5M
}
240
241
void CRollingBloomFilter::reset()
242
239k
{
243
239k
    nTweak = FastRandomContext().rand<unsigned int>();
244
239k
    nEntriesThisGeneration = 0;
245
239k
    nGeneration = 1;
246
239k
    std::fill(data.begin(), data.end(), 0);
247
239k
}