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 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright (c) 2012-2014 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. #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. #include <boost/foreach.hpp>
  14. #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
  15. #define LN2 0.6931471805599453094172321214581765680755001343602552
  16. using namespace std;
  17. CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :
  18. /**
  19. * The ideal size for a bloom filter with a given number of elements and false positive rate is:
  20. * - nElements * log(fp rate) / ln(2)^2
  21. * We ignore filter parameters which will create a bloom filter larger than the protocol limits
  22. */
  23. vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
  24. /**
  25. * The ideal number of hash functions is filter size * ln(2) / number of elements
  26. * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
  27. * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
  28. */
  29. isFull(false),
  30. isEmpty(false),
  31. nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
  32. nTweak(nTweakIn),
  33. nFlags(nFlagsIn)
  34. {
  35. }
  36. // Private constructor used by CRollingBloomFilter
  37. CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn) :
  38. vData((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)) / 8),
  39. isFull(false),
  40. isEmpty(true),
  41. nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
  42. nTweak(nTweakIn),
  43. nFlags(BLOOM_UPDATE_NONE)
  44. {
  45. }
  46. inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
  47. {
  48. // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
  49. return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
  50. }
  51. void CBloomFilter::insert(const vector<unsigned char>& vKey)
  52. {
  53. if (isFull)
  54. return;
  55. for (unsigned int i = 0; i < nHashFuncs; i++)
  56. {
  57. unsigned int nIndex = Hash(i, vKey);
  58. // Sets bit nIndex of vData
  59. vData[nIndex >> 3] |= (1 << (7 & nIndex));
  60. }
  61. isEmpty = false;
  62. }
  63. void CBloomFilter::insert(const COutPoint& outpoint)
  64. {
  65. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
  66. stream << outpoint;
  67. vector<unsigned char> data(stream.begin(), stream.end());
  68. insert(data);
  69. }
  70. void CBloomFilter::insert(const uint256& hash)
  71. {
  72. vector<unsigned char> data(hash.begin(), hash.end());
  73. insert(data);
  74. }
  75. bool CBloomFilter::contains(const vector<unsigned char>& vKey) const
  76. {
  77. if (isFull)
  78. return true;
  79. if (isEmpty)
  80. return false;
  81. for (unsigned int i = 0; i < nHashFuncs; i++)
  82. {
  83. unsigned int nIndex = Hash(i, vKey);
  84. // Checks bit nIndex of vData
  85. if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
  86. return false;
  87. }
  88. return true;
  89. }
  90. bool CBloomFilter::contains(const COutPoint& outpoint) const
  91. {
  92. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
  93. stream << outpoint;
  94. vector<unsigned char> data(stream.begin(), stream.end());
  95. return contains(data);
  96. }
  97. bool CBloomFilter::contains(const uint256& hash) const
  98. {
  99. vector<unsigned char> data(hash.begin(), hash.end());
  100. return contains(data);
  101. }
  102. void CBloomFilter::clear()
  103. {
  104. vData.assign(vData.size(),0);
  105. isFull = false;
  106. isEmpty = true;
  107. }
  108. void CBloomFilter::reset(unsigned int nNewTweak)
  109. {
  110. clear();
  111. nTweak = nNewTweak;
  112. }
  113. bool CBloomFilter::IsWithinSizeConstraints() const
  114. {
  115. return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
  116. }
  117. bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
  118. {
  119. bool fFound = false;
  120. // Match if the filter contains the hash of tx
  121. // for finding tx when they appear in a block
  122. if (isFull)
  123. return true;
  124. if (isEmpty)
  125. return false;
  126. const uint256& hash = tx.GetHash();
  127. if (contains(hash))
  128. fFound = true;
  129. for (unsigned int i = 0; i < tx.vout.size(); i++)
  130. {
  131. const CTxOut& txout = tx.vout[i];
  132. // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
  133. // If this matches, also add the specific output that was matched.
  134. // This means clients don't have to update the filter themselves when a new relevant tx
  135. // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
  136. CScript::const_iterator pc = txout.scriptPubKey.begin();
  137. vector<unsigned char> data;
  138. while (pc < txout.scriptPubKey.end())
  139. {
  140. opcodetype opcode;
  141. if (!txout.scriptPubKey.GetOp(pc, opcode, data))
  142. break;
  143. if (data.size() != 0 && contains(data))
  144. {
  145. fFound = true;
  146. if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
  147. insert(COutPoint(hash, i));
  148. else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
  149. {
  150. txnouttype type;
  151. vector<vector<unsigned char> > vSolutions;
  152. if (Solver(txout.scriptPubKey, type, vSolutions) &&
  153. (type == TX_PUBKEY || type == TX_MULTISIG))
  154. insert(COutPoint(hash, i));
  155. }
  156. break;
  157. }
  158. }
  159. }
  160. if (fFound)
  161. return true;
  162. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  163. {
  164. // Match if the filter contains an outpoint tx spends
  165. if (contains(txin.prevout))
  166. return true;
  167. // Match if the filter contains any arbitrary script data element in any scriptSig in tx
  168. CScript::const_iterator pc = txin.scriptSig.begin();
  169. vector<unsigned char> data;
  170. while (pc < txin.scriptSig.end())
  171. {
  172. opcodetype opcode;
  173. if (!txin.scriptSig.GetOp(pc, opcode, data))
  174. break;
  175. if (data.size() != 0 && contains(data))
  176. return true;
  177. }
  178. }
  179. return false;
  180. }
  181. void CBloomFilter::UpdateEmptyFull()
  182. {
  183. bool full = true;
  184. bool empty = true;
  185. for (unsigned int i = 0; i < vData.size(); i++)
  186. {
  187. full &= vData[i] == 0xff;
  188. empty &= vData[i] == 0;
  189. }
  190. isFull = full;
  191. isEmpty = empty;
  192. }
  193. CRollingBloomFilter::CRollingBloomFilter(unsigned int nElements, double fpRate) :
  194. b1(nElements * 2, fpRate, 0), b2(nElements * 2, fpRate, 0)
  195. {
  196. // Implemented using two bloom filters of 2 * nElements each.
  197. // We fill them up, and clear them, staggered, every nElements
  198. // inserted, so at least one always contains the last nElements
  199. // inserted.
  200. nInsertions = 0;
  201. nBloomSize = nElements * 2;
  202. reset();
  203. }
  204. void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
  205. {
  206. if (nInsertions == 0) {
  207. b1.clear();
  208. } else if (nInsertions == nBloomSize / 2) {
  209. b2.clear();
  210. }
  211. b1.insert(vKey);
  212. b2.insert(vKey);
  213. if (++nInsertions == nBloomSize) {
  214. nInsertions = 0;
  215. }
  216. }
  217. void CRollingBloomFilter::insert(const uint256& hash)
  218. {
  219. vector<unsigned char> data(hash.begin(), hash.end());
  220. insert(data);
  221. }
  222. bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
  223. {
  224. if (nInsertions < nBloomSize / 2) {
  225. return b2.contains(vKey);
  226. }
  227. return b1.contains(vKey);
  228. }
  229. bool CRollingBloomFilter::contains(const uint256& hash) const
  230. {
  231. vector<unsigned char> data(hash.begin(), hash.end());
  232. return contains(data);
  233. }
  234. void CRollingBloomFilter::reset()
  235. {
  236. unsigned int nNewTweak = GetRand(std::numeric_limits<unsigned int>::max());
  237. b1.reset(nNewTweak);
  238. b2.reset(nNewTweak);
  239. nInsertions = 0;
  240. }