Line data Source code
1 : // Copyright (c) 2012-2021 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 <common/bloom.h>
6 :
7 : #include <evo/assetlocktx.h>
8 : #include <evo/providertx.h>
9 : #include <evo/specialtx.h>
10 : #include <hash.h>
11 : #include <logging.h>
12 : #include <primitives/transaction.h>
13 : #include <random.h>
14 : #include <script/script.h>
15 : #include <script/standard.h>
16 : #include <span.h>
17 : #include <streams.h>
18 : #include <util/fastrange.h>
19 :
20 : #include <algorithm>
21 : #include <cmath>
22 : #include <cstdlib>
23 : #include <limits>
24 : #include <vector>
25 :
26 : static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
27 : static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
28 :
29 1318 : CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
30 : /**
31 : * The ideal size for a bloom filter with a given number of elements and false positive rate is:
32 : * - nElements * log(fp rate) / ln(2)^2
33 : * We ignore filter parameters which will create a bloom filter larger than the protocol limits
34 : */
35 659 : vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
36 : /**
37 : * The ideal number of hash functions is filter size * ln(2) / number of elements
38 : * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
39 : * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
40 : */
41 659 : nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
42 659 : nTweak(nTweakIn),
43 659 : nFlags(nFlagsIn)
44 659 : {
45 1318 : }
46 :
47 46415 : inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, Span<const unsigned char> vDataToHash) const
48 : {
49 : // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
50 46415 : return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
51 : }
52 :
53 2673 : void CBloomFilter::insert(Span<const unsigned char> vKey)
54 : {
55 2673 : if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
56 4 : return;
57 27416 : for (unsigned int i = 0; i < nHashFuncs; i++)
58 : {
59 24747 : unsigned int nIndex = Hash(i, vKey);
60 : // Sets bit nIndex of vData
61 24747 : vData[nIndex >> 3] |= (1 << (7 & nIndex));
62 24747 : }
63 2673 : }
64 :
65 23 : void CBloomFilter::insert(const COutPoint& outpoint)
66 : {
67 23 : CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
68 23 : stream << outpoint;
69 23 : insert(MakeUCharSpan(stream));
70 23 : }
71 :
72 2819 : bool CBloomFilter::contains(Span<const unsigned char> vKey) const
73 : {
74 2819 : if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
75 0 : return true;
76 23951 : for (unsigned int i = 0; i < nHashFuncs; i++)
77 : {
78 21668 : unsigned int nIndex = Hash(i, vKey);
79 : // Checks bit nIndex of vData
80 21668 : if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
81 536 : return false;
82 21132 : }
83 2283 : return true;
84 2819 : }
85 :
86 105 : bool CBloomFilter::contains(const COutPoint& outpoint) const
87 : {
88 105 : CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
89 105 : stream << outpoint;
90 105 : return contains(MakeUCharSpan(stream));
91 105 : }
92 :
93 18 : bool CBloomFilter::IsWithinSizeConstraints() const
94 : {
95 18 : return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
96 : }
97 :
98 : // Match if the filter contains any arbitrary script data element in script
99 267 : bool CBloomFilter::CheckScript(const CScript &script) const
100 : {
101 267 : CScript::const_iterator pc = script.begin();
102 267 : std::vector<unsigned char> data;
103 1065 : while (pc < script.end()) {
104 : opcodetype opcode;
105 825 : if (!script.GetOp(pc, opcode, data))
106 0 : break;
107 825 : if (data.size() != 0 && contains(data))
108 27 : return true;
109 : }
110 240 : return false;
111 267 : }
112 :
113 : // If the transaction is a special transaction that has a registration
114 : // transaction hash, test the registration transaction hash.
115 : // If the transaction is a special transaction with any public keys or any
116 : // public key hashes test them.
117 : // If the transaction is a special transaction with payout addresses test
118 : // the hash160 of those addresses.
119 : // Filter is updated only if it has BLOOM_UPDATE_ALL flag to be able to have
120 : // simple SPV wallets that doesn't work with DIP2 transactions (multicoin
121 : // wallets, etc.)
122 : // NOTE(maintenance): Keep this implementation in sync with
123 : // ExtractSpecialTxFilterElements in src/evo/specialtx_filter.cpp.
124 : // Both routines must handle the same set of special-transaction fields.
125 : // If you modify one, update the other to prevent mismatches between
126 : // bloom filter relevance and compact filter element extraction.
127 99 : bool CBloomFilter::CheckSpecialTransactionMatchesAndUpdate(const CTransaction &tx)
128 : {
129 99 : if (!tx.HasExtraPayloadField()) {
130 81 : return false; // it is not a special transaction
131 : }
132 18 : switch(tx.nType) {
133 : case(TRANSACTION_PROVIDER_REGISTER): {
134 10 : if (const auto opt_proTx = GetTxPayload<CProRegTx>(tx)) {
135 6 : if(contains(opt_proTx->collateralOutpoint) ||
136 3 : contains(opt_proTx->keyIDOwner) ||
137 2 : contains(opt_proTx->keyIDVoting) ||
138 1 : CheckScript(opt_proTx->scriptPayout)) {
139 5 : if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
140 5 : insert(tx.GetHash());
141 5 : return true;
142 : }
143 0 : }
144 0 : return false;
145 : }
146 : case(TRANSACTION_PROVIDER_UPDATE_SERVICE): {
147 12 : if (const auto opt_proTx = GetTxPayload<CProUpServTx>(tx)) {
148 6 : if(contains(opt_proTx->proTxHash)) {
149 3 : return true;
150 : }
151 3 : if(CheckScript(opt_proTx->scriptOperatorPayout)) {
152 0 : if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
153 0 : insert(opt_proTx->proTxHash);
154 0 : return true;
155 : }
156 3 : }
157 3 : return false;
158 : }
159 : case(TRANSACTION_PROVIDER_UPDATE_REGISTRAR): {
160 10 : if (const auto opt_proTx = GetTxPayload<CProUpRegTx>(tx)) {
161 5 : if(contains(opt_proTx->proTxHash))
162 1 : return true;
163 6 : if(contains(opt_proTx->keyIDVoting) ||
164 2 : CheckScript(opt_proTx->scriptPayout)) {
165 3 : if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
166 3 : insert(opt_proTx->proTxHash);
167 3 : return true;
168 : }
169 1 : }
170 1 : return false;
171 : }
172 : case(TRANSACTION_PROVIDER_UPDATE_REVOKE): {
173 4 : if (const auto opt_proTx = GetTxPayload<CProUpRevTx>(tx)) {
174 2 : if(contains(opt_proTx->proTxHash))
175 1 : return true;
176 1 : }
177 1 : return false;
178 : }
179 : case(TRANSACTION_ASSET_LOCK): {
180 : // inputs of Asset Lock transactions are standard. But some outputs are special
181 0 : if (const auto opt_assetlockTx = GetTxPayload<CAssetLockPayload>(tx)) {
182 0 : bool fFound = false;
183 0 : const auto& extraOuts = opt_assetlockTx->getCreditOutputs();
184 0 : for (unsigned int i = 0; i < extraOuts.size(); ++i)
185 : {
186 0 : fFound = ProcessTxOut(extraOuts[i], tx.GetHash(), i) || fFound;
187 0 : }
188 0 : if (fFound) return true;
189 0 : }
190 0 : return false;
191 : }
192 : case(TRANSACTION_ASSET_UNLOCK): // Outputs are standard and no inputs.
193 : case(TRANSACTION_COINBASE):
194 : case(TRANSACTION_QUORUM_COMMITMENT):
195 : case(TRANSACTION_MNHF_SIGNAL):
196 : // No additional checks for this transaction types
197 0 : return false;
198 : }
199 :
200 0 : LogPrintf("Unknown special transaction type in Bloom filter check.\n");
201 0 : return false;
202 99 : }
203 :
204 169 : bool CBloomFilter::ProcessTxOut(const CTxOut& txout, const uint256& hash, unsigned int index)
205 : {
206 : // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
207 : // If this matches, also add the specific output that was matched.
208 : // This means clients don't have to update the filter themselves when a new relevant tx
209 : // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
210 169 : bool fFound = false;
211 169 : if(CheckScript(txout.scriptPubKey)) {
212 23 : fFound = true;
213 23 : if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
214 17 : insert(COutPoint(hash, index));
215 6 : else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
216 : {
217 2 : std::vector<std::vector<unsigned char> > vSolutions;
218 2 : TxoutType type = Solver(txout.scriptPubKey, vSolutions);
219 2 : if (type == TxoutType::PUBKEY || type == TxoutType::MULTISIG) {
220 1 : insert(COutPoint(hash, index));
221 1 : }
222 2 : }
223 23 : }
224 169 : return fFound;
225 0 : }
226 :
227 112 : bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
228 : {
229 112 : bool fFound = false;
230 : // Match if the filter contains the hash of tx
231 : // for finding tx when they appear in a block
232 112 : if (vData.empty()) // zero-size = "match-all" filter
233 0 : return true;
234 112 : const uint256& hash = tx.GetHash();
235 112 : if (contains(hash))
236 13 : fFound = true;
237 :
238 : // Check additional matches for special transactions
239 112 : fFound = fFound || CheckSpecialTransactionMatchesAndUpdate(tx);
240 :
241 281 : for (unsigned int i = 0; i < tx.vout.size(); i++)
242 : {
243 169 : fFound = ProcessTxOut(tx.vout[i], hash, i) || fFound;
244 169 : }
245 :
246 112 : if (fFound)
247 47 : return true;
248 :
249 155 : for (const CTxIn& txin : tx.vin)
250 : {
251 : // Match if the filter contains an outpoint tx spends
252 96 : if (contains(txin.prevout))
253 4 : return true;
254 :
255 : // Match if the filter contains any arbitrary script data element in any scriptSig in tx
256 92 : if(CheckScript(txin.scriptSig))
257 2 : return true;
258 : }
259 :
260 59 : return false;
261 112 : }
262 :
263 76188 : CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
264 38094 : {
265 38094 : double logFpRate = log(fpRate);
266 : /* The optimal number of hash functions is log(fpRate) / log(0.5), but
267 : * restrict it to the range 1-50. */
268 38094 : nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
269 : /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
270 38094 : nEntriesPerGeneration = (nElements + 1) / 2;
271 38094 : uint32_t nMaxElements = nEntriesPerGeneration * 3;
272 : /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
273 : * => pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
274 : * => 1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
275 : * => log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
276 : * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
277 : * => nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
278 : */
279 38094 : uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
280 38094 : data.clear();
281 : /* For each data element we need to store 2 bits. If both bits are 0, the
282 : * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
283 : * treated as set in generation 1, 2, or 3 respectively.
284 : * These bits are stored in separate integers: position P corresponds to bit
285 : * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
286 38094 : data.resize(((nFilterBits + 63) / 64) << 1);
287 38094 : reset();
288 76188 : }
289 :
290 : /* Similar to CBloomFilter::Hash */
291 22237945 : static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, Span<const unsigned char> vDataToHash)
292 : {
293 22237945 : return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
294 : }
295 :
296 964317 : void CRollingBloomFilter::insert(Span<const unsigned char> vKey)
297 : {
298 964317 : if (nEntriesThisGeneration == nEntriesPerGeneration) {
299 43 : nEntriesThisGeneration = 0;
300 43 : nGeneration++;
301 43 : if (nGeneration == 4) {
302 11 : nGeneration = 1;
303 11 : }
304 43 : uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
305 43 : uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
306 : /* Wipe old entries that used this generation number. */
307 22056 : for (uint32_t p = 0; p < data.size(); p += 2) {
308 22013 : uint64_t p1 = data[p], p2 = data[p + 1];
309 22013 : uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
310 22013 : data[p] = p1 & mask;
311 22013 : data[p + 1] = p2 & mask;
312 22013 : }
313 43 : }
314 964317 : nEntriesThisGeneration++;
315 :
316 19818175 : for (int n = 0; n < nHashFuncs; n++) {
317 18853858 : uint32_t h = RollingBloomHash(n, nTweak, vKey);
318 18853858 : int bit = h & 0x3F;
319 : /* 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. */
320 18853858 : uint32_t pos = FastRange32(h, data.size());
321 : /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
322 18853858 : data[pos & ~1U] = (data[pos & ~1U] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration & 1)) << bit;
323 18853858 : data[pos | 1] = (data[pos | 1] & ~(uint64_t{1} << bit)) | (uint64_t(nGeneration >> 1)) << bit;
324 18853858 : }
325 964317 : }
326 :
327 882983 : bool CRollingBloomFilter::contains(Span<const unsigned char> vKey) const
328 : {
329 3517088 : for (int n = 0; n < nHashFuncs; n++) {
330 3384607 : uint32_t h = RollingBloomHash(n, nTweak, vKey);
331 3384607 : int bit = h & 0x3F;
332 3384607 : uint32_t pos = FastRange32(h, data.size());
333 : /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
334 3384607 : if (!(((data[pos & ~1U] | data[pos | 1]) >> bit) & 1)) {
335 750502 : return false;
336 : }
337 2634105 : }
338 132481 : return true;
339 882983 : }
340 :
341 55622 : void CRollingBloomFilter::reset()
342 : {
343 55622 : nTweak = GetRand<unsigned int>();
344 55622 : nEntriesThisGeneration = 0;
345 55622 : nGeneration = 1;
346 55622 : std::fill(data.begin(), data.end(), 0);
347 55622 : }
|