Line data Source code
1 : // Copyright (c) 2012-2019 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 <bloom.h>
6 :
7 : #include <primitives/transaction.h>
8 : #include <hash.h>
9 : #include <script/script.h>
10 : #include <script/standard.h>
11 : #include <random.h>
12 : #include <streams.h>
13 :
14 : #include <math.h>
15 : #include <stdlib.h>
16 :
17 : #include <algorithm>
18 :
19 : #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
20 : #define LN2 0.6931471805599453094172321214581765680755001343602552
21 :
22 44 : CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
23 : /**
24 : * The ideal size for a bloom filter with a given number of elements and false positive rate is:
25 : * - nElements * log(fp rate) / ln(2)^2
26 : * We ignore filter parameters which will create a bloom filter larger than the protocol limits
27 : */
28 22 : vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
29 : /**
30 : * The ideal number of hash functions is filter size * ln(2) / number of elements
31 : * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
32 : * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
33 : */
34 22 : nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
35 22 : nTweak(nTweakIn),
36 22 : nFlags(nFlagsIn)
37 22 : {
38 44 : }
39 :
40 1981 : inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
41 : {
42 : // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
43 1981 : return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
44 : }
45 :
46 47 : void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
47 : {
48 47 : if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
49 : return;
50 825 : for (unsigned int i = 0; i < nHashFuncs; i++)
51 : {
52 780 : unsigned int nIndex = Hash(i, vKey);
53 : // Sets bit nIndex of vData
54 780 : vData[nIndex >> 3] |= (1 << (7 & nIndex));
55 : }
56 47 : }
57 :
58 14 : void CBloomFilter::insert(const COutPoint& outpoint)
59 : {
60 14 : CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
61 14 : stream << outpoint;
62 14 : std::vector<unsigned char> data(stream.begin(), stream.end());
63 14 : insert(data);
64 14 : }
65 :
66 9 : void CBloomFilter::insert(const uint256& hash)
67 : {
68 9 : std::vector<unsigned char> data(hash.begin(), hash.end());
69 9 : insert(data);
70 9 : }
71 :
72 477 : bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
73 : {
74 477 : if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
75 0 : return true;
76 1244 : for (unsigned int i = 0; i < nHashFuncs; i++)
77 : {
78 1201 : unsigned int nIndex = Hash(i, vKey);
79 : // Checks bit nIndex of vData
80 1201 : if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
81 434 : return false;
82 767 : }
83 43 : return true;
84 477 : }
85 :
86 95 : bool CBloomFilter::contains(const COutPoint& outpoint) const
87 : {
88 95 : CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
89 95 : stream << outpoint;
90 95 : std::vector<unsigned char> data(stream.begin(), stream.end());
91 95 : return contains(data);
92 95 : }
93 :
94 87 : bool CBloomFilter::contains(const uint256& hash) const
95 : {
96 87 : std::vector<unsigned char> data(hash.begin(), hash.end());
97 87 : return contains(data);
98 87 : }
99 :
100 9 : bool CBloomFilter::IsWithinSizeConstraints() const
101 : {
102 9 : return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
103 : }
104 :
105 87 : bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
106 : {
107 : bool fFound = false;
108 : // Match if the filter contains the hash of tx
109 : // for finding tx when they appear in a block
110 87 : if (vData.empty()) // zero-size = "match-all" filter
111 0 : return true;
112 87 : const uint256& hash = tx.GetHash();
113 87 : if (contains(hash))
114 13 : fFound = true;
115 :
116 232 : for (unsigned int i = 0; i < tx.vout.size(); i++)
117 : {
118 145 : const CTxOut& txout = tx.vout[i];
119 : // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
120 : // If this matches, also add the specific output that was matched.
121 : // This means clients don't have to update the filter themselves when a new relevant tx
122 : // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
123 145 : CScript::const_iterator pc = txout.scriptPubKey.begin();
124 145 : std::vector<unsigned char> data;
125 666 : while (pc < txout.scriptPubKey.end())
126 : {
127 537 : opcodetype opcode;
128 537 : if (!txout.scriptPubKey.GetOp(pc, opcode, data))
129 0 : break;
130 537 : if (data.size() != 0 && contains(data))
131 : {
132 : fFound = true;
133 16 : if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
134 10 : insert(COutPoint(hash, i));
135 6 : else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
136 : {
137 2 : std::vector<std::vector<unsigned char> > vSolutions;
138 2 : TxoutType type = Solver(txout.scriptPubKey, vSolutions);
139 2 : if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
140 1 : insert(COutPoint(hash, i));
141 1 : }
142 2 : }
143 16 : break;
144 : }
145 537 : }
146 145 : }
147 :
148 87 : if (fFound)
149 29 : return true;
150 :
151 149 : for (const CTxIn& txin : tx.vin)
152 : {
153 : // Match if the filter contains an outpoint tx spends
154 91 : if (contains(txin.prevout))
155 4 : return true;
156 :
157 : // Match if the filter contains any arbitrary script data element in any scriptSig in tx
158 87 : CScript::const_iterator pc = txin.scriptSig.begin();
159 87 : std::vector<unsigned char> data;
160 225 : while (pc < txin.scriptSig.end())
161 : {
162 140 : opcodetype opcode;
163 140 : if (!txin.scriptSig.GetOp(pc, opcode, data))
164 0 : break;
165 140 : if (data.size() != 0 && contains(data))
166 89 : return true;
167 140 : }
168 87 : }
169 :
170 52 : return false;
171 87 : }
172 :
173 8032 : CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
174 4016 : {
175 4016 : 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 4016 : 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 nElements / 2 entries. */
180 4016 : nEntriesPerGeneration = (nElements + 1) / 2;
181 4016 : uint32_t nMaxElements = nEntriesPerGeneration * 3;
182 : /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
183 : * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
184 : * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
185 : * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
186 : * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
187 : * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
188 : */
189 4016 : uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
190 4016 : data.clear();
191 : /* For each data element we need to store 2 bits. If both bits are 0, the
192 : * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
193 : * treated as set in generation 1, 2, or 3 respectively.
194 : * These bits are stored in separate integers: position P corresponds to bit
195 : * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
196 4016 : data.resize(((nFilterBits + 63) / 64) << 1);
197 4016 : reset();
198 8032 : }
199 :
200 : /* Similar to CBloomFilter::Hash */
201 4412281 : static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
202 4412281 : return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
203 : }
204 :
205 :
206 : // A replacement for x % n. This assumes that x and n are 32bit integers, and x is a uniformly random distributed 32bit value
207 : // which should be the case for a good hash.
208 : // See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
209 4412257 : static inline uint32_t FastMod(uint32_t x, size_t n) {
210 4412257 : return ((uint64_t)x * (uint64_t)n) >> 32;
211 : }
212 :
213 196342 : void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
214 : {
215 196342 : if (nEntriesThisGeneration == nEntriesPerGeneration) {
216 41 : nEntriesThisGeneration = 0;
217 41 : nGeneration++;
218 41 : if (nGeneration == 4) {
219 12 : nGeneration = 1;
220 12 : }
221 41 : uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
222 41 : uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
223 : /* Wipe old entries that used this generation number. */
224 15314 : for (uint32_t p = 0; p < data.size(); p += 2) {
225 15273 : uint64_t p1 = data[p], p2 = data[p + 1];
226 15273 : uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
227 15273 : data[p] = p1 & mask;
228 15273 : data[p + 1] = p2 & mask;
229 : }
230 41 : }
231 196342 : nEntriesThisGeneration++;
232 :
233 3945788 : for (int n = 0; n < nHashFuncs; n++) {
234 3749446 : uint32_t h = RollingBloomHash(n, nTweak, vKey);
235 3749446 : int bit = h & 0x3F;
236 : /* 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. */
237 3749446 : uint32_t pos = FastMod(h, data.size());
238 : /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
239 3749446 : data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
240 3749446 : data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
241 : }
242 196342 : }
243 :
244 178978 : void CRollingBloomFilter::insert(const uint256& hash)
245 : {
246 178978 : std::vector<unsigned char> vData(hash.begin(), hash.end());
247 178978 : insert(vData);
248 178978 : }
249 :
250 182656 : bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
251 : {
252 688996 : for (int n = 0; n < nHashFuncs; n++) {
253 662836 : uint32_t h = RollingBloomHash(n, nTweak, vKey);
254 662836 : int bit = h & 0x3F;
255 662836 : uint32_t pos = FastMod(h, data.size());
256 : /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
257 662836 : if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
258 156496 : return false;
259 : }
260 506340 : }
261 26160 : return true;
262 182656 : }
263 :
264 130113 : bool CRollingBloomFilter::contains(const uint256& hash) const
265 : {
266 130113 : std::vector<unsigned char> vData(hash.begin(), hash.end());
267 130113 : return contains(vData);
268 130113 : }
269 :
270 8239 : void CRollingBloomFilter::reset()
271 : {
272 8239 : nTweak = GetRand(std::numeric_limits<unsigned int>::max());
273 8239 : nEntriesThisGeneration = 0;
274 8239 : nGeneration = 1;
275 8239 : std::fill(data.begin(), data.end(), 0);
276 8239 : }
|