Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
bloom.cpp
Go to the documentation of this file.
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>
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
23static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
24static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
25
26static unsigned int BloomFilterSize(const unsigned int elements, const double false_positive_rate)
27{
29 if (elements == 0) return 0; // Must precede the zero-rate case to preserve empty-filter semantics.
30 if (false_positive_rate == 0) return MAX_BLOOM_FILTER_SIZE; // Avoid log(0) raising FE_DIVBYZERO.
31 return std::min(-1 / LN2SQUARED * elements * log(false_positive_rate), MAX_BLOOM_FILTER_SIZE * 8.0) / 8;
32}
33
34CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
46 nHashFuncs(nElements == 0 ? 0 : std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
47 nTweak(nTweakIn),
48 nFlags(nFlagsIn)
49{
50}
51
52inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, std::span<const unsigned char> vDataToHash) const
53{
54 // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
55 return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
56}
57
58void CBloomFilter::insert(std::span<const unsigned char> vKey)
59{
60 if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
61 return;
62 for (unsigned int i = 0; i < nHashFuncs; i++)
63 {
64 unsigned int nIndex = Hash(i, vKey);
65 // Sets bit nIndex of vData
66 vData[nIndex >> 3] |= (1 << (7 & nIndex));
67 }
68}
69
70void CBloomFilter::insert(const COutPoint& outpoint)
71{
73 stream << outpoint;
75}
76
77bool CBloomFilter::contains(std::span<const unsigned char> vKey) const
78{
79 if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
80 return true;
81 for (unsigned int i = 0; i < nHashFuncs; i++)
82 {
83 unsigned int nIndex = Hash(i, vKey);
84 // Checks bit nIndex of vData
85 if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
86 return false;
87 }
88 return true;
89}
90
91bool CBloomFilter::contains(const COutPoint& outpoint) const
92{
94 stream << outpoint;
96}
97
102
104{
105 bool fFound = false;
106 // Match if the filter contains the hash of tx
107 // for finding tx when they appear in a block
108 if (vData.empty()) // zero-size = "match-all" filter
109 return true;
110 const Txid& hash = tx.GetHash();
111 if (contains(hash.ToUint256()))
112 fFound = true;
113
114 for (unsigned int i = 0; i < tx.vout.size(); i++)
115 {
116 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.
122 std::vector<unsigned char> data;
123 while (pc < txout.scriptPubKey.end())
124 {
126 if (!txout.scriptPubKey.GetOp(pc, opcode, data))
127 break;
128 if (data.size() != 0 && contains(data))
129 {
130 fFound = true;
132 insert(COutPoint(hash, i));
134 {
135 std::vector<std::vector<unsigned char> > vSolutions;
137 if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
138 insert(COutPoint(hash, i));
139 }
140 }
141 break;
142 }
143 }
144 }
145
146 if (fFound)
147 return true;
148
149 for (const CTxIn& txin : tx.vin)
150 {
151 // Match if the filter contains an outpoint tx spends
152 if (contains(txin.prevout))
153 return true;
154
155 // Match if the filter contains any arbitrary script data element in any scriptSig in tx
156 CScript::const_iterator pc = txin.scriptSig.begin();
157 std::vector<unsigned char> data;
158 while (pc < txin.scriptSig.end())
159 {
161 if (!txin.scriptSig.GetOp(pc, opcode, data))
162 break;
163 if (data.size() != 0 && contains(data))
164 return true;
165 }
166 }
167
168 return false;
169}
170
172{
173 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 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. */
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 */
188 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 data.resize(CeilDiv(nFilterBits, 64u) << 1);
195 reset();
196}
197
198/* Similar to CBloomFilter::Hash */
199static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, std::span<const unsigned char> vDataToHash)
200{
201 return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
202}
203
204void CRollingBloomFilter::insert(std::span<const unsigned char> vKey)
205{
208 nGeneration++;
209 if (nGeneration == 4) {
210 nGeneration = 1;
211 }
214 /* Wipe old entries that used this generation number. */
215 for (uint32_t p = 0; p < data.size(); p += 2) {
216 uint64_t p1 = data[p], p2 = data[p + 1];
218 data[p] = p1 & mask;
219 data[p + 1] = p2 & mask;
220 }
221 }
223
224 for (int n = 0; n < nHashFuncs; n++) {
226 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 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 data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
231 data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
232 }
233}
234
235bool CRollingBloomFilter::contains(std::span<const unsigned char> vKey) const
236{
237 for (int n = 0; n < nHashFuncs; n++) {
239 int bit = h & 0x3F;
240 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 if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
243 return false;
244 }
245 }
246 return true;
247}
248
250{
251 nTweak = FastRandomContext().rand<unsigned int>();
253 nGeneration = 1;
254 std::fill(data.begin(), data.end(), 0);
255}
static unsigned int BloomFilterSize(const unsigned int elements, const double false_positive_rate)
Definition bloom.cpp:26
static constexpr double LN2SQUARED
Definition bloom.cpp:23
static constexpr double LN2
Definition bloom.cpp:24
static uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, std::span< const unsigned char > vDataToHash)
Definition bloom.cpp:199
constexpr unsigned int MAX_BLOOM_FILTER_SIZE
20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
Definition bloom.h:18
constexpr unsigned int MAX_HASH_FUNCS
Definition bloom.h:19
@ BLOOM_UPDATE_P2PUBKEY_ONLY
Definition bloom.h:30
@ BLOOM_UPDATE_ALL
Definition bloom.h:28
@ BLOOM_UPDATE_MASK
Definition bloom.h:31
#define Assert(val)
Identity function.
Definition check.h:119
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
Definition bloom.cpp:98
unsigned char nFlags
Definition bloom.h:51
std::vector< unsigned char > vData
Definition bloom.h:48
unsigned int nHashFuncs
Definition bloom.h:49
void insert(std::span< const unsigned char > vKey)
Definition bloom.cpp:58
unsigned int Hash(unsigned int nHashNum, std::span< const unsigned char > vDataToHash) const
Definition bloom.cpp:52
CBloomFilter()
Definition bloom.h:68
bool contains(std::span< const unsigned char > vKey) const
Definition bloom.cpp:77
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes)
Definition bloom.cpp:103
unsigned int nTweak
Definition bloom.h:50
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:30
unsigned int nTweak
Definition bloom.h:126
CRollingBloomFilter(unsigned int nElements, double nFPRate)
Definition bloom.cpp:171
bool contains(std::span< const unsigned char > vKey) const
Definition bloom.cpp:235
int nEntriesPerGeneration
Definition bloom.h:122
int nEntriesThisGeneration
Definition bloom.h:123
std::vector< uint64_t > data
Definition bloom.h:125
void insert(std::span< const unsigned char > vKey)
Definition bloom.cpp:204
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition script.h:497
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const Txid & GetHash() const LIFETIMEBOUND
const std::vector< CTxIn > vin
An input of a transaction.
Definition transaction.h:63
An output of a transaction.
CScript scriptPubKey
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
Fast randomness source.
Definition random.h:386
I rand() noexcept
Generate a random integer in its entire (non-negative) range.
Definition random.h:287
iterator begin()
Definition prevector.h:255
iterator end()
Definition prevector.h:257
const uint256 & ToUint256() const LIFETIMEBOUND
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
static uint32_t FastRange32(uint32_t x, uint32_t n)
Fast range reduction with 32-bit input and 32-bit range.
Definition fastrange.h:19
unsigned int MurmurHash3(unsigned int nHashSeed, std::span< const unsigned char > vDataToHash)
Definition hash.cpp:13
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
Definition overflow.h:70
opcodetype
Script opcodes.
Definition script.h:75
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition solver.cpp:141
TxoutType
Definition solver.h:22
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Definition span.h:111
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82