Coverage Report

Created: 2026-08-25 19:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/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 <compare>
20
#include <vector>
21
22
static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
23
static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
24
25
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
1.31k
    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
1.31k
    nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
38
1.31k
    nTweak(nTweakIn),
39
1.31k
    nFlags(nFlagsIn)
40
1.31k
{
41
1.31k
}
42
43
inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, std::span<const unsigned char> vDataToHash) const
44
1.49M
{
45
    // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
46
1.49M
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
47
1.49M
}
48
49
void CBloomFilter::insert(std::span<const unsigned char> vKey)
50
89.1k
{
51
89.1k
    if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
  Branch (51:9): [True: 21.7k, False: 67.3k]
52
21.7k
        return;
53
371k
    for (unsigned int i = 0; i < nHashFuncs; i++)
  Branch (53:30): [True: 303k, False: 67.3k]
54
303k
    {
55
303k
        unsigned int nIndex = Hash(i, vKey);
56
        // Sets bit nIndex of vData
57
303k
        vData[nIndex >> 3] |= (1 << (7 & nIndex));
58
303k
    }
59
67.3k
}
60
61
void CBloomFilter::insert(const COutPoint& outpoint)
62
21.6k
{
63
21.6k
    DataStream stream{};
64
21.6k
    stream << outpoint;
65
21.6k
    insert(MakeUCharSpan(stream));
66
21.6k
}
67
68
bool CBloomFilter::contains(std::span<const unsigned char> vKey) const
69
587k
{
70
587k
    if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
  Branch (70:9): [True: 43.3k, False: 544k]
71
43.3k
        return true;
72
1.52M
    for (unsigned int i = 0; i < nHashFuncs; i++)
  Branch (72:30): [True: 1.18M, False: 334k]
73
1.18M
    {
74
1.18M
        unsigned int nIndex = Hash(i, vKey);
75
        // Checks bit nIndex of vData
76
1.18M
        if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
  Branch (76:13): [True: 209k, False: 977k]
77
209k
            return false;
78
1.18M
    }
79
334k
    return true;
80
544k
}
81
82
bool CBloomFilter::contains(const COutPoint& outpoint) const
83
68.1k
{
84
68.1k
    DataStream stream{};
85
68.1k
    stream << outpoint;
86
68.1k
    return contains(MakeUCharSpan(stream));
87
68.1k
}
88
89
bool CBloomFilter::IsWithinSizeConstraints() const
90
171k
{
91
171k
    return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
  Branch (91:12): [True: 171k, False: 4]
  Branch (91:53): [True: 171k, False: 308]
92
171k
}
93
94
bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
95
374k
{
96
374k
    bool fFound = false;
97
    // Match if the filter contains the hash of tx
98
    //  for finding tx when they appear in a block
99
374k
    if (vData.empty()) // zero-size = "match-all" filter
  Branch (99:9): [True: 283k, False: 90.7k]
100
283k
        return true;
101
90.7k
    const Txid& hash = tx.GetHash();
102
90.7k
    if (contains(hash.ToUint256()))
  Branch (102:9): [True: 77.4k, False: 13.3k]
103
77.4k
        fFound = true;
104
105
384k
    for (unsigned int i = 0; i < tx.vout.size(); i++)
  Branch (105:30): [True: 293k, False: 90.7k]
106
293k
    {
107
293k
        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
293k
        CScript::const_iterator pc = txout.scriptPubKey.begin();
113
293k
        std::vector<unsigned char> data;
114
1.57M
        while (pc < txout.scriptPubKey.end())
  Branch (114:16): [True: 1.50M, False: 72.2k]
115
1.50M
        {
116
1.50M
            opcodetype opcode;
117
1.50M
            if (!txout.scriptPubKey.GetOp(pc, opcode, data))
  Branch (117:17): [True: 76.6k, False: 1.42M]
118
76.6k
                break;
119
1.42M
            if (data.size() != 0 && contains(data))
  Branch (119:17): [True: 249k, False: 1.17M]
  Branch (119:37): [True: 144k, False: 105k]
120
144k
            {
121
144k
                fFound = true;
122
144k
                if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
  Branch (122:21): [True: 1.46k, False: 142k]
123
1.46k
                    insert(COutPoint(hash, i));
124
142k
                else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
  Branch (124:26): [True: 132k, False: 10.8k]
125
132k
                {
126
132k
                    std::vector<std::vector<unsigned char> > vSolutions;
127
132k
                    TxoutType type = Solver(txout.scriptPubKey, vSolutions);
128
132k
                    if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
  Branch (128:25): [True: 7.12k, False: 124k]
  Branch (128:54): [True: 1.98k, False: 122k]
129
9.10k
                        insert(COutPoint(hash, i));
130
9.10k
                    }
131
132k
                }
132
144k
                break;
133
144k
            }
134
1.42M
        }
135
293k
    }
136
137
90.7k
    if (fFound)
  Branch (137:9): [True: 78.0k, False: 12.6k]
138
78.0k
        return true;
139
140
12.6k
    for (const CTxIn& txin : tx.vin)
  Branch (140:28): [True: 45.9k, False: 9.82k]
141
45.9k
    {
142
        // Match if the filter contains an outpoint tx spends
143
45.9k
        if (contains(txin.prevout))
  Branch (143:13): [True: 1.56k, False: 44.4k]
144
1.56k
            return true;
145
146
        // Match if the filter contains any arbitrary script data element in any scriptSig in tx
147
44.4k
        CScript::const_iterator pc = txin.scriptSig.begin();
148
44.4k
        std::vector<unsigned char> data;
149
446k
        while (pc < txin.scriptSig.end())
  Branch (149:16): [True: 416k, False: 29.4k]
150
416k
        {
151
416k
            opcodetype opcode;
152
416k
            if (!txin.scriptSig.GetOp(pc, opcode, data))
  Branch (152:17): [True: 13.6k, False: 403k]
153
13.6k
                break;
154
403k
            if (data.size() != 0 && contains(data))
  Branch (154:17): [True: 45.1k, False: 357k]
  Branch (154:37): [True: 1.31k, False: 43.8k]
155
1.31k
                return true;
156
403k
        }
157
44.4k
    }
158
159
9.82k
    return false;
160
12.6k
}
161
162
CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
163
71.1k
{
164
71.1k
    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
71.1k
    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
71.1k
    nEntriesPerGeneration = CeilDiv(nElements, 2u);
170
71.1k
    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
71.1k
    uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
179
71.1k
    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
71.1k
    data.resize(CeilDiv(nFilterBits, 64u) << 1);
186
71.1k
    reset();
187
71.1k
}
188
189
/* Similar to CBloomFilter::Hash */
190
static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, std::span<const unsigned char> vDataToHash)
191
28.7M
{
192
28.7M
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
193
28.7M
}
194
195
void CRollingBloomFilter::insert(std::span<const unsigned char> vKey)
196
863k
{
197
863k
    if (nEntriesThisGeneration == nEntriesPerGeneration) {
  Branch (197:9): [True: 21.4k, False: 841k]
198
21.4k
        nEntriesThisGeneration = 0;
199
21.4k
        nGeneration++;
200
21.4k
        if (nGeneration == 4) {
  Branch (200:13): [True: 6.28k, False: 15.1k]
201
6.28k
            nGeneration = 1;
202
6.28k
        }
203
21.4k
        uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
204
21.4k
        uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
205
        /* Wipe old entries that used this generation number. */
206
157k
        for (uint32_t p = 0; p < data.size(); p += 2) {
  Branch (206:30): [True: 136k, False: 21.4k]
207
136k
            uint64_t p1 = data[p], p2 = data[p + 1];
208
136k
            uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
209
136k
            data[p] = p1 & mask;
210
136k
            data[p + 1] = p2 & mask;
211
136k
        }
212
21.4k
    }
213
863k
    nEntriesThisGeneration++;
214
215
14.0M
    for (int n = 0; n < nHashFuncs; n++) {
  Branch (215:21): [True: 13.1M, False: 863k]
216
13.1M
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
217
13.1M
        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
13.1M
        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
13.1M
        data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
222
13.1M
        data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
223
13.1M
    }
224
863k
}
225
226
bool CRollingBloomFilter::contains(std::span<const unsigned char> vKey) const
227
8.00M
{
228
15.8M
    for (int n = 0; n < nHashFuncs; n++) {
  Branch (228:21): [True: 15.5M, False: 379k]
229
15.5M
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
230
15.5M
        int bit = h & 0x3F;
231
15.5M
        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
15.5M
        if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
  Branch (233:13): [True: 7.62M, False: 7.89M]
234
7.62M
            return false;
235
7.62M
        }
236
15.5M
    }
237
379k
    return true;
238
8.00M
}
239
240
void CRollingBloomFilter::reset()
241
241k
{
242
241k
    nTweak = FastRandomContext().rand<unsigned int>();
243
241k
    nEntriesThisGeneration = 0;
244
241k
    nGeneration = 1;
245
241k
    std::fill(data.begin(), data.end(), 0);
246
241k
}