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