PIVX Core  5.6.99
P2P Digital Currency
bloom.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2014 The Bitcoin developers
2 // Copyright (c) 2017-2020 The PIVX Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include "bloom.h"
7 
8 #include "hash.h"
10 #include "script/script.h"
11 #include "script/standard.h"
12 #include "random.h"
13 #include "streams.h"
14 
15 #include <math.h>
16 #include <stdlib.h>
17 
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(false),
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  unsigned int nIndex = Hash(i, vKey);
54  // Sets bit nIndex of vData
55  vData[nIndex >> 3] |= (1 << (7 & nIndex));
56  }
57  isEmpty = false;
58 }
59 
60 void CBloomFilter::insert(const COutPoint& outpoint)
61 {
62  CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
63  stream << outpoint;
64  std::vector<unsigned char> data(stream.begin(), stream.end());
65  insert(data);
66 }
67 
68 void CBloomFilter::insert(const uint256& hash)
69 {
70  std::vector<unsigned char> data(hash.begin(), hash.end());
71  insert(data);
72 }
73 
74 bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
75 {
76  if (isFull) {
77  return true;
78  }
79  if (isEmpty) {
80  return false;
81  }
82  for (unsigned int i = 0; i < nHashFuncs; i++) {
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 {
93  CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
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 
128  for (unsigned char b : vData)
129  if (b != 0xff)
130  return false;
131  return true;
132 }
133 
138 bool CBloomFilter::Merge(const CBloomFilter& filter) {
139  if (!this->MatchesAll() && !filter.MatchesAll()) {
140  if(! (filter.vData.size() == this->vData.size() &&
141  filter.nHashFuncs == this->nHashFuncs &&
142  filter.nTweak == this->nTweak)){
143  return false;
144  }
145  for (unsigned int i = 0; i < vData.size(); i++)
146  this->vData[i] |= filter.vData[i];
147  } else {
148  // TODO: Check this.
149  this->vData.clear();
150  this->vData[0] = 0xff;
151  }
152  return true;
153 }
154 
156 {
157  bool fFound = false;
158  // Match if the filter contains the hash of tx
159  // for finding tx when they appear in a block
160  if (isFull)
161  return true;
162  if (isEmpty)
163  return false;
164  const uint256& hash = tx.GetHash();
165  if (contains(hash))
166  fFound = true;
167 
168  for (unsigned int i = 0; i < tx.vout.size(); i++) {
169  const CTxOut& txout = tx.vout[i];
170  // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
171  // If this matches, also add the specific output that was matched.
172  // This means clients don't have to update the filter themselves when a new relevant tx
173  // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
175  std::vector<unsigned char> data;
176  while (pc < txout.scriptPubKey.end()) {
177  opcodetype opcode;
178  if (!txout.scriptPubKey.GetOp(pc, opcode, data)){
179  break;
180  }
181 
182  if (data.size() != 0 && contains(data)) {
183  fFound = true;
185  insert(COutPoint(hash, i));
187  txnouttype type;
188  std::vector<std::vector<unsigned char> > vSolutions;
189  if (Solver(txout.scriptPubKey, type, vSolutions) &&
190  (type == TX_PUBKEY || type == TX_MULTISIG))
191  insert(COutPoint(hash, i));
192  }
193  break;
194  }
195  }
196  }
197 
198  if (fFound)
199  return true;
200 
201  for (const CTxIn& txin : tx.vin) {
202  // Match if the filter contains an outpoint tx spends
203  if (contains(txin.prevout))
204  return true;
205 
206  // Match if the filter contains any arbitrary script data element in any scriptSig in tx
208  std::vector<unsigned char> data;
209  while (pc < txin.scriptSig.end()) {
210  opcodetype opcode;
211  if (!txin.scriptSig.GetOp(pc, opcode, data))
212  break;
213  if (data.size() != 0 && contains(data)) {
214  return true;
215  }
216  }
217  }
218 
219  return false;
220 }
221 
223 {
224  bool full = true;
225  bool empty = true;
226  for (unsigned int i = 0; i < vData.size(); i++) {
227  full &= vData[i] == 0xff;
228  empty &= vData[i] == 0;
229  }
230  isFull = full;
231  isEmpty = empty;
232 }
233 
234 CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
235 {
236  double logFpRate = log(fpRate);
237  /* The optimal number of hash functions is log(fpRate) / log(0.5), but
238  * restrict it to the range 1-50. */
239  nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
240  /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
241  nEntriesPerGeneration = (nElements + 1) / 2;
242  uint32_t nMaxElements = nEntriesPerGeneration * 3;
243  /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
244  * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
245  * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
246  * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
247  * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
248  * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
249  */
250  uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
251  data.clear();
252  /* For each data element we need to store 2 bits. If both bits are 0, the
253  * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
254  * treated as set in generation 1, 2, or 3 respectively.
255  * These bits are stored in separate integers: position P corresponds to bit
256  * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
257  data.resize(((nFilterBits + 63) / 64) << 1);
258  reset();
259 }
260 
261 /* Similar to CBloomFilter::Hash */
262 static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
263  return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
264 }
265 
266 
267 // A replacement for x % n. This assumes that x and n are 32bit integers, and x is a uniformly random distributed 32bit value
268 // which should be the case for a good hash.
269 // See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
270 static inline uint32_t FastMod(uint32_t x, size_t n) {
271  return ((uint64_t)x * (uint64_t)n) >> 32;
272 }
273 
274 void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
275 {
278  nGeneration++;
279  if (nGeneration == 4) {
280  nGeneration = 1;
281  }
282  uint64_t nGenerationMask1 = -(uint64_t)(nGeneration & 1);
283  uint64_t nGenerationMask2 = -(uint64_t)(nGeneration >> 1);
284  /* Wipe old entries that used this generation number. */
285  for (uint32_t p = 0; p < data.size(); p += 2) {
286  uint64_t p1 = data[p], p2 = data[p + 1];
287  uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
288  data[p] = p1 & mask;
289  data[p + 1] = p2 & mask;
290  }
291  }
293 
294  for (int n = 0; n < nHashFuncs; n++) {
295  uint32_t h = RollingBloomHash(n, nTweak, vKey);
296  int bit = h & 0x3F;
297  /* 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. */
298  uint32_t pos = FastMod(h, data.size());
299  /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
300  data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
301  data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
302  }
303 }
304 
306 {
307  std::vector<unsigned char> data(hash.begin(), hash.end());
308  insert(data);
309 }
310 
311 bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
312 {
313  for (int n = 0; n < nHashFuncs; n++) {
314  uint32_t h = RollingBloomHash(n, nTweak, vKey);
315  int bit = h & 0x3F;
316  uint32_t pos = FastMod(h, data.size());
317  /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
318  if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
319  return false;
320  }
321  }
322  return true;
323 }
324 
325 bool CRollingBloomFilter::contains(const uint256& hash) const
326 {
327  std::vector<unsigned char> data(hash.begin(), hash.end());
328  return contains(data);
329 }
330 
332 {
333  nTweak = GetRand(std::numeric_limits<unsigned int>::max());
335  nGeneration = 1;
336  for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
337  *it = 0;
338  }
339 }
#define LN2
Definition: bloom.cpp:20
#define LN2SQUARED
Definition: bloom.cpp:19
@ BLOOM_UPDATE_P2PUBKEY_ONLY
Definition: bloom.h:29
@ BLOOM_UPDATE_ALL
Definition: bloom.h:27
@ BLOOM_UPDATE_MASK
Definition: bloom.h:30
false
Definition: bls_dkg.cpp:151
const_iterator end() const
Definition: streams.h:163
const_iterator begin() const
Definition: streams.h:161
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
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
unsigned int Hash(unsigned int nHashNum, const std::vector< unsigned char > &vDataToHash) const
Definition: bloom.cpp:42
unsigned char nFlags
Definition: bloom.h:52
bool isEmpty
Definition: bloom.h:49
std::vector< unsigned char > vData
Definition: bloom.h:47
bool isFull
Definition: bloom.h:48
unsigned int nHashFuncs
Definition: bloom.h:50
bool Merge(const CBloomFilter &filter)
Copies filter into this.
Definition: bloom.cpp:138
void reset(const unsigned int nNewTweak)
Definition: bloom.cpp:112
CBloomFilter()
Definition: bloom.h:67
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:48
void clear()
Definition: bloom.cpp:105
bool MatchesAll() const
Returns true if this filter will match anything.
Definition: bloom.cpp:127
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes)
Definition: bloom.cpp:155
unsigned int nTweak
Definition: bloom.h:51
void UpdateEmptyFull()
Checks for empty and full filters to avoid wasting cpu.
Definition: bloom.cpp:222
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:74
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:72
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:274
unsigned int nTweak
Definition: bloom.h:130
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:311
CRollingBloomFilter(const unsigned int nElements, const double nFPRate)
Definition: bloom.cpp:234
int nEntriesPerGeneration
Definition: bloom.h:126
int nEntriesThisGeneration
Definition: bloom.h:127
std::vector< uint64_t > data
Definition: bloom.h:129
bool GetOp(iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet)
Definition: script.h:488
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:244
std::vector< CTxIn > vin
Definition: transaction.h:270
const uint256 & GetHash() const
Definition: transaction.h:301
std::vector< CTxOut > vout
Definition: transaction.h:271
An input of a transaction.
Definition: transaction.h:94
CScript scriptSig
Definition: transaction.h:97
COutPoint prevout
Definition: transaction.h:96
An output of a transaction.
Definition: transaction.h:137
CScript scriptPubKey
Definition: transaction.h:140
unsigned char * end()
Definition: uint256.h:68
unsigned char * begin()
Definition: uint256.h:63
iterator begin()
Definition: prevector.h:285
iterator end()
Definition: prevector.h:287
256-bit opaque blob.
Definition: uint256.h:138
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector< unsigned char > &vDataToHash)
Definition: hash.cpp:16
Definition: uint256.h:212
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:586
opcodetype
Script opcodes.
Definition: script.h:50
@ SER_NETWORK
Definition: serialize.h:174
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:90
txnouttype
Definition: standard.h:46
@ TX_PUBKEY
Definition: standard.h:49
@ TX_MULTISIG
Definition: standard.h:52