Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

bloom.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2015 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 <evo/specialtx.h>
9 #include <evo/providertx.h>
10 #include <evo/cbtx.h>
12 #include <hash.h>
13 #include <script/script.h>
14 #include <script/standard.h>
15 #include <random.h>
16 #include <streams.h>
17 
18 #include <math.h>
19 #include <stdlib.h>
20 
21 
22 #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
23 #define LN2 0.6931471805599453094172321214581765680755001343602552
24 
25 CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
31  vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
37  isFull(false),
38  isEmpty(true),
39  nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
40  nTweak(nTweakIn),
41  nFlags(nFlagsIn)
42 {
43 }
44 
45 // Private constructor used by CRollingBloomFilter
46 CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn) :
47  vData((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)) / 8),
48  isFull(false),
49  isEmpty(true),
50  nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
51  nTweak(nTweakIn),
52  nFlags(BLOOM_UPDATE_NONE)
53 {
54 }
55 
56 inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
57 {
58  // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
59  return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
60 }
61 
62 void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
63 {
64  if (isFull)
65  return;
66  for (unsigned int i = 0; i < nHashFuncs; i++)
67  {
68  unsigned int nIndex = Hash(i, vKey);
69  // Sets bit nIndex of vData
70  vData[nIndex >> 3] |= (1 << (7 & nIndex));
71  }
72  isEmpty = false;
73 }
74 
75 void CBloomFilter::insert(const COutPoint& outpoint)
76 {
78  stream << outpoint;
79  std::vector<unsigned char> data(stream.begin(), stream.end());
80  insert(data);
81 }
82 
83 void CBloomFilter::insert(const uint256& hash)
84 {
85  std::vector<unsigned char> data(hash.begin(), hash.end());
86  insert(data);
87 }
88 
89 bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
90 {
91  if (isFull)
92  return true;
93  if (isEmpty)
94  return false;
95  for (unsigned int i = 0; i < nHashFuncs; i++)
96  {
97  unsigned int nIndex = Hash(i, vKey);
98  // Checks bit nIndex of vData
99  if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
100  return false;
101  }
102  return true;
103 }
104 
105 bool CBloomFilter::contains(const COutPoint& outpoint) const
106 {
108  stream << outpoint;
109  std::vector<unsigned char> data(stream.begin(), stream.end());
110  return contains(data);
111 }
112 
113 bool CBloomFilter::contains(const uint256& hash) const
114 {
115  std::vector<unsigned char> data(hash.begin(), hash.end());
116  return contains(data);
117 }
118 
119 bool CBloomFilter::contains(const uint160& hash) const
120 {
121  std::vector<unsigned char> data(hash.begin(), hash.end());
122  return contains(data);
123 }
124 
126 {
127  vData.assign(vData.size(),0);
128  isFull = false;
129  isEmpty = true;
130 }
131 
132 void CBloomFilter::reset(const unsigned int nNewTweak)
133 {
134  clear();
135  nTweak = nNewTweak;
136 }
137 
139 {
140  return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
141 }
142 
143 // Match if the filter contains any arbitrary script data element in script
144 bool CBloomFilter::CheckScript(const CScript &script) const
145 {
146  CScript::const_iterator pc = script.begin();
147  std::vector<unsigned char> data;
148  while (pc < script.end()) {
149  opcodetype opcode;
150  if (!script.GetOp(pc, opcode, data))
151  break;
152  if (data.size() != 0 && contains(data))
153  return true;
154  }
155  return false;
156 }
157 
158 // If the transaction is a special transaction that has a registration
159 // transaction hash, test the registration transaction hash.
160 // If the transaction is a special transaction with any public keys or any
161 // public key hashes test them.
162 // If the transaction is a special transaction with payout addresses test
163 // the hash160 of those addresses.
164 // Filter is updated only if it has BLOOM_UPDATE_ALL flag to be able to have
165 // simple SPV wallets that doesn't work with DIP2 transactions (multicoin
166 // wallets, etc.)
168 {
169  if(tx.nVersion != 3 || tx.nType == TRANSACTION_NORMAL) {
170  return false; // it is not a special transaction
171  }
172  switch(tx.nType) {
174  CProRegTx proTx;
175  if (GetTxPayload(tx, proTx)) {
176  if(contains(proTx.collateralOutpoint) ||
177  contains(proTx.keyIDOwner) ||
178  contains(proTx.keyIDVoting) ||
179  CheckScript(proTx.scriptPayout)) {
181  insert(tx.GetHash());
182  return true;
183  }
184  }
185  return false;
186  }
188  CProUpServTx proTx;
189  if (GetTxPayload(tx, proTx)) {
190  if(contains(proTx.proTxHash)) {
191  return true;
192  }
193  if(CheckScript(proTx.scriptOperatorPayout)) {
195  insert(proTx.proTxHash);
196  return true;
197  }
198  }
199  return false;
200  }
202  CProUpRegTx proTx;
203  if (GetTxPayload(tx, proTx)) {
204  if(contains(proTx.proTxHash))
205  return true;
206  if(contains(proTx.keyIDVoting) ||
207  CheckScript(proTx.scriptPayout)) {
209  insert(proTx.proTxHash);
210  return true;
211  }
212  }
213  return false;
214  }
216  CProUpRevTx proTx;
217  if (GetTxPayload(tx, proTx)) {
218  if(contains(proTx.proTxHash))
219  return true;
220  }
221  return false;
222  }
223  case(TRANSACTION_COINBASE):
225  // No aditional checks for this transaction types
226  return false;
227  }
228 
229  LogPrintf("Unknown special transaction type in Bloom filter check.\n");
230  return false;
231 }
232 
234 {
235  bool fFound = false;
236  // Match if the filter contains the hash of tx
237  // for finding tx when they appear in a block
238  if (isFull)
239  return true;
240  if (isEmpty)
241  return false;
242  const uint256& hash = tx.GetHash();
243  if (contains(hash))
244  fFound = true;
245 
246  // Check additional matches for special transactions
247  fFound = fFound || CheckSpecialTransactionMatchesAndUpdate(tx);
248 
249  for (unsigned int i = 0; i < tx.vout.size(); i++)
250  {
251  const CTxOut& txout = tx.vout[i];
252  // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
253  // If this matches, also add the specific output that was matched.
254  // This means clients don't have to update the filter themselves when a new relevant tx
255  // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
256  if(CheckScript(txout.scriptPubKey)) {
257  fFound = true;
259  insert(COutPoint(hash, i));
261  {
262  txnouttype type;
263  std::vector<std::vector<unsigned char> > vSolutions;
264  if (Solver(txout.scriptPubKey, type, vSolutions) &&
265  (type == TX_PUBKEY || type == TX_MULTISIG))
266  insert(COutPoint(hash, i));
267  }
268  }
269  }
270 
271  if (fFound)
272  return true;
273 
274  for (const CTxIn& txin : tx.vin)
275  {
276  // Match if the filter contains an outpoint tx spends
277  if (contains(txin.prevout))
278  return true;
279 
280  // Match if the filter contains any arbitrary script data element in any scriptSig in tx
281  if(CheckScript(txin.scriptSig))
282  return true;
283  }
284 
285  return false;
286 }
287 
289 {
290  bool full = true;
291  bool empty = true;
292  for (unsigned int i = 0; i < vData.size(); i++)
293  {
294  full &= vData[i] == 0xff;
295  empty &= vData[i] == 0;
296  }
297  isFull = full;
298  isEmpty = empty;
299 }
300 
301 CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
302 {
303  double logFpRate = log(fpRate);
304  /* The optimal number of hash functions is log(fpRate) / log(0.5), but
305  * restrict it to the range 1-50. */
306  nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
307  /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
308  nEntriesPerGeneration = (nElements + 1) / 2;
309  uint32_t nMaxElements = nEntriesPerGeneration * 3;
310  /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
311  * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
312  * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
313  * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
314  * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
315  * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
316  */
317  uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
318  data.clear();
319  /* For each data element we need to store 2 bits. If both bits are 0, the
320  * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
321  * treated as set in generation 1, 2, or 3 respectively.
322  * These bits are stored in separate integers: position P corresponds to bit
323  * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
324  data.resize(((nFilterBits + 63) / 64) << 1);
325  reset();
326 }
327 
328 /* Similar to CBloomFilter::Hash */
329 static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
330  return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
331 }
332 
333 
334 // A replacement for x % n. This assumes that x and n are 32bit integers, and x is a uniformly random distributed 32bit value
335 // which should be the case for a good hash.
336 // See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
337 static inline uint32_t FastMod(uint32_t x, size_t n) {
338  return ((uint64_t)x * (uint64_t)n) >> 32;
339 }
340 
341 void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
342 {
345  nGeneration++;
346  if (nGeneration == 4) {
347  nGeneration = 1;
348  }
349  uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
350  uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
351  /* Wipe old entries that used this generation number. */
352  for (uint32_t p = 0; p < data.size(); p += 2) {
353  uint64_t p1 = data[p], p2 = data[p + 1];
354  uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
355  data[p] = p1 & mask;
356  data[p + 1] = p2 & mask;
357  }
358  }
360 
361  for (int n = 0; n < nHashFuncs; n++) {
362  uint32_t h = RollingBloomHash(n, nTweak, vKey);
363  int bit = h & 0x3F;
364  /* 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. */
365  uint32_t pos = FastMod(h, data.size());
366  /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
367  data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
368  data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
369  }
370 }
371 
373 {
374  std::vector<unsigned char> vData(hash.begin(), hash.end());
375  insert(vData);
376 }
377 
378 bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
379 {
380  for (int n = 0; n < nHashFuncs; n++) {
381  uint32_t h = RollingBloomHash(n, nTweak, vKey);
382  int bit = h & 0x3F;
383  uint32_t pos = FastMod(h, data.size());
384  /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
385  if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
386  return false;
387  }
388  }
389  return true;
390 }
391 
392 bool CRollingBloomFilter::contains(const uint256& hash) const
393 {
394  std::vector<unsigned char> vData(hash.begin(), hash.end());
395  return contains(vData);
396 }
397 
399 {
400  nTweak = GetRand(std::numeric_limits<unsigned int>::max());
402  nGeneration = 1;
403  for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
404  *it = 0;
405  }
406 }
bool GetTxPayload(const std::vector< unsigned char > &payload, T &obj)
Definition: specialtx.h:21
uint256 proTxHash
Definition: providertx.h:142
uint256 proTxHash
Definition: providertx.h:95
CKeyID keyIDVoting
Definition: providertx.h:145
CRollingBloomFilter(const unsigned int nElements, const double nFPRate)
Definition: bloom.cpp:301
CScript scriptPubKey
Definition: transaction.h:148
COutPoint collateralOutpoint
Definition: providertx.h:28
unsigned int nTweak
Definition: bloom.h:53
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:341
unsigned char nFlags
Definition: bloom.h:54
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes) ...
Definition: bloom.cpp:233
bool CheckScript(const CScript &script) const
Definition: bloom.cpp:144
CScript scriptOperatorPayout
Definition: providertx.h:97
unsigned int nTweak
Definition: bloom.h:146
bool isFull
Definition: bloom.h:50
CKeyID keyIDVoting
Definition: providertx.h:32
Definition: box.hpp:161
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:19
std::vector< unsigned char > vData
Definition: bloom.h:49
false true true true
Definition: bls_dkg.cpp:176
unsigned int Hash(unsigned int nHashNum, const std::vector< unsigned char > &vDataToHash) const
Definition: bloom.cpp:56
unsigned int nHashFuncs
Definition: bloom.h:52
void reset(const unsigned int nNewTweak)
Definition: bloom.cpp:132
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:103
#define LN2
Definition: bloom.cpp:23
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:62
unsigned char * begin()
Definition: uint256.h:57
unsigned char * end()
Definition: uint256.h:62
const std::vector< CTxIn > vin
Definition: transaction.h:215
const impl< T, B, MP > empty
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:378
iterator end()
Definition: prevector.h:320
false
Definition: bls_dkg.cpp:168
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector< unsigned char > &vDataToHash)
Definition: hash.cpp:15
opcodetype
Script opcodes.
Definition: script.h:48
#define LogPrintf(...)
Definition: util.h:203
An input of a transaction.
Definition: transaction.h:70
const uint256 & GetHash() const
Definition: transaction.h:256
void clear()
Definition: bloom.cpp:125
static uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector< unsigned char > &vDataToHash)
Definition: bloom.cpp:329
CBloomFilter()
Definition: bloom.h:77
const std::vector< CTxOut > vout
Definition: transaction.h:216
CKeyID keyIDOwner
Definition: providertx.h:30
An output of a transaction.
Definition: transaction.h:144
CScript scriptPayout
Definition: providertx.h:34
static const unsigned int MAX_HASH_FUNCS
Definition: bloom.h:20
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
std::vector< uint64_t > data
Definition: bloom.h:145
CScript scriptPayout
Definition: providertx.h:146
#define LN2SQUARED
Definition: bloom.cpp:22
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:35
bool CheckSpecialTransactionMatchesAndUpdate(const CTransaction &tx)
Definition: bloom.cpp:167
const int16_t nVersion
Definition: transaction.h:217
constexpr T mask
Definition: bits.hpp:45
CScript scriptSig
Definition: transaction.h:74
txnouttype
Definition: standard.h:56
256-bit opaque blob.
Definition: uint256.h:123
int nEntriesThisGeneration
Definition: bloom.h:143
const_iterator end() const
Definition: streams.h:192
const_iterator begin() const
Definition: streams.h:190
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:389
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:14
160-bit opaque blob.
Definition: uint256.h:112
iterator begin()
Definition: prevector.h:318
void UpdateEmptyFull()
Checks for empty and full filters to avoid wasting cpu.
Definition: bloom.cpp:288
bool GetOp(iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet)
Definition: script.h:496
static uint32_t FastMod(uint32_t x, size_t n)
Definition: bloom.cpp:337
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
COutPoint prevout
Definition: transaction.h:73
const int16_t nType
Definition: transaction.h:218
bool isEmpty
Definition: bloom.h:51
uint256 proTxHash
Definition: providertx.h:203
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:138
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:354
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:89
int nEntriesPerGeneration
Definition: bloom.h:142
Released under the MIT license