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