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