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