Bitcoin Core  0.19.99
P2P Digital Currency
bloom.cpp
Go to the documentation of this file.
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 
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 CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
28  vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
34  isFull(false),
35  isEmpty(true),
36  nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
37  nTweak(nTweakIn),
38  nFlags(nFlagsIn)
39 {
40 }
41 
42 inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<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 
48 void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
49 {
50  if (isFull)
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  isEmpty = false;
59 }
60 
61 void CBloomFilter::insert(const COutPoint& outpoint)
62 {
64  stream << outpoint;
65  std::vector<unsigned char> data(stream.begin(), stream.end());
66  insert(data);
67 }
68 
69 void CBloomFilter::insert(const uint256& hash)
70 {
71  std::vector<unsigned char> data(hash.begin(), hash.end());
72  insert(data);
73 }
74 
75 bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
76 {
77  if (isFull)
78  return true;
79  if (isEmpty)
80  return false;
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 
91 bool CBloomFilter::contains(const COutPoint& outpoint) const
92 {
94  stream << outpoint;
95  std::vector<unsigned char> data(stream.begin(), stream.end());
96  return contains(data);
97 }
98 
99 bool CBloomFilter::contains(const uint256& hash) const
100 {
101  std::vector<unsigned char> data(hash.begin(), hash.end());
102  return contains(data);
103 }
104 
106 {
107  vData.assign(vData.size(),0);
108  isFull = false;
109  isEmpty = true;
110 }
111 
112 void CBloomFilter::reset(const unsigned int nNewTweak)
113 {
114  clear();
115  nTweak = nNewTweak;
116 }
117 
119 {
120  return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
121 }
122 
124 {
125  bool fFound = false;
126  // Match if the filter contains the hash of tx
127  // for finding tx when they appear in a block
128  if (isFull)
129  return true;
130  if (isEmpty)
131  return false;
132  const uint256& hash = tx.GetHash();
133  if (contains(hash))
134  fFound = true;
135 
136  for (unsigned int i = 0; i < tx.vout.size(); i++)
137  {
138  const CTxOut& txout = tx.vout[i];
139  // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
140  // If this matches, also add the specific output that was matched.
141  // This means clients don't have to update the filter themselves when a new relevant tx
142  // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
144  std::vector<unsigned char> data;
145  while (pc < txout.scriptPubKey.end())
146  {
147  opcodetype opcode;
148  if (!txout.scriptPubKey.GetOp(pc, opcode, data))
149  break;
150  if (data.size() != 0 && contains(data))
151  {
152  fFound = true;
154  insert(COutPoint(hash, i));
155  else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
156  {
157  std::vector<std::vector<unsigned char> > vSolutions;
158  txnouttype type = Solver(txout.scriptPubKey, vSolutions);
159  if (type == TX_PUBKEY || type == TX_MULTISIG) {
160  insert(COutPoint(hash, i));
161  }
162  }
163  break;
164  }
165  }
166  }
167 
168  if (fFound)
169  return true;
170 
171  for (const CTxIn& txin : tx.vin)
172  {
173  // Match if the filter contains an outpoint tx spends
174  if (contains(txin.prevout))
175  return true;
176 
177  // Match if the filter contains any arbitrary script data element in any scriptSig in tx
179  std::vector<unsigned char> data;
180  while (pc < txin.scriptSig.end())
181  {
182  opcodetype opcode;
183  if (!txin.scriptSig.GetOp(pc, opcode, data))
184  break;
185  if (data.size() != 0 && contains(data))
186  return true;
187  }
188  }
189 
190  return false;
191 }
192 
194 {
195  bool full = true;
196  bool empty = true;
197  for (unsigned int i = 0; i < vData.size(); i++)
198  {
199  full &= vData[i] == 0xff;
200  empty &= vData[i] == 0;
201  }
202  isFull = full;
203  isEmpty = empty;
204 }
205 
206 CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
207 {
208  double logFpRate = log(fpRate);
209  /* The optimal number of hash functions is log(fpRate) / log(0.5), but
210  * restrict it to the range 1-50. */
211  nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
212  /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
213  nEntriesPerGeneration = (nElements + 1) / 2;
214  uint32_t nMaxElements = nEntriesPerGeneration * 3;
215  /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
216  * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
217  * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
218  * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
219  * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
220  * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
221  */
222  uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
223  data.clear();
224  /* For each data element we need to store 2 bits. If both bits are 0, the
225  * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
226  * treated as set in generation 1, 2, or 3 respectively.
227  * These bits are stored in separate integers: position P corresponds to bit
228  * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
229  data.resize(((nFilterBits + 63) / 64) << 1);
230  reset();
231 }
232 
233 /* Similar to CBloomFilter::Hash */
234 static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
235  return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
236 }
237 
238 
239 // A replacement for x % n. This assumes that x and n are 32bit integers, and x is a uniformly random distributed 32bit value
240 // which should be the case for a good hash.
241 // See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
242 static inline uint32_t FastMod(uint32_t x, size_t n) {
243  return ((uint64_t)x * (uint64_t)n) >> 32;
244 }
245 
246 void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
247 {
248  if (nEntriesThisGeneration == nEntriesPerGeneration) {
249  nEntriesThisGeneration = 0;
250  nGeneration++;
251  if (nGeneration == 4) {
252  nGeneration = 1;
253  }
254  uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
255  uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
256  /* Wipe old entries that used this generation number. */
257  for (uint32_t p = 0; p < data.size(); p += 2) {
258  uint64_t p1 = data[p], p2 = data[p + 1];
259  uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
260  data[p] = p1 & mask;
261  data[p + 1] = p2 & mask;
262  }
263  }
264  nEntriesThisGeneration++;
265 
266  for (int n = 0; n < nHashFuncs; n++) {
267  uint32_t h = RollingBloomHash(n, nTweak, vKey);
268  int bit = h & 0x3F;
269  /* 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. */
270  uint32_t pos = FastMod(h, data.size());
271  /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
272  data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
273  data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
274  }
275 }
276 
278 {
279  std::vector<unsigned char> vData(hash.begin(), hash.end());
280  insert(vData);
281 }
282 
283 bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
284 {
285  for (int n = 0; n < nHashFuncs; n++) {
286  uint32_t h = RollingBloomHash(n, nTweak, vKey);
287  int bit = h & 0x3F;
288  uint32_t pos = FastMod(h, data.size());
289  /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
290  if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
291  return false;
292  }
293  }
294  return true;
295 }
296 
297 bool CRollingBloomFilter::contains(const uint256& hash) const
298 {
299  std::vector<unsigned char> vData(hash.begin(), hash.end());
300  return contains(vData);
301 }
302 
304 {
305  nTweak = GetRand(std::numeric_limits<unsigned int>::max());
306  nEntriesThisGeneration = 0;
307  nGeneration = 1;
308  std::fill(data.begin(), data.end(), 0);
309 }
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:585
CRollingBloomFilter(const unsigned int nElements, const double nFPRate)
Definition: bloom.cpp:206
CScript scriptPubKey
Definition: transaction.h:137
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:499
unsigned int nTweak
Definition: bloom.h:51
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:246
unsigned char nFlags
Definition: bloom.h:52
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes) ...
Definition: bloom.cpp:123
bool isFull
Definition: bloom.h:48
static const 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
std::vector< unsigned char > vData
Definition: bloom.h:47
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:91
unsigned int Hash(unsigned int nHashNum, const std::vector< unsigned char > &vDataToHash) const
Definition: bloom.cpp:42
unsigned int nHashFuncs
Definition: bloom.h:50
void reset(const unsigned int nNewTweak)
Definition: bloom.cpp:112
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:201
#define LN2
Definition: bloom.cpp:20
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:48
unsigned char * begin()
Definition: uint256.h:54
unsigned char * end()
Definition: uint256.h:59
const std::vector< CTxIn > vin
Definition: transaction.h:287
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:283
iterator end()
Definition: prevector.h:292
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector< unsigned char > &vDataToHash)
Definition: hash.cpp:15
opcodetype
Script opcodes.
Definition: script.h:54
An input of a transaction.
Definition: transaction.h:63
const uint256 & GetHash() const
Definition: transaction.h:322
void clear()
Definition: bloom.cpp:105
static uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector< unsigned char > &vDataToHash)
Definition: bloom.cpp:234
CBloomFilter()
Definition: bloom.h:67
const std::vector< CTxOut > vout
Definition: transaction.h:288
An output of a transaction.
Definition: transaction.h:133
static const unsigned int MAX_HASH_FUNCS
Definition: bloom.h:18
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
#define LN2SQUARED
Definition: bloom.cpp:19
CScript scriptSig
Definition: transaction.h:67
txnouttype
Definition: standard.h:55
256-bit opaque blob.
Definition: uint256.h:120
const_iterator end() const
Definition: streams.h:290
const_iterator begin() const
Definition: streams.h:288
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
iterator begin()
Definition: prevector.h:290
void UpdateEmptyFull()
Checks for empty and full filters to avoid wasting cpu.
Definition: bloom.cpp:193
static uint32_t FastMod(uint32_t x, size_t n)
Definition: bloom.cpp:242
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
COutPoint prevout
Definition: transaction.h:66
bool isEmpty
Definition: bloom.h:49
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:118
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:75