|
| 1 | +// Copyright (c) 2018 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 | +#ifndef BITCOIN_BLOCKFILTER_H |
| 6 | +#define BITCOIN_BLOCKFILTER_H |
| 7 | + |
| 8 | +#include <set> |
| 9 | +#include <stdint.h> |
| 10 | +#include <vector> |
| 11 | + |
| 12 | +#include <serialize.h> |
| 13 | +#include <uint256.h> |
| 14 | + |
| 15 | +/** |
| 16 | + * This implements a Golomb-coded set as defined in BIP 158. It is a |
| 17 | + * compact, probabilistic data structure for testing set membership. |
| 18 | + */ |
| 19 | +class GCSFilter |
| 20 | +{ |
| 21 | +public: |
| 22 | + typedef std::vector<unsigned char> Element; |
| 23 | + typedef std::set<Element> ElementSet; |
| 24 | + |
| 25 | +private: |
| 26 | + uint64_t m_siphash_k0; |
| 27 | + uint64_t m_siphash_k1; |
| 28 | + uint8_t m_P; //!< Golomb-Rice coding parameter |
| 29 | + uint32_t m_M; //!< Inverse false positive rate |
| 30 | + uint32_t m_N; //!< Number of elements in the filter |
| 31 | + uint64_t m_F; //!< Range of element hashes, F = N * M |
| 32 | + std::vector<unsigned char> m_encoded; |
| 33 | + |
| 34 | +public: |
| 35 | + |
| 36 | + /** Constructs an empty filter. */ |
| 37 | + GCSFilter(uint64_t siphash_k0 = 0, uint64_t siphash_k1 = 0, uint8_t P = 0, uint32_t M = 0); |
| 38 | + |
| 39 | + /** Reconstructs an already-created filter from an encoding. */ |
| 40 | + GCSFilter(uint64_t siphash_k0, uint64_t siphash_k1, uint8_t P, uint32_t M, |
| 41 | + std::vector<unsigned char> encoded_filter); |
| 42 | + |
| 43 | + /** Builds a new filter from the params and set of elements. */ |
| 44 | + GCSFilter(uint64_t siphash_k0, uint64_t siphash_k1, uint8_t P, uint32_t M, |
| 45 | + const ElementSet& elements); |
| 46 | + |
| 47 | + uint8_t GetP() const { return m_P; } |
| 48 | + uint32_t GetN() const { return m_N; } |
| 49 | + uint32_t GetM() const { return m_M; } |
| 50 | + const std::vector<unsigned char>& GetEncoded() const { return m_encoded; } |
| 51 | + |
| 52 | + /** |
| 53 | + * Checks if the element may be in the set. False positives are possible |
| 54 | + * with probability 1/M. |
| 55 | + */ |
| 56 | + bool Match(const Element& element) const; |
| 57 | + |
| 58 | + /** |
| 59 | + * Checks if any of the given elements may be in the set. False positives |
| 60 | + * are possible with probability 1/M per element checked. This is more |
| 61 | + * efficient that checking Match on multiple elements separately. |
| 62 | + */ |
| 63 | + bool MatchAny(const ElementSet& elements) const; |
| 64 | +}; |
| 65 | + |
| 66 | +#endif // BITCOIN_BLOCKFILTER_H |
0 commit comments