You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bloom.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright (c) 2012-2016 The Starwels developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include "bloom.h"
  5. #include "primitives/transaction.h"
  6. #include "hash.h"
  7. #include "script/script.h"
  8. #include "script/standard.h"
  9. #include "random.h"
  10. #include "streams.h"
  11. #include <math.h>
  12. #include <stdlib.h>
  13. #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
  14. #define LN2 0.6931471805599453094172321214581765680755001343602552
  15. CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
  16. /**
  17. * The ideal size for a bloom filter with a given number of elements and false positive rate is:
  18. * - nElements * log(fp rate) / ln(2)^2
  19. * We ignore filter parameters which will create a bloom filter larger than the protocol limits
  20. */
  21. vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
  22. /**
  23. * The ideal number of hash functions is filter size * ln(2) / number of elements
  24. * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
  25. * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
  26. */
  27. isFull(false),
  28. isEmpty(true),
  29. nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
  30. nTweak(nTweakIn),
  31. nFlags(nFlagsIn)
  32. {
  33. }
  34. // Private constructor used by CRollingBloomFilter
  35. CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn) :
  36. vData((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)) / 8),
  37. isFull(false),
  38. isEmpty(true),
  39. nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
  40. nTweak(nTweakIn),
  41. nFlags(BLOOM_UPDATE_NONE)
  42. {
  43. }
  44. inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
  45. {
  46. // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
  47. return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
  48. }
  49. void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
  50. {
  51. if (isFull)
  52. return;
  53. for (unsigned int i = 0; i < nHashFuncs; i++)
  54. {
  55. unsigned int nIndex = Hash(i, vKey);
  56. // Sets bit nIndex of vData
  57. vData[nIndex >> 3] |= (1 << (7 & nIndex));
  58. }
  59. isEmpty = false;
  60. }
  61. void CBloomFilter::insert(const COutPoint& outpoint)
  62. {
  63. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
  64. stream << outpoint;
  65. std::vector<unsigned char> data(stream.begin(), stream.end());
  66. insert(data);
  67. }
  68. void CBloomFilter::insert(const uint256& hash)
  69. {
  70. std::vector<unsigned char> data(hash.begin(), hash.end());
  71. insert(data);
  72. }
  73. bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
  74. {
  75. if (isFull)
  76. return true;
  77. if (isEmpty)
  78. return false;
  79. for (unsigned int i = 0; i < nHashFuncs; i++)
  80. {
  81. unsigned int nIndex = Hash(i, vKey);
  82. // Checks bit nIndex of vData
  83. if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
  84. return false;
  85. }
  86. return true;
  87. }
  88. bool CBloomFilter::contains(const COutPoint& outpoint) const
  89. {
  90. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
  91. stream << outpoint;
  92. std::vector<unsigned char> data(stream.begin(), stream.end());
  93. return contains(data);
  94. }
  95. bool CBloomFilter::contains(const uint256& hash) const
  96. {
  97. std::vector<unsigned char> data(hash.begin(), hash.end());
  98. return contains(data);
  99. }
  100. void CBloomFilter::clear()
  101. {
  102. vData.assign(vData.size(),0);
  103. isFull = false;
  104. isEmpty = true;
  105. }
  106. void CBloomFilter::reset(const unsigned int nNewTweak)
  107. {
  108. clear();
  109. nTweak = nNewTweak;
  110. }
  111. bool CBloomFilter::IsWithinSizeConstraints() const
  112. {
  113. return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
  114. }
  115. bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
  116. {
  117. bool fFound = false;
  118. // Match if the filter contains the hash of tx
  119. // for finding tx when they appear in a block
  120. if (isFull)
  121. return true;
  122. if (isEmpty)
  123. return false;
  124. const uint256& hash = tx.GetHash();
  125. if (contains(hash))
  126. fFound = true;
  127. for (unsigned int i = 0; i < tx.vout.size(); i++)
  128. {
  129. const CTxOut& txout = tx.vout[i];
  130. // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
  131. // If this matches, also add the specific output that was matched.
  132. // This means clients don't have to update the filter themselves when a new relevant tx
  133. // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
  134. CScript::const_iterator pc = txout.scriptPubKey.begin();
  135. std::vector<unsigned char> data;
  136. while (pc < txout.scriptPubKey.end())
  137. {
  138. opcodetype opcode;
  139. if (!txout.scriptPubKey.GetOp(pc, opcode, data))
  140. break;
  141. if (data.size() != 0 && contains(data))
  142. {
  143. fFound = true;
  144. if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
  145. insert(COutPoint(hash, i));
  146. else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
  147. {
  148. txnouttype type;
  149. std::vector<std::vector<unsigned char> > vSolutions;
  150. if (Solver(txout.scriptPubKey, type, vSolutions) &&
  151. (type == TX_PUBKEY || type == TX_MULTISIG))
  152. insert(COutPoint(hash, i));
  153. }
  154. break;
  155. }
  156. }
  157. }
  158. if (fFound)
  159. return true;
  160. for (const CTxIn& txin : tx.vin)
  161. {
  162. // Match if the filter contains an outpoint tx spends
  163. if (contains(txin.prevout))
  164. return true;
  165. // Match if the filter contains any arbitrary script data element in any scriptSig in tx
  166. CScript::const_iterator pc = txin.scriptSig.begin();
  167. std::vector<unsigned char> data;
  168. while (pc < txin.scriptSig.end())
  169. {
  170. opcodetype opcode;
  171. if (!txin.scriptSig.GetOp(pc, opcode, data))
  172. break;
  173. if (data.size() != 0 && contains(data))
  174. return true;
  175. }
  176. }
  177. return false;
  178. }
  179. void CBloomFilter::UpdateEmptyFull()
  180. {
  181. bool full = true;
  182. bool empty = true;
  183. for (unsigned int i = 0; i < vData.size(); i++)
  184. {
  185. full &= vData[i] == 0xff;
  186. empty &= vData[i] == 0;
  187. }
  188. isFull = full;
  189. isEmpty = empty;
  190. }
  191. CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
  192. {
  193. double logFpRate = log(fpRate);
  194. /* The optimal number of hash functions is log(fpRate) / log(0.5), but
  195. * restrict it to the range 1-50. */
  196. nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
  197. /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
  198. nEntriesPerGeneration = (nElements + 1) / 2;
  199. uint32_t nMaxElements = nEntriesPerGeneration * 3;
  200. /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
  201. * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
  202. * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
  203. * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
  204. * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
  205. * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
  206. */
  207. uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
  208. data.clear();
  209. /* For each data element we need to store 2 bits. If both bits are 0, the
  210. * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
  211. * treated as set in generation 1, 2, or 3 respectively.
  212. * These bits are stored in separate integers: position P corresponds to bit
  213. * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
  214. data.resize(((nFilterBits + 63) / 64) << 1);
  215. reset();
  216. }
  217. /* Similar to CBloomFilter::Hash */
  218. static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
  219. return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
  220. }
  221. void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
  222. {
  223. if (nEntriesThisGeneration == nEntriesPerGeneration) {
  224. nEntriesThisGeneration = 0;
  225. nGeneration++;
  226. if (nGeneration == 4) {
  227. nGeneration = 1;
  228. }
  229. uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
  230. uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
  231. /* Wipe old entries that used this generation number. */
  232. for (uint32_t p = 0; p < data.size(); p += 2) {
  233. uint64_t p1 = data[p], p2 = data[p + 1];
  234. uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
  235. data[p] = p1 & mask;
  236. data[p + 1] = p2 & mask;
  237. }
  238. }
  239. nEntriesThisGeneration++;
  240. for (int n = 0; n < nHashFuncs; n++) {
  241. uint32_t h = RollingBloomHash(n, nTweak, vKey);
  242. int bit = h & 0x3F;
  243. uint32_t pos = (h >> 6) % data.size();
  244. /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
  245. data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
  246. data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
  247. }
  248. }
  249. void CRollingBloomFilter::insert(const uint256& hash)
  250. {
  251. std::vector<unsigned char> vData(hash.begin(), hash.end());
  252. insert(vData);
  253. }
  254. bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
  255. {
  256. for (int n = 0; n < nHashFuncs; n++) {
  257. uint32_t h = RollingBloomHash(n, nTweak, vKey);
  258. int bit = h & 0x3F;
  259. uint32_t pos = (h >> 6) % data.size();
  260. /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
  261. if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
  262. return false;
  263. }
  264. }
  265. return true;
  266. }
  267. bool CRollingBloomFilter::contains(const uint256& hash) const
  268. {
  269. std::vector<unsigned char> vData(hash.begin(), hash.end());
  270. return contains(vData);
  271. }
  272. void CRollingBloomFilter::reset()
  273. {
  274. nTweak = GetRand(std::numeric_limits<unsigned int>::max());
  275. nEntriesThisGeneration = 0;
  276. nGeneration = 1;
  277. for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
  278. *it = 0;
  279. }
  280. }