Bitcoin ABC 0.30.5
P2P Digital Currency
bloom.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2016 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 <streams.h>
13#include <util/fastrange.h>
14
15#include <cmath>
16#include <cstdlib>
17
18#include <algorithm>
19
20#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
21#define LN2 0.6931471805599453094172321214581765680755001343602552
22
36CBloomFilter::CBloomFilter(const uint32_t nElements, const double nFPRate,
37 const uint32_t nTweakIn, uint8_t nFlagsIn)
38 : vData(std::min<uint32_t>(-1 / LN2SQUARED * nElements * log(nFPRate),
40 8),
41 nHashFuncs(std::min<uint32_t>(vData.size() * 8 / nElements * LN2,
43 nTweak(nTweakIn), nFlags(nFlagsIn) {}
44
45inline uint32_t CBloomFilter::Hash(uint32_t nHashNum,
46 Span<const uint8_t> vDataToHash) const {
47 // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between
48 // nHashNum values.
49 return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) %
50 (vData.size() * 8);
51}
52
54 if (vData.empty()) {
55 // Avoid divide-by-zero (CVE-2013-5700)
56 return;
57 }
58
59 for (uint32_t i = 0; i < nHashFuncs; i++) {
60 uint32_t nIndex = Hash(i, vKey);
61 // Sets bit nIndex of vData
62 vData[nIndex >> 3] |= (1 << (7 & nIndex));
63 }
64}
65
66void CBloomFilter::insert(const COutPoint &outpoint) {
68 stream << outpoint;
69 insert(MakeUCharSpan(stream));
70}
71
73 if (vData.empty()) {
74 // Avoid divide-by-zero (CVE-2013-5700)
75 return true;
76 }
77 for (uint32_t i = 0; i < nHashFuncs; i++) {
78 uint32_t nIndex = Hash(i, vKey);
79 // Checks bit nIndex of vData
80 if (!(vData[nIndex >> 3] & (1 << (7 & nIndex)))) {
81 return false;
82 }
83 }
84 return true;
85}
86
87bool CBloomFilter::contains(const COutPoint &outpoint) const {
89 stream << outpoint;
90 return contains(MakeUCharSpan(stream));
91}
92
94 return vData.size() <= MAX_BLOOM_FILTER_SIZE &&
96}
97
99 bool fFound = false;
100 // Match if the filter contains the hash of tx for finding tx when they
101 // appear in a block
102 if (vData.empty()) {
103 // zero-size = "match-all" filter
104 return true;
105 }
106
107 const TxId &txid = tx.GetId();
108 if (contains(txid)) {
109 fFound = true;
110 }
111
112 for (size_t i = 0; i < tx.vout.size(); i++) {
113 const CTxOut &txout = tx.vout[i];
114 // Match if the filter contains any arbitrary script data element in any
115 // scriptPubKey in tx. If this matches, also add the specific output
116 // that was matched. This means clients don't have to update the filter
117 // themselves when a new relevant tx is discovered in order to find
118 // spending transactions, which avoids round-tripping and race
119 // conditions.
121 std::vector<uint8_t> data;
122 while (pc < txout.scriptPubKey.end()) {
123 opcodetype opcode;
124 if (!txout.scriptPubKey.GetOp(pc, opcode, data)) {
125 break;
126 }
127 if (data.size() != 0 && contains(data)) {
128 fFound = true;
130 insert(COutPoint(txid, i));
131 } else if ((nFlags & BLOOM_UPDATE_MASK) ==
133 std::vector<std::vector<uint8_t>> vSolutions;
134 TxoutType type = Solver(txout.scriptPubKey, vSolutions);
135 if (type == TxoutType::PUBKEY ||
136 type == TxoutType::MULTISIG) {
137 insert(COutPoint(txid, i));
138 }
139 }
140 break;
141 }
142 }
143 }
144
145 return fFound;
146}
147
149 for (const CTxIn &txin : tx.vin) {
150 // Match if the filter contains an outpoint tx spends
151 if (contains(txin.prevout)) {
152 return true;
153 }
154
155 // Match if the filter contains any arbitrary script data element in any
156 // scriptSig in tx
158 std::vector<uint8_t> data;
159 while (pc < txin.scriptSig.end()) {
160 opcodetype opcode;
161 if (!txin.scriptSig.GetOp(pc, opcode, data)) {
162 break;
163 }
164 if (data.size() != 0 && contains(data)) {
165 return true;
166 }
167 }
168 }
169
170 return false;
171}
172
174 const double fpRate) {
175 double logFpRate = log(fpRate);
176 /* The optimal number of hash functions is log(fpRate) / log(0.5), but
177 * restrict it to the range 1-50. */
178 nHashFuncs = std::max(1, std::min<int>(round(logFpRate / log(0.5)), 50));
179 /* In this rolling bloom filter, we'll store between 2 and 3 generations of
180 * nElements / 2 entries. */
181 nEntriesPerGeneration = (nElements + 1) / 2;
182 uint32_t nMaxElements = nEntriesPerGeneration * 3;
183 /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements /
184 * nFilterBits), nHashFuncs)
185 * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs *
186 * nMaxElements / nFilterBits)
187 * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs *
188 * nMaxElements / nFilterBits)
189 * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs *
190 * nMaxElements / nFilterBits
191 * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 -
192 * pow(fpRate, 1.0 / nHashFuncs))
193 * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 -
194 * exp(logFpRate / nHashFuncs))
195 */
196 uint32_t nFilterBits =
197 uint32_t(ceil(-1.0 * nHashFuncs * nMaxElements /
198 log(1.0 - exp(logFpRate / nHashFuncs))));
199 data.clear();
200 /* For each data element we need to store 2 bits. If both bits are 0, the
201 * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
202 * treated as set in generation 1, 2, or 3 respectively. These bits are
203 * stored in separate integers: position P corresponds to bit (P & 63) of
204 * the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
205 data.resize(((nFilterBits + 63) / 64) << 1);
206 reset();
207}
208
209/* Similar to CBloomFilter::Hash */
210static inline uint32_t RollingBloomHash(uint32_t nHashNum, uint32_t nTweak,
211 Span<const uint8_t> vDataToHash) {
212 return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
213}
214
218 nGeneration++;
219 if (nGeneration == 4) {
220 nGeneration = 1;
221 }
222 uint64_t nGenerationMask1 = 0 - uint64_t(nGeneration & 1);
223 uint64_t nGenerationMask2 = 0 - uint64_t(nGeneration >> 1);
224 /* Wipe old entries that used this generation number. */
225 for (uint32_t p = 0; p < data.size(); p += 2) {
226 uint64_t p1 = data[p], p2 = data[p + 1];
227 uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
228 data[p] = p1 & mask;
229 data[p + 1] = p2 & mask;
230 }
231 }
233
234 for (int n = 0; n < nHashFuncs; n++) {
235 uint32_t h = RollingBloomHash(n, nTweak, vKey);
236 int bit = h & 0x3F;
237 /* FastMod works with the upper bits of h, so it is safe to ignore that
238 * the lower bits of h are already used for bit. */
239 uint32_t pos = FastRange32(h, data.size());
240 /* The lowest bit of pos is ignored, and set to zero for the first bit,
241 * and to one for the second. */
242 data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t(1) << bit)) |
243 uint64_t(nGeneration & 1) << bit;
244 data[pos | 1U] = (data[pos | 1] & ~(uint64_t(1) << bit)) |
245 uint64_t(nGeneration >> 1) << bit;
246 }
247}
248
250 for (int n = 0; n < nHashFuncs; n++) {
251 uint32_t h = RollingBloomHash(n, nTweak, vKey);
252 int bit = h & 0x3F;
253 uint32_t pos = FastRange32(h, data.size());
254 /* If the relevant bit is not set in either data[pos & ~1] or data[pos |
255 * 1], the filter does not contain vKey */
256 if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
257 return false;
258 }
259 }
260 return true;
261}
262
264 nTweak = GetRand<unsigned int>();
266 nGeneration = 1;
267 std::fill(data.begin(), data.end(), 0);
268}
#define LN2
Definition: bloom.cpp:21
static uint32_t RollingBloomHash(uint32_t nHashNum, uint32_t nTweak, Span< const uint8_t > vDataToHash)
Definition: bloom.cpp:210
#define LN2SQUARED
Definition: bloom.cpp:20
static const uint32_t MAX_BLOOM_FILTER_SIZE
20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
Definition: bloom.h:17
static const uint32_t MAX_HASH_FUNCS
Definition: bloom.h:18
@ BLOOM_UPDATE_P2PUBKEY_ONLY
Definition: bloom.h:29
@ BLOOM_UPDATE_ALL
Definition: bloom.h:26
@ 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:93
bool contains(Span< const uint8_t > vKey) const
Definition: bloom.cpp:72
uint8_t nFlags
Definition: bloom.h:49
void insert(Span< const uint8_t > vKey)
Definition: bloom.cpp:53
uint32_t nHashFuncs
Definition: bloom.h:47
std::vector< uint8_t > vData
Definition: bloom.h:46
bool MatchInputs(const CTransaction &tx)
Scan inputs to see if the spent outpoints are a match, or the input scripts contain matching elements...
Definition: bloom.cpp:148
bool MatchAndInsertOutputs(const CTransaction &tx)
Scans output scripts for matches and adds those outpoints to the filter for spend detection.
Definition: bloom.cpp:98
CBloomFilter()
Definition: bloom.h:67
uint32_t Hash(uint32_t nHashNum, Span< const uint8_t > vDataToHash) const
Definition: bloom.cpp:45
uint32_t nTweak
Definition: bloom.h:48
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:177
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
CRollingBloomFilter(const uint32_t nElements, const double nFPRate)
Definition: bloom.cpp:173
int nEntriesPerGeneration
Definition: bloom.h:125
int nEntriesThisGeneration
Definition: bloom.h:126
std::vector< uint64_t > data
Definition: bloom.h:128
uint32_t nTweak
Definition: bloom.h:129
void insert(Span< const uint8_t > vKey)
Definition: bloom.cpp:215
bool contains(Span< const uint8_t > vKey) const
Definition: bloom.cpp:249
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< uint8_t > &vchRet) const
Definition: script.h:502
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
const std::vector< CTxOut > vout
Definition: transaction.h:207
const std::vector< CTxIn > vin
Definition: transaction.h:206
const TxId GetId() const
Definition: transaction.h:240
An input of a transaction.
Definition: transaction.h:59
CScript scriptSig
Definition: transaction.h:62
COutPoint prevout
Definition: transaction.h:61
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
iterator begin()
Definition: prevector.h:398
iterator end()
Definition: prevector.h:400
static uint32_t FastRange32(uint32_t x, uint32_t n)
This file offers implementations of the fast range reduction technique described in https://lemire....
Definition: fastrange.h:22
uint32_t MurmurHash3(uint32_t nHashSeed, Span< const uint8_t > vDataToHash)
Definition: hash.cpp:14
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
opcodetype
Script opcodes.
Definition: script.h:47
@ SER_NETWORK
Definition: serialize.h:152
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
Definition: span.h:337
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:108
TxoutType
Definition: standard.h:38
A TxId is the identifier of a transaction.
Definition: txid.h:14
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11