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