Bitcoin Core 22.99.0
P2P Digital Currency
bloom.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2020 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/standard.h>
12#include <span.h>
13#include <streams.h>
14
15#include <algorithm>
16#include <cmath>
17#include <cstdlib>
18#include <limits>
19#include <vector>
20
21static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
22static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
23
24CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
30 vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
36 nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
37 nTweak(nTweakIn),
38 nFlags(nFlagsIn)
39{
40}
41
42inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, Span<const unsigned char> vDataToHash) const
43{
44 // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
45 return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
46}
47
49{
50 if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
51 return;
52 for (unsigned int i = 0; i < nHashFuncs; i++)
53 {
54 unsigned int nIndex = Hash(i, vKey);
55 // Sets bit nIndex of vData
56 vData[nIndex >> 3] |= (1 << (7 & nIndex));
57 }
58}
59
60void CBloomFilter::insert(const COutPoint& outpoint)
61{
63 stream << outpoint;
64 insert(stream);
65}
66
68{
69 if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
70 return true;
71 for (unsigned int i = 0; i < nHashFuncs; i++)
72 {
73 unsigned int nIndex = Hash(i, vKey);
74 // Checks bit nIndex of vData
75 if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
76 return false;
77 }
78 return true;
79}
80
81bool CBloomFilter::contains(const COutPoint& outpoint) const
82{
84 stream << outpoint;
85 return contains(stream);
86}
87
89{
91}
92
94{
95 bool fFound = false;
96 // Match if the filter contains the hash of tx
97 // for finding tx when they appear in a block
98 if (vData.empty()) // zero-size = "match-all" filter
99 return true;
100 const uint256& hash = tx.GetHash();
101 if (contains(hash))
102 fFound = true;
103
104 for (unsigned int i = 0; i < tx.vout.size(); i++)
105 {
106 const CTxOut& txout = tx.vout[i];
107 // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
108 // If this matches, also add the specific output that was matched.
109 // This means clients don't have to update the filter themselves when a new relevant tx
110 // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
112 std::vector<unsigned char> data;
113 while (pc < txout.scriptPubKey.end())
114 {
115 opcodetype opcode;
116 if (!txout.scriptPubKey.GetOp(pc, opcode, data))
117 break;
118 if (data.size() != 0 && contains(data))
119 {
120 fFound = true;
122 insert(COutPoint(hash, i));
124 {
125 std::vector<std::vector<unsigned char> > vSolutions;
126 TxoutType type = Solver(txout.scriptPubKey, vSolutions);
127 if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
128 insert(COutPoint(hash, i));
129 }
130 }
131 break;
132 }
133 }
134 }
135
136 if (fFound)
137 return true;
138
139 for (const CTxIn& txin : tx.vin)
140 {
141 // Match if the filter contains an outpoint tx spends
142 if (contains(txin.prevout))
143 return true;
144
145 // Match if the filter contains any arbitrary script data element in any scriptSig in tx
147 std::vector<unsigned char> data;
148 while (pc < txin.scriptSig.end())
149 {
150 opcodetype opcode;
151 if (!txin.scriptSig.GetOp(pc, opcode, data))
152 break;
153 if (data.size() != 0 && contains(data))
154 return true;
155 }
156 }
157
158 return false;
159}
160
161CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
162{
163 double logFpRate = log(fpRate);
164 /* The optimal number of hash functions is log(fpRate) / log(0.5), but
165 * restrict it to the range 1-50. */
166 nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
167 /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
168 nEntriesPerGeneration = (nElements + 1) / 2;
169 uint32_t nMaxElements = nEntriesPerGeneration * 3;
170 /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
171 * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
172 * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
173 * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
174 * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
175 * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
176 */
177 uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
178 data.clear();
179 /* For each data element we need to store 2 bits. If both bits are 0, the
180 * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
181 * treated as set in generation 1, 2, or 3 respectively.
182 * These bits are stored in separate integers: position P corresponds to bit
183 * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
184 data.resize(((nFilterBits + 63) / 64) << 1);
185 reset();
186}
187
188/* Similar to CBloomFilter::Hash */
189static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, Span<const unsigned char> vDataToHash)
190{
191 return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
192}
193
194
195// A replacement for x % n. This assumes that x and n are 32bit integers, and x is a uniformly random distributed 32bit value
196// which should be the case for a good hash.
197// See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
198static inline uint32_t FastMod(uint32_t x, size_t n) {
199 return ((uint64_t)x * (uint64_t)n) >> 32;
200}
201
203{
206 nGeneration++;
207 if (nGeneration == 4) {
208 nGeneration = 1;
209 }
210 uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
211 uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
212 /* Wipe old entries that used this generation number. */
213 for (uint32_t p = 0; p < data.size(); p += 2) {
214 uint64_t p1 = data[p], p2 = data[p + 1];
215 uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
216 data[p] = p1 & mask;
217 data[p + 1] = p2 & mask;
218 }
219 }
221
222 for (int n = 0; n < nHashFuncs; n++) {
223 uint32_t h = RollingBloomHash(n, nTweak, vKey);
224 int bit = h & 0x3F;
225 /* 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. */
226 uint32_t pos = FastMod(h, data.size());
227 /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
228 data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
229 data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
230 }
231}
232
234{
235 for (int n = 0; n < nHashFuncs; n++) {
236 uint32_t h = RollingBloomHash(n, nTweak, vKey);
237 int bit = h & 0x3F;
238 uint32_t pos = FastMod(h, data.size());
239 /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
240 if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
241 return false;
242 }
243 }
244 return true;
245}
246
248{
249 nTweak = GetRand(std::numeric_limits<unsigned int>::max());
251 nGeneration = 1;
252 std::fill(data.begin(), data.end(), 0);
253}
static constexpr double LN2SQUARED
Definition: bloom.cpp:21
static uint32_t FastMod(uint32_t x, size_t n)
Definition: bloom.cpp:198
static constexpr double LN2
Definition: bloom.cpp:22
static uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, Span< const unsigned char > vDataToHash)
Definition: bloom.cpp:189
static 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:17
static constexpr unsigned int MAX_HASH_FUNCS
Definition: bloom.h:18
@ BLOOM_UPDATE_P2PUBKEY_ONLY
Definition: bloom.h:29
@ BLOOM_UPDATE_ALL
Definition: bloom.h:27
@ BLOOM_UPDATE_MASK
Definition: bloom.h:30
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:88
void insert(Span< const unsigned char > vKey)
Definition: bloom.cpp:48
bool contains(Span< const unsigned char > vKey) const
Definition: bloom.cpp:67
unsigned char nFlags
Definition: bloom.h:50
std::vector< unsigned char > vData
Definition: bloom.h:47
unsigned int nHashFuncs
Definition: bloom.h:48
unsigned int Hash(unsigned int nHashNum, Span< const unsigned char > vDataToHash) const
Definition: bloom.cpp:42
CBloomFilter()
Definition: bloom.h:65
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes)
Definition: bloom.cpp:93
unsigned int nTweak
Definition: bloom.h:49
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:205
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:27
bool contains(Span< const unsigned char > vKey) const
Definition: bloom.cpp:233
unsigned int nTweak
Definition: bloom.h:123
CRollingBloomFilter(const unsigned int nElements, const double nFPRate)
Definition: bloom.cpp:161
void insert(Span< const unsigned char > vKey)
Definition: bloom.cpp:202
int nEntriesPerGeneration
Definition: bloom.h:119
int nEntriesThisGeneration
Definition: bloom.h:120
std::vector< uint64_t > data
Definition: bloom.h:122
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:487
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const uint256 & GetHash() const
Definition: transaction.h:302
const std::vector< CTxOut > vout
Definition: transaction.h:271
const std::vector< CTxIn > vin
Definition: transaction.h:270
An input of a transaction.
Definition: transaction.h:66
CScript scriptSig
Definition: transaction.h:69
COutPoint prevout
Definition: transaction.h:68
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:93
iterator begin()
Definition: prevector.h:290
iterator end()
Definition: prevector.h:292
256-bit opaque blob.
Definition: uint256.h:124
unsigned int MurmurHash3(unsigned int nHashSeed, Span< const unsigned char > vDataToHash)
Definition: hash.cpp:17
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:591
opcodetype
Script opcodes.
Definition: script.h:67
@ SER_NETWORK
Definition: serialize.h:138
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:144
TxoutType
Definition: standard.h:59
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12