commonware_cryptography/
bloomfilter.rs

1//! An implementation of a [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter).
2
3use crate::{
4    sha256::{Digest, Sha256},
5    Hasher,
6};
7use bytes::{Buf, BufMut};
8use commonware_codec::{
9    codec::{Read, Write},
10    error::Error as CodecError,
11    EncodeSize, FixedSize,
12};
13use commonware_utils::bitmap::BitMap;
14use core::num::{NonZeroU64, NonZeroU8, NonZeroUsize};
15
16/// The length of a half of a [Digest].
17const HALF_DIGEST_LEN: usize = 16;
18
19/// The length of a full [Digest].
20const FULL_DIGEST_LEN: usize = Digest::SIZE;
21
22/// A [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter).
23///
24/// This implementation uses the Kirsch-Mitzenmacher optimization to derive `k` hash functions
25/// from two hash values, which are in turn derived from a single [Digest]. This provides
26/// efficient hashing for [BloomFilter::insert] and [BloomFilter::contains] operations.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct BloomFilter {
29    hashers: u8,
30    bits: BitMap,
31}
32
33impl BloomFilter {
34    /// Creates a new [BloomFilter] with `hashers` hash functions and `bits` bits.
35    pub fn new(hashers: NonZeroU8, bits: NonZeroUsize) -> Self {
36        Self {
37            hashers: hashers.get(),
38            bits: BitMap::zeroes(bits.get() as u64),
39        }
40    }
41
42    /// Generate `num_hashers` bit indices for a given item.
43    fn indices(&self, item: &[u8], bits: u64) -> impl Iterator<Item = u64> {
44        // Extract two 128-bit hash values from the SHA256 digest of the item
45        let digest = Sha256::hash(item);
46        let mut h1_bytes = [0u8; HALF_DIGEST_LEN];
47        h1_bytes.copy_from_slice(&digest[0..HALF_DIGEST_LEN]);
48        let h1 = u128::from_be_bytes(h1_bytes);
49        let mut h2_bytes = [0u8; HALF_DIGEST_LEN];
50        h2_bytes.copy_from_slice(&digest[HALF_DIGEST_LEN..FULL_DIGEST_LEN]);
51        let h2 = u128::from_be_bytes(h2_bytes);
52
53        // Generate `hashers` hashes using the Kirsch-Mitzenmacher optimization:
54        //
55        // `h_i(x) = (h1(x) + i * h2(x)) mod m`
56        let hashers = self.hashers as u128;
57        let bits = bits as u128;
58        (0..hashers)
59            .map(move |hasher| h1.wrapping_add(hasher.wrapping_mul(h2)) % bits)
60            .map(|index| index as u64)
61    }
62
63    /// Inserts an item into the [BloomFilter].
64    pub fn insert(&mut self, item: &[u8]) {
65        let indices = self.indices(item, self.bits.len());
66        for index in indices {
67            self.bits.set(index, true);
68        }
69    }
70
71    /// Checks if an item is possibly in the [BloomFilter].
72    ///
73    /// Returns `true` if the item is probably in the set, and `false` if it is definitely not.
74    pub fn contains(&self, item: &[u8]) -> bool {
75        let indices = self.indices(item, self.bits.len());
76        for index in indices {
77            if !self.bits.get(index) {
78                return false;
79            }
80        }
81        true
82    }
83}
84
85impl Write for BloomFilter {
86    fn write(&self, buf: &mut impl BufMut) {
87        self.hashers.write(buf);
88        self.bits.write(buf);
89    }
90}
91
92impl Read for BloomFilter {
93    // The number of hashers and the number of bits that the bitmap must have.
94    type Cfg = (NonZeroU8, NonZeroU64);
95
96    fn read_cfg(
97        buf: &mut impl Buf,
98        (hashers_cfg, bits_cfg): &Self::Cfg,
99    ) -> Result<Self, CodecError> {
100        let hashers = u8::read_cfg(buf, &())?;
101        if hashers != hashers_cfg.get() {
102            return Err(CodecError::Invalid(
103                "BloomFilter",
104                "hashers doesn't match config",
105            ));
106        }
107        let bits = BitMap::read_cfg(buf, &bits_cfg.get())?;
108        if bits.len() != bits_cfg.get() {
109            return Err(CodecError::Invalid(
110                "BloomFilter",
111                "bitmap length doesn't match config",
112            ));
113        }
114        Ok(Self { hashers, bits })
115    }
116}
117
118impl EncodeSize for BloomFilter {
119    fn encode_size(&self) -> usize {
120        self.hashers.encode_size() + self.bits.encode_size()
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use commonware_codec::{Decode, Encode};
128    use commonware_utils::{NZUsize, NZU64, NZU8};
129
130    #[test]
131    fn test_insert_and_contains() {
132        let mut bf = BloomFilter::new(NZU8!(10), NZUsize!(1000));
133        let item1 = b"hello";
134        let item2 = b"world";
135        let item3 = b"bloomfilter";
136
137        bf.insert(item1);
138        bf.insert(item2);
139
140        assert!(bf.contains(item1));
141        assert!(bf.contains(item2));
142        assert!(!bf.contains(item3));
143    }
144
145    #[test]
146    fn test_empty() {
147        let bf = BloomFilter::new(NZU8!(5), NZUsize!(100));
148        assert!(!bf.contains(b"anything"));
149    }
150
151    #[test]
152    fn test_false_positives() {
153        let mut bf = BloomFilter::new(NZU8!(10), NZUsize!(100));
154        for i in 0..10usize {
155            bf.insert(&i.to_be_bytes());
156        }
157
158        // Check for inserted items
159        for i in 0..10usize {
160            assert!(bf.contains(&i.to_be_bytes()));
161        }
162
163        // Check for non-inserted items and count false positives
164        let mut false_positives = 0;
165        for i in 100..1100usize {
166            if bf.contains(&i.to_be_bytes()) {
167                false_positives += 1;
168            }
169        }
170
171        // A small bloom filter with many items will have some false positives.
172        // The exact number is probabilistic, but it should not be zero and not all should be FPs.
173        assert!(false_positives > 0);
174        assert!(false_positives < 1000);
175    }
176
177    #[test]
178    fn test_codec_roundtrip() {
179        let mut bf = BloomFilter::new(NZU8!(5), NZUsize!(100));
180        bf.insert(b"test1");
181        bf.insert(b"test2");
182
183        let cfg = (NZU8!(5), NZU64!(100));
184
185        let encoded = bf.encode();
186        let decoded = BloomFilter::decode_cfg(encoded, &cfg).unwrap();
187
188        assert_eq!(bf, decoded);
189    }
190
191    #[test]
192    fn test_codec_empty() {
193        let bf = BloomFilter::new(NZU8!(4), NZUsize!(128));
194        let cfg = (NZU8!(4), NZU64!(128));
195        let encoded = bf.encode();
196        let decoded = BloomFilter::decode_cfg(encoded, &cfg).unwrap();
197        assert_eq!(bf, decoded);
198    }
199
200    #[test]
201    fn test_codec_with_invalid_hashers() {
202        let mut bf = BloomFilter::new(NZU8!(5), NZUsize!(100));
203        bf.insert(b"test1");
204        let encoded = bf.encode();
205
206        // Too large
207        let cfg = (NZU8!(10), NZU64!(100));
208        let decoded = BloomFilter::decode_cfg(encoded.clone(), &cfg);
209        assert!(matches!(
210            decoded,
211            Err(CodecError::Invalid(
212                "BloomFilter",
213                "hashers doesn't match config"
214            ))
215        ));
216
217        // Too small
218        let cfg = (NZU8!(4), NZU64!(100));
219        let decoded = BloomFilter::decode_cfg(encoded, &cfg);
220        assert!(matches!(
221            decoded,
222            Err(CodecError::Invalid(
223                "BloomFilter",
224                "hashers doesn't match config"
225            ))
226        ));
227    }
228
229    #[test]
230    fn test_codec_with_invalid_bits() {
231        let mut bf = BloomFilter::new(NZU8!(5), NZUsize!(100));
232        bf.insert(b"test1");
233        let encoded = bf.encode();
234
235        // Wrong bit count
236        let cfg = (NZU8!(5), NZU64!(99));
237        let result = BloomFilter::decode_cfg(encoded.clone(), &cfg);
238        assert!(matches!(result, Err(CodecError::InvalidLength(100))));
239
240        let cfg = (NZU8!(5), NZU64!(101));
241        let result = BloomFilter::decode_cfg(encoded, &cfg);
242        assert!(matches!(
243            result,
244            Err(CodecError::Invalid(
245                "BloomFilter",
246                "bitmap length doesn't match config"
247            ))
248        ));
249    }
250}