Debian Codegraph @

third_party/rust/rust_cascade/src/lib.rs

raw
1 //! # rust-cascade
2 //!
3 //! A library for creating and querying the cascading bloom filters described by
4 //! Larisch, Choffnes, Levin, Maggs, Mislove, and Wilson in
5 //! "CRLite: A Scalable System for Pushing All TLS Revocations to All Browsers"
6 //! <https://www.ieee-security.org/TC/SP2017/papers/567.pdf>
7
8 extern crate byteorder;
9 extern crate murmurhash3;
10 extern crate rand;
11 extern crate sha2;
12
13 use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
14 use murmurhash3::murmurhash3_x86_32;
15 #[cfg(feature = "builder")]
16 use rand::rngs::OsRng;
17 #[cfg(feature = "builder")]
18 use rand::RngCore;
19 use sha2::{Digest, Sha256};
20 use std::convert::{TryFrom, TryInto};
21 use std::fmt;
22 use std::io::{ErrorKind, Read};
23 use std::mem::size_of;
24
25 #[derive(Debug)]
26 pub enum CascadeError {
27 LongSalt,
28 TooManyLayers,
29 Collision,
30 UnknownHashFunction,
31 CapacityViolation(&'static str),
32 Parse(&'static str),
33 }
34
35 impl fmt::Display for CascadeError {
36 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 match *self {
38 CascadeError::LongSalt => {
39 write!(f, "Cannot serialize a filter with a salt of length >= 256.")
40 }
41 CascadeError::TooManyLayers => {
42 write!(f, "Cannot serialize a filter with >= 255 layers.")
43 }
44 CascadeError::Collision => {
45 write!(f, "Collision between included and excluded sets.")
46 }
47 CascadeError::UnknownHashFunction => {
48 write!(f, "Unknown hash function.")
49 }
50 CascadeError::CapacityViolation(function) => {
51 write!(f, "Unexpected call to {}", function)
52 }
53 CascadeError::Parse(reason) => {
54 write!(f, "Cannot parse cascade: {}", reason)
55 }
56 }
57 }
58 }
59
60 /// A Bloom filter representing a specific layer in a multi-layer cascading Bloom filter.
61 /// The same hash function is used for all layers, so it is not encoded here.
62 struct Bloom {
63 /// How many hash functions this filter uses
64 n_hash_funcs: u32,
65 /// The bit length of the filter
66 size: u32,
67 /// The data of the filter
68 data: Vec<u8>,
69 }
70
71 #[repr(u8)]
72 #[derive(Copy, Clone, PartialEq)]
73 /// These enumerations need to match the python filter-cascade project:
74 /// <https://github.com/mozilla/filter-cascade/blob/v0.3.0/filtercascade/fileformats.py>
75 pub enum HashAlgorithm {
76 MurmurHash3 = 1,
77 Sha256l32 = 2, // low 32 bits of sha256
78 Sha256 = 3, // all 256 bits of sha256
79 }
80
81 impl fmt::Display for HashAlgorithm {
82 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83 write!(f, "{}", *self as u8)
84 }
85 }
86
87 impl TryFrom<u8> for HashAlgorithm {
88 type Error = CascadeError;
89 fn try_from(value: u8) -> Result<HashAlgorithm, CascadeError> {
90 match value {
91 // Naturally, these need to match the enum declaration
92 1 => Ok(Self::MurmurHash3),
93 2 => Ok(Self::Sha256l32),
94 3 => Ok(Self::Sha256),
95 _ => Err(CascadeError::UnknownHashFunction),
96 }
97 }
98 }
99
100 /// A CascadeIndexGenerator provides one-time access to a table of pseudorandom functions H_ij
101 /// in which each function is of the form
102 /// H(s: &[u8], r: u32) -> usize
103 /// and for which 0 <= H(s,r) < r for all s, r.
104 /// The pseudorandom functions share a common key, represented as a octet string, and the table can
105 /// be constructed from this key alone. The functions are pseudorandom with respect to s, but not
106 /// r. For a uniformly random key/table, fixed r, and arbitrary strings m0 and m1,
107 /// H_ij(m0, r) is computationally indistinguishable from H_ij(m1,r)
108 /// for all i,j.
109 ///
110 /// A call to next_layer() increments i and resets j.
111 /// A call to next_index(s, r) increments j, and outputs some value H_ij(s) with 0 <= H_ij(s) < r.
112
113 #[derive(Debug)]
114 enum CascadeIndexGenerator {
115 MurmurHash3 {
116 key: Vec<u8>,
117 counter: u32,
118 depth: u8,
119 },
120 Sha256l32 {
121 key: Vec<u8>,
122 counter: u32,
123 depth: u8,
124 },
125 Sha256Ctr {
126 key: Vec<u8>,
127 counter: u32,
128 state: [u8; 32],
129 state_available: u8,
130 },
131 }
132
133 impl PartialEq for CascadeIndexGenerator {
134 fn eq(&self, other: &Self) -> bool {
135 match (self, other) {
136 (
137 CascadeIndexGenerator::MurmurHash3 { key: ref a, .. },
138 CascadeIndexGenerator::MurmurHash3 { key: ref b, .. },
139 )
140 | (
141 CascadeIndexGenerator::Sha256l32 { key: ref a, .. },
142 CascadeIndexGenerator::Sha256l32 { key: ref b, .. },
143 )
144 | (
145 CascadeIndexGenerator::Sha256Ctr { key: ref a, .. },
146 CascadeIndexGenerator::Sha256Ctr { key: ref b, .. },
147 ) => a == b,
148 _ => false,
149 }
150 }
151 }
152
153 impl CascadeIndexGenerator {
154 fn new(hash_alg: HashAlgorithm, key: Vec<u8>) -> Self {
155 match hash_alg {
156 HashAlgorithm::MurmurHash3 => Self::MurmurHash3 {
157 key,
158 counter: 0,
159 depth: 1,
160 },
161 HashAlgorithm::Sha256l32 => Self::Sha256l32 {
162 key,
163 counter: 0,
164 depth: 1,
165 },
166 HashAlgorithm::Sha256 => Self::Sha256Ctr {
167 key,
168 counter: 0,
169 state: [0; 32],
170 state_available: 0,
171 },
172 }
173 }
174
175 fn next_layer(&mut self) {
176 match self {
177 Self::MurmurHash3 {
178 ref mut counter,
179 ref mut depth,
180 ..
181 }
182 | Self::Sha256l32 {
183 ref mut counter,
184 ref mut depth,
185 ..
186 } => {
187 *counter = 0;
188 *depth += 1;
189 }
190 Self::Sha256Ctr { .. } => (),
191 }
192 }
193
194 fn next_index(&mut self, salt: &[u8], range: u32) -> usize {
195 let index = match self {
196 Self::MurmurHash3 {
197 key,
198 ref mut counter,
199 depth,
200 } => {
201 let hash_seed = (*counter << 16) + *depth as u32;
202 *counter += 1;
203 murmurhash3_x86_32(key, hash_seed)
204 }
205
206 Self::Sha256l32 {
207 key,
208 ref mut counter,
209 depth,
210 } => {
211 let mut hasher = Sha256::new();
212 hasher.update(salt);
213 hasher.update(counter.to_le_bytes());
214 hasher.update(depth.to_le_bytes());
215 hasher.update(&key);
216 *counter += 1;
217 u32::from_le_bytes(
218 hasher.finalize()[0..4]
219 .try_into()
220 .expect("sha256 should have given enough bytes"),
221 )
222 }
223
224 Self::Sha256Ctr {
225 key,
226 ref mut counter,
227 ref mut state,
228 ref mut state_available,
229 } => {
230 // |bytes_needed| is the minimum number of bytes needed to represent a value in [0, range).
231 let bytes_needed = ((range.next_power_of_two().trailing_zeros() + 7) / 8) as usize;
232 let mut index_arr = [0u8; 4];
233 for byte in index_arr.iter_mut().take(bytes_needed) {
234 if *state_available == 0 {
235 let mut hasher = Sha256::new();
236 hasher.update(counter.to_le_bytes());
237 hasher.update(salt);
238 hasher.update(&key);
239 hasher.finalize_into(state.into());
240 *state_available = state.len() as u8;
241 *counter += 1;
242 }
243 *byte = state[state.len() - *state_available as usize];
244 *state_available -= 1;
245 }
246 LittleEndian::read_u32(&index_arr)
247 }
248 };
249 (index % range) as usize
250 }
251 }
252
253 impl Bloom {
254 /// `new_crlite_bloom` creates an empty bloom filter for a layer of a cascade with the
255 /// parameters specified in [LCL+17, Section III.C].
256 ///
257 /// # Arguments
258 /// * `include_capacity` - the number of elements that will be encoded at the new layer.
259 /// * `exclude_capacity` - the number of elements in the complement of the encoded set.
260 /// * `top_layer` - whether this is the top layer of the filter.
261 #[cfg(feature = "builder")]
262 pub fn new_crlite_bloom(
263 include_capacity: usize,
264 exclude_capacity: usize,
265 top_layer: bool,
266 ) -> Self {
267 assert!(include_capacity != 0 && exclude_capacity != 0);
268
269 let r = include_capacity as f64;
270 let s = exclude_capacity as f64;
271
272 // The desired false positive rate for the top layer is
273 // p = r/(sqrt(2)*s).
274 // With this setting, the number of false positives (which will need to be
275 // encoded at the second layer) is expected to be a factor of sqrt(2)
276 // smaller than the number of elements encoded at the top layer.
277 //
278 // At layer i > 1 we try to ensure that the number of elements to be
279 // encoded at layer i+1 is half the number of elements encoded at
280 // layer i. So we take p = 1/2.
281 let log2_fp_rate = match top_layer {
282 true => (r / s).log2() - 0.5f64,
283 false => -1f64,
284 };
285
286 // the number of hash functions (k) and the size of the bloom filter (m) are given in
287 // [LCL+17] as k = log2(1/p) and m = r log2(1/p) / ln(2).
288 //
289 // If this formula gives a value of m < 256, we take m=256 instead. This results in very
290 // slightly sub-optimal size, but gives us the added benefit of doing less hashing.
291 let n_hash_funcs = (-log2_fp_rate).round() as u32;
292 let size = match (r * (-log2_fp_rate) / (f64::ln(2f64))).round() as u32 {
293 size if size >= 256 => size,
294 _ => 256,
295 };
296
297 Bloom {
298 n_hash_funcs,
299 size,
300 data: vec![0u8; ((size + 7) / 8) as usize],
301 }
302 }
303
304 /// `read` attempts to decode the Bloom filter represented by the bytes in the given reader.
305 ///
306 /// # Arguments
307 /// * `reader` - The encoded representation of this Bloom filter. May be empty. May include
308 /// additional data describing further Bloom filters.
309 /// The format of an encoded Bloom filter is:
310 /// [1 byte] - the hash algorithm to use in the filter
311 /// [4 little endian bytes] - the length in bits of the filter
312 /// [4 little endian bytes] - the number of hash functions to use in the filter
313 /// [1 byte] - which layer in the cascade this filter is
314 /// [variable length bytes] - the filter itself (must be of minimal length)
315 pub fn read<R: Read>(
316 reader: &mut R,
317 ) -> Result<Option<(Bloom, usize, HashAlgorithm)>, CascadeError> {
318 let hash_algorithm_val = match reader.read_u8() {
319 Ok(val) => val,
320 // If reader is at EOF, there is no bloom filter.
321 Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
322 Err(_) => return Err(CascadeError::Parse("read error")),
323 };
324 let hash_algorithm = HashAlgorithm::try_from(hash_algorithm_val)?;
325
326 let size = reader
327 .read_u32::<byteorder::LittleEndian>()
328 .or(Err(CascadeError::Parse("truncated at layer size")))?;
329 let n_hash_funcs = reader
330 .read_u32::<byteorder::LittleEndian>()
331 .or(Err(CascadeError::Parse("truncated at layer hash count")))?;
332 let layer = reader
333 .read_u8()
334 .or(Err(CascadeError::Parse("truncated at layer number")))?;
335
336 let byte_count = ((size + 7) / 8) as usize;
337 let mut data = vec![0; byte_count];
338 reader
339 .read_exact(&mut data)
340 .or(Err(CascadeError::Parse("truncated at layer data")))?;
341 let bloom = Bloom {
342 n_hash_funcs,
343 size,
344 data,
345 };
346 Ok(Some((bloom, layer as usize, hash_algorithm)))
347 }
348
349 fn has(&self, generator: &mut CascadeIndexGenerator, salt: &[u8]) -> bool {
350 for _ in 0..self.n_hash_funcs {
351 let bit_index = generator.next_index(salt, self.size);
352 assert!(bit_index < self.size as usize);
353 let byte_index = bit_index / 8;
354 let mask = 1 << (bit_index % 8);
355 if self.data[byte_index] & mask == 0 {
356 return false;
357 }
358 }
359 true
360 }
361
362 #[cfg(feature = "builder")]
363 fn insert(&mut self, generator: &mut CascadeIndexGenerator, salt: &[u8]) {
364 for _ in 0..self.n_hash_funcs {
365 let bit_index = generator.next_index(salt, self.size);
366 let byte_index = bit_index / 8;
367 let mask = 1 << (bit_index % 8);
368 self.data[byte_index] |= mask;
369 }
370 }
371
372 pub fn approximate_size_of(&self) -> usize {
373 size_of::<Bloom>() + self.data.len()
374 }
375 }
376
377 impl fmt::Display for Bloom {
378 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
379 write!(f, "n_hash_funcs={} size={}", self.n_hash_funcs, self.size)
380 }
381 }
382
383 /// A multi-layer cascading Bloom filter.
384 pub struct Cascade {
385 /// The Bloom filter for this layer in the cascade
386 filters: Vec<Bloom>,
387 /// The salt in use, if any
388 salt: Vec<u8>,
389 /// The hash algorithm / index generating function to use
390 hash_algorithm: HashAlgorithm,
391 /// Whether the logic should be inverted
392 inverted: bool,
393 }
394
395 impl Cascade {
396 /// from_bytes attempts to decode and return a multi-layer cascading Bloom filter.
397 ///
398 /// # Arguments
399 /// `bytes` - The encoded representation of the Bloom filters in this cascade. Starts with 2
400 /// little endian bytes indicating the version. The current version is 2. The Python
401 /// filter-cascade project defines the formats, see
402 /// <https://github.com/mozilla/filter-cascade/blob/v0.3.0/filtercascade/fileformats.py>
403 ///
404 /// May be of length 0, in which case `None` is returned.
405 pub fn from_bytes(bytes: Vec<u8>) -> Result<Option<Self>, CascadeError> {
406 if bytes.is_empty() {
407 return Ok(None);
408 }
409 let mut reader = bytes.as_slice();
410 let version = reader
411 .read_u16::<byteorder::LittleEndian>()
412 .or(Err(CascadeError::Parse("truncated at version")))?;
413
414 let mut filters = vec![];
415 let mut salt = vec![];
416 let mut top_hash_alg = None;
417 let mut inverted = false;
418
419 if version > 2 {
420 return Err(CascadeError::Parse("unknown version"));
421 }
422
423 if version == 2 {
424 let inverted_val = reader
425 .read_u8()
426 .or(Err(CascadeError::Parse("truncated at inverted")))?;
427 if inverted_val > 1 {
428 return Err(CascadeError::Parse("invalid value for inverted"));
429 }
430 inverted = 0 != inverted_val;
431 let salt_len: usize = reader
432 .read_u8()
433 .or(Err(CascadeError::Parse("truncated at salt length")))?
434 .into();
435 if salt_len >= 256 {
436 return Err(CascadeError::Parse("salt too long"));
437 }
438 if salt_len > 0 {
439 let mut salt_bytes = vec![0; salt_len];
440 reader
441 .read_exact(&mut salt_bytes)
442 .or(Err(CascadeError::Parse("truncated at salt")))?;
443 salt = salt_bytes;
444 }
445 }
446
447 while let Some((filter, layer_number, layer_hash_alg)) = Bloom::read(&mut reader)? {
448 filters.push(filter);
449
450 if layer_number != filters.len() {
451 return Err(CascadeError::Parse("irregular layer numbering"));
452 }
453
454 if *top_hash_alg.get_or_insert(layer_hash_alg) != layer_hash_alg {
455 return Err(CascadeError::Parse("Inconsistent hash algorithms"));
456 }
457 }
458
459 if filters.is_empty() {
460 return Err(CascadeError::Parse("missing filters"));
461 }
462
463 let hash_algorithm = top_hash_alg.ok_or(CascadeError::Parse("missing hash algorithm"))?;
464
465 Ok(Some(Cascade {
466 filters,
467 salt,
468 hash_algorithm,
469 inverted,
470 }))
471 }
472
473 /// to_bytes encodes a cascade in the version 2 format.
474 pub fn to_bytes(&self) -> Result<Vec<u8>, CascadeError> {
475 if self.salt.len() >= 256 {
476 return Err(CascadeError::LongSalt);
477 }
478 if self.filters.len() >= 255 {
479 return Err(CascadeError::TooManyLayers);
480 }
481 let mut out = vec![];
482 let version: u16 = 2;
483 let inverted: u8 = self.inverted.into();
484 let salt_len: u8 = self.salt.len() as u8;
485 let hash_alg: u8 = self.hash_algorithm as u8;
486 out.extend_from_slice(&version.to_le_bytes());
487 out.push(inverted);
488 out.push(salt_len);
489 out.extend_from_slice(&self.salt);
490 for (layer, bloom) in self.filters.iter().enumerate() {
491 out.push(hash_alg);
492 out.extend_from_slice(&bloom.size.to_le_bytes());
493 out.extend_from_slice(&bloom.n_hash_funcs.to_le_bytes());
494 out.push((1 + layer) as u8); // 1-indexed
495 out.extend_from_slice(&bloom.data);
496 }
497 Ok(out)
498 }
499
500 /// has determines if the given sequence of bytes is in the cascade.
501 ///
502 /// # Arguments
503 /// `entry` - The bytes to query
504 pub fn has(&self, entry: Vec<u8>) -> bool {
505 // Query filters 0..self.filters.len() until we get a non-membership result.
506 // If this occurs at an even index filter, the element *is not* included.
507 // ... at an odd-index filter, the element *is* included.
508 let mut generator = CascadeIndexGenerator::new(self.hash_algorithm, entry);
509 let mut rv = false;
510 for filter in &self.filters {
511 if filter.has(&mut generator, &self.salt) {
512 rv = !rv;
513 generator.next_layer();
514 } else {
515 break;
516 }
517 }
518 if self.inverted {
519 rv = !rv;
520 }
521 rv
522 }
523
524 pub fn invert(&mut self) {
525 self.inverted = !self.inverted;
526 }
527
528 /// Determine the approximate amount of memory in bytes used by this
529 /// Cascade. Because this implementation does not integrate with the
530 /// allocator, it can't get an accurate measurement of how much memory it
531 /// uses. However, it can make a reasonable guess, assuming the sizes of
532 /// the bloom filters are large enough to dominate the overall allocated
533 /// size.
534 pub fn approximate_size_of(&self) -> usize {
535 size_of::<Cascade>()
536 + self
537 .filters
538 .iter()
539 .map(|x| x.approximate_size_of())
540 .sum::<usize>()
541 + self.salt.len()
542 }
543 }
544
545 impl fmt::Display for Cascade {
546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
547 writeln!(
548 f,
549 "salt={:?} inverted={} hash_algorithm={}",
550 self.salt, self.inverted, self.hash_algorithm,
551 )?;
552 for filter in &self.filters {
553 writeln!(f, "\t[{}]", filter)?;
554 }
555 Ok(())
556 }
557 }
558
559 /// A CascadeBuilder creates a Cascade with layers given by `Bloom::new_crlite_bloom`.
560 ///
561 /// A builder is initialized using [`CascadeBuilder::default`] or [`CascadeBuilder::new`]. Prefer `default`. The `new` constructor
562 /// allows the user to specify sensitive internal details such as the hash function and the domain
563 /// separation parameter.
564 ///
565 /// Both constructors take `include_capacity` and an `exclude_capacity` parameters. The
566 /// `include_capacity` is the number of elements that will be encoded in the Cascade. The
567 /// `exclude_capacity` is size of the complement of the encoded set.
568 ///
569 /// The encoded set is specified through calls to [`CascadeBuilder::include`]. Its complement is specified through
570 /// calls to [`CascadeBuilder::exclude`]. The cascade is built with a call to [`CascadeBuilder::finalize`].
571 ///
572 /// The builder will track of the number of calls to `include` and `exclude`.
573 /// The caller is responsible for making *exactly* `include_capacity` calls to `include`
574 /// followed by *exactly* `exclude_capacity` calls to `exclude`.
575 /// Calling `exclude` before all `include` calls have been made will result in a panic!().
576 /// Calling `finalize` before all `exclude` calls have been made will result in a panic!().
577 ///
578 #[cfg(feature = "builder")]
579 pub struct CascadeBuilder {
580 filters: Vec<Bloom>,
581 salt: Vec<u8>,
582 hash_algorithm: HashAlgorithm,
583 to_include: Vec<CascadeIndexGenerator>,
584 to_exclude: Vec<CascadeIndexGenerator>,
585 status: BuildStatus,
586 }
587
588 #[cfg(feature = "builder")]
589 impl CascadeBuilder {
590 pub fn default(include_capacity: usize, exclude_capacity: usize) -> Self {
591 let mut salt = vec![0u8; 16];
592 OsRng.fill_bytes(&mut salt);
593 CascadeBuilder::new(
594 HashAlgorithm::Sha256,
595 salt,
596 include_capacity,
597 exclude_capacity,
598 )
599 }
600
601 pub fn new(
602 hash_algorithm: HashAlgorithm,
603 salt: Vec<u8>,
604 include_capacity: usize,
605 exclude_capacity: usize,
606 ) -> Self {
607 CascadeBuilder {
608 filters: vec![Bloom::new_crlite_bloom(
609 include_capacity,
610 exclude_capacity,
611 true,
612 )],
613 salt,
614 to_include: vec![],
615 to_exclude: vec![],
616 hash_algorithm,
617 status: BuildStatus(include_capacity, exclude_capacity),
618 }
619 }
620
621 pub fn include(&mut self, item: Vec<u8>) -> Result<(), CascadeError> {
622 match self.status {
623 BuildStatus(ref mut cap, _) if *cap > 0 => *cap -= 1,
624 _ => return Err(CascadeError::CapacityViolation("include")),
625 }
626 let mut generator = CascadeIndexGenerator::new(self.hash_algorithm, item);
627 self.filters[0].insert(&mut generator, &self.salt);
628 self.to_include.push(generator);
629
630 Ok(())
631 }
632
633 pub fn exclude(&mut self, item: Vec<u8>) -> Result<(), CascadeError> {
634 match self.status {
635 BuildStatus(0, ref mut cap) if *cap > 0 => *cap -= 1,
636 _ => return Err(CascadeError::CapacityViolation("exclude")),
637 }
638 let mut generator = CascadeIndexGenerator::new(self.hash_algorithm, item);
639 if self.filters[0].has(&mut generator, &self.salt) {
640 self.to_exclude.push(generator);
641 }
642 Ok(())
643 }
644
645 /// `exclude_threaded` is like `exclude` but it stores false positives in a caller-owned
646 /// `ExcludeSet`. This allows the caller to exclude items in parallel.
647 pub fn exclude_threaded(&self, exclude_set: &mut ExcludeSet, item: Vec<u8>) {
648 exclude_set.size += 1;
649 let mut generator = CascadeIndexGenerator::new(self.hash_algorithm, item);
650 if self.filters[0].has(&mut generator, &self.salt) {
651 exclude_set.set.push(generator);
652 }
653 }
654
655 /// `collect_exclude_set` merges an `ExcludeSet` into the internal storage of the CascadeBuilder.
656 pub fn collect_exclude_set(
657 &mut self,
658 exclude_set: &mut ExcludeSet,
659 ) -> Result<(), CascadeError> {
660 match self.status {
661 BuildStatus(0, ref mut cap) if *cap >= exclude_set.size => *cap -= exclude_set.size,
662 _ => return Err(CascadeError::CapacityViolation("exclude")),
663 }
664 self.to_exclude.append(&mut exclude_set.set);
665
666 Ok(())
667 }
668
669 fn push_layer(&mut self) -> Result<(), CascadeError> {
670 // At even layers we encode elements of to_include. At odd layers we encode elements of
671 // to_exclude. In both cases, we track false positives by filtering the complement of the
672 // encoded set through the newly produced bloom filter.
673 let at_even_layer = self.filters.len() % 2 == 0;
674 let (to_encode, to_filter) = match at_even_layer {
675 true => (&mut self.to_include, &mut self.to_exclude),
676 false => (&mut self.to_exclude, &mut self.to_include),
677 };
678
679 // split ownership of `salt` away from `to_encode` and `to_filter`
680 // We need an immutable reference to salt during `to_encode.iter_mut()`
681 let mut bloom = Bloom::new_crlite_bloom(to_encode.len(), to_filter.len(), false);
682
683 let salt = self.salt.as_slice();
684
685 to_encode.iter_mut().for_each(|x| {
686 x.next_layer();
687 bloom.insert(x, salt)
688 });
689
690 let mut delta = to_filter.len();
691 to_filter.retain_mut(|x| {
692 x.next_layer();
693 bloom.has(x, salt)
694 });
695 delta -= to_filter.len();
696
697 if delta == 0 {
698 // Check for collisions between the |to_encode| and |to_filter| sets.
699 // The implementation of PartialEq for CascadeIndexGenerator will successfully
700 // identify cases where the user called |include(item)| and |exclude(item)| for the
701 // same item. It will not identify collisions in the underlying hash function.
702 for x in to_encode.iter_mut() {
703 if to_filter.contains(x) {
704 return Err(CascadeError::Collision);
705 }
706 }
707 }
708
709 self.filters.push(bloom);
710 Ok(())
711 }
712
713 pub fn finalize(mut self) -> Result<Box<Cascade>, CascadeError> {
714 match self.status {
715 BuildStatus(0, 0) => (),
716 _ => return Err(CascadeError::CapacityViolation("finalize")),
717 }
718
719 loop {
720 if self.to_exclude.is_empty() {
721 break;
722 }
723 self.push_layer()?;
724
725 if self.to_include.is_empty() {
726 break;
727 }
728 self.push_layer()?;
729 }
730
731 Ok(Box::new(Cascade {
732 filters: self.filters,
733 salt: self.salt,
734 hash_algorithm: self.hash_algorithm,
735 inverted: false,
736 }))
737 }
738 }
739
740 /// BuildStatus is used to ensure that the `include`, `exclude`, and `finalize` calls to
741 /// CascadeBuilder are made in the right order. The (a,b) state indicates that the
742 /// CascadeBuilder is waiting for `a` calls to `include` and `b` calls to `exclude`.
743 #[cfg(feature = "builder")]
744 struct BuildStatus(usize, usize);
745
746 /// CascadeBuilder::exclude takes `&mut self` so that it can count exclusions and push items to
747 /// self.to_exclude. The bulk of the work it does, however, can be done with an immutable reference
748 /// to the top level bloom filter. An `ExcludeSet` is used by `CascadeBuilder::exclude_threaded` to
749 /// track the changes to a `CascadeBuilder` that would be made with a call to
750 /// `CascadeBuilder::exclude`.
751 #[cfg(feature = "builder")]
752 #[derive(Default)]
753 pub struct ExcludeSet {
754 size: usize,
755 set: Vec<CascadeIndexGenerator>,
756 }
757
758 #[cfg(test)]
759 mod tests {
760 use Bloom;
761 use Cascade;
762 #[cfg(feature = "builder")]
763 use CascadeBuilder;
764 #[cfg(feature = "builder")]
765 use CascadeError;
766 use CascadeIndexGenerator;
767 #[cfg(feature = "builder")]
768 use ExcludeSet;
769 use HashAlgorithm;
770
771 #[test]
772 fn bloom_v1_test_from_bytes() {
773 let src: Vec<u8> = vec![
774 0x01, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x41, 0x00,
775 ];
776 let mut reader = src.as_slice();
777
778 match Bloom::read(&mut reader) {
779 Ok(Some((bloom, 1, HashAlgorithm::MurmurHash3))) => {
780 assert!(bloom.has(
781 &mut CascadeIndexGenerator::new(HashAlgorithm::MurmurHash3, b"this".to_vec()),
782 &vec![]
783 ));
784 assert!(bloom.has(
785 &mut CascadeIndexGenerator::new(HashAlgorithm::MurmurHash3, b"that".to_vec()),
786 &vec![]
787 ));
788 assert!(!bloom.has(
789 &mut CascadeIndexGenerator::new(HashAlgorithm::MurmurHash3, b"other".to_vec()),
790 &vec![]
791 ));
792 }
793 Ok(_) => panic!("Parsing failed"),
794 Err(_) => panic!("Parsing failed"),
795 };
796 assert!(reader.is_empty());
797
798 let short: Vec<u8> = vec![
799 0x01, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x41,
800 ];
801 assert!(Bloom::read(&mut short.as_slice()).is_err());
802
803 let empty: Vec<u8> = Vec::new();
804 let mut reader = empty.as_slice();
805 match Bloom::read(&mut reader) {
806 Ok(should_be_none) => assert!(should_be_none.is_none()),
807 Err(_) => panic!("Parsing failed"),
808 };
809 }
810
811 #[test]
812 fn bloom_v3_unsupported() {
813 let src: Vec<u8> = vec![0x03, 0x01, 0x00];
814 assert!(Bloom::read(&mut src.as_slice()).is_err());
815 }
816
817 #[test]
818 fn cascade_v1_murmur_from_file_bytes_test() {
819 let v = include_bytes!("../test_data/test_v1_murmur_mlbf").to_vec();
820 let cascade = Cascade::from_bytes(v)
821 .expect("parsing Cascade should succeed")
822 .expect("Cascade should be Some");
823 // Key format is SHA256(issuer SPKI) + serial number
824 let key_for_revoked_cert_1 = vec![
825 0x2e, 0xb2, 0xd5, 0xa8, 0x60, 0xfe, 0x50, 0xe9, 0xc2, 0x42, 0x36, 0x85, 0x52, 0x98,
826 0x01, 0x50, 0xe4, 0x5d, 0xb5, 0x32, 0x1a, 0x5b, 0x00, 0x5e, 0x26, 0xd6, 0x76, 0x25,
827 0x3a, 0x40, 0x9b, 0xf5, 0x06, 0x2d, 0xf5, 0x68, 0xa0, 0x51, 0x31, 0x08, 0x20, 0xd7,
828 0xec, 0x43, 0x27, 0xe1, 0xba, 0xfd,
829 ];
830 assert!(cascade.has(key_for_revoked_cert_1));
831 let key_for_revoked_cert_2 = vec![
832 0xf1, 0x1c, 0x3d, 0xd0, 0x48, 0xf7, 0x4e, 0xdb, 0x7c, 0x45, 0x19, 0x2b, 0x83, 0xe5,
833 0x98, 0x0d, 0x2f, 0x67, 0xec, 0x84, 0xb4, 0xdd, 0xb9, 0x39, 0x6e, 0x33, 0xff, 0x51,
834 0x73, 0xed, 0x69, 0x8f, 0x00, 0xd2, 0xe8, 0xf6, 0xaa, 0x80, 0x48, 0x1c, 0xd4,
835 ];
836 assert!(cascade.has(key_for_revoked_cert_2));
837 let key_for_valid_cert = vec![
838 0x99, 0xfc, 0x9d, 0x40, 0xf1, 0xad, 0xb1, 0x63, 0x65, 0x61, 0xa6, 0x1d, 0x68, 0x3d,
839 0x9e, 0xa6, 0xb4, 0x60, 0xc5, 0x7d, 0x0c, 0x75, 0xea, 0x00, 0xc3, 0x41, 0xb9, 0xdf,
840 0xb9, 0x0b, 0x5f, 0x39, 0x0b, 0x77, 0x75, 0xf7, 0xaf, 0x9a, 0xe5, 0x42, 0x65, 0xc9,
841 0xcd, 0x32, 0x57, 0x10, 0x77, 0x8e,
842 ];
843 assert!(!cascade.has(key_for_valid_cert));
844
845 assert_eq!(cascade.approximate_size_of(), 15408);
846
847 let v = include_bytes!("../test_data/test_v1_murmur_short_mlbf").to_vec();
848 assert!(Cascade::from_bytes(v).is_err());
849 }
850
851 #[test]
852 fn cascade_v2_sha256l32_from_file_bytes_test() {
853 let v = include_bytes!("../test_data/test_v2_sha256l32_mlbf").to_vec();
854 let cascade = Cascade::from_bytes(v)
855 .expect("parsing Cascade should succeed")
856 .expect("Cascade should be Some");
857
858 assert!(cascade.salt.len() == 0);
859 assert!(cascade.inverted == false);
860 assert!(cascade.has(b"this".to_vec()) == true);
861 assert!(cascade.has(b"that".to_vec()) == true);
862 assert!(cascade.has(b"other".to_vec()) == false);
863 assert_eq!(cascade.approximate_size_of(), 1001);
864 }
865
866 #[test]
867 fn cascade_v2_sha256l32_with_salt_from_file_bytes_test() {
868 let v = include_bytes!("../test_data/test_v2_sha256l32_salt_mlbf").to_vec();
869 let cascade = Cascade::from_bytes(v)
870 .expect("parsing Cascade should succeed")
871 .expect("Cascade should be Some");
872
873 assert!(cascade.salt == b"nacl".to_vec());
874 assert!(cascade.inverted == false);
875 assert!(cascade.has(b"this".to_vec()) == true);
876 assert!(cascade.has(b"that".to_vec()) == true);
877 assert!(cascade.has(b"other".to_vec()) == false);
878 assert_eq!(cascade.approximate_size_of(), 1001);
879 }
880
881 #[test]
882 fn cascade_v2_murmur_from_file_bytes_test() {
883 let v = include_bytes!("../test_data/test_v2_murmur_mlbf").to_vec();
884 let cascade = Cascade::from_bytes(v)
885 .expect("parsing Cascade should succeed")
886 .expect("Cascade should be Some");
887
888 assert!(cascade.salt.len() == 0);
889 assert!(cascade.inverted == false);
890 assert!(cascade.has(b"this".to_vec()) == true);
891 assert!(cascade.has(b"that".to_vec()) == true);
892 assert!(cascade.has(b"other".to_vec()) == false);
893 assert_eq!(cascade.approximate_size_of(), 992);
894 }
895
896 #[test]
897 fn cascade_v2_murmur_inverted_from_file_bytes_test() {
898 let v = include_bytes!("../test_data/test_v2_murmur_inverted_mlbf").to_vec();
899 let cascade = Cascade::from_bytes(v)
900 .expect("parsing Cascade should succeed")
901 .expect("Cascade should be Some");
902
903 assert!(cascade.salt.len() == 0);
904 assert!(cascade.inverted == true);
905 assert!(cascade.has(b"this".to_vec()) == true);
906 assert!(cascade.has(b"that".to_vec()) == true);
907 assert!(cascade.has(b"other".to_vec()) == false);
908 assert_eq!(cascade.approximate_size_of(), 1058);
909 }
910
911 #[test]
912 fn cascade_v2_sha256l32_inverted_from_file_bytes_test() {
913 let v = include_bytes!("../test_data/test_v2_sha256l32_inverted_mlbf").to_vec();
914 let cascade = Cascade::from_bytes(v)
915 .expect("parsing Cascade should succeed")
916 .expect("Cascade should be Some");
917
918 assert!(cascade.salt.len() == 0);
919 assert!(cascade.inverted == true);
920 assert!(cascade.has(b"this".to_vec()) == true);
921 assert!(cascade.has(b"that".to_vec()) == true);
922 assert!(cascade.has(b"other".to_vec()) == false);
923 assert_eq!(cascade.approximate_size_of(), 1061);
924 }
925
926 #[test]
927 fn cascade_v2_sha256ctr_from_file_bytes_test() {
928 let v = include_bytes!("../test_data/test_v2_sha256ctr_salt_mlbf").to_vec();
929 let cascade = Cascade::from_bytes(v)
930 .expect("parsing Cascade should succeed")
931 .expect("Cascade should be Some");
932
933 assert!(cascade.salt == b"nacl".to_vec());
934 assert!(cascade.inverted == false);
935 assert!(cascade.has(b"this".to_vec()) == true);
936 assert!(cascade.has(b"that".to_vec()) == true);
937 assert!(cascade.has(b"other".to_vec()) == false);
938 assert_eq!(cascade.approximate_size_of(), 1070);
939 }
940
941 #[test]
942 fn cascade_empty() {
943 let cascade = Cascade::from_bytes(Vec::new()).expect("parsing Cascade should succeed");
944 assert!(cascade.is_none());
945 }
946
947 #[test]
948 fn cascade_test_from_bytes() {
949 let unknown_version: Vec<u8> = vec![0xff, 0xff, 0x00, 0x00];
950 match Cascade::from_bytes(unknown_version) {
951 Ok(_) => panic!("Cascade::from_bytes allows unknown version."),
952 Err(_) => (),
953 }
954
955 let first_layer_is_zero: Vec<u8> = vec![
956 0x01, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
957 ];
958 match Cascade::from_bytes(first_layer_is_zero) {
959 Ok(_) => panic!("Cascade::from_bytes allows zero indexed layers."),
960 Err(_) => (),
961 }
962
963 let second_layer_is_three: Vec<u8> = vec![
964 0x01, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,
965 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00,
966 ];
967 match Cascade::from_bytes(second_layer_is_three) {
968 Ok(_) => panic!("Cascade::from_bytes allows non-sequential layers."),
969 Err(_) => (),
970 }
971 }
972
973 #[test]
974 #[cfg(feature = "builder")]
975 fn cascade_builder_test_collision() {
976 let mut builder = CascadeBuilder::default(1, 1);
977 builder.include(b"collision!".to_vec()).ok();
978 builder.exclude(b"collision!".to_vec()).ok();
979 assert!(matches!(builder.finalize(), Err(CascadeError::Collision)));
980 }
981
982 #[test]
983 #[cfg(feature = "builder")]
984 fn cascade_builder_test_exclude_too_few() {
985 let mut builder = CascadeBuilder::default(1, 1);
986 builder.include(b"1".to_vec()).ok();
987 assert!(matches!(
988 builder.finalize(),
989 Err(CascadeError::CapacityViolation(_))
990 ));
991 }
992
993 #[test]
994 #[cfg(feature = "builder")]
995 fn cascade_builder_test_include_too_few() {
996 let mut builder = CascadeBuilder::default(1, 1);
997 assert!(matches!(
998 builder.exclude(b"1".to_vec()),
999 Err(CascadeError::CapacityViolation(_))
1000 ));
1001 }
1002
1003 #[test]
1004 #[cfg(feature = "builder")]
1005 fn cascade_builder_test_include_too_many() {
1006 let mut builder = CascadeBuilder::default(1, 1);
1007 builder.include(b"1".to_vec()).ok();
1008 assert!(matches!(
1009 builder.include(b"2".to_vec()),
1010 Err(CascadeError::CapacityViolation(_))
1011 ));
1012 }
1013
1014 #[test]
1015 #[cfg(feature = "builder")]
1016 fn cascade_builder_test_exclude_too_many() {
1017 let mut builder = CascadeBuilder::default(1, 1);
1018 builder.include(b"1".to_vec()).ok();
1019 builder.exclude(b"2".to_vec()).ok();
1020 assert!(matches!(
1021 builder.exclude(b"3".to_vec()),
1022 Err(CascadeError::CapacityViolation(_))
1023 ));
1024 }
1025
1026 #[test]
1027 #[cfg(feature = "builder")]
1028 fn cascade_builder_test_exclude_threaded_no_collect() {
1029 let mut builder = CascadeBuilder::default(1, 3);
1030 let mut exclude_set = ExcludeSet::default();
1031 builder.include(b"1".to_vec()).ok();
1032 builder.exclude_threaded(&mut exclude_set, b"2".to_vec());
1033 builder.exclude_threaded(&mut exclude_set, b"3".to_vec());
1034 builder.exclude_threaded(&mut exclude_set, b"4".to_vec());
1035 assert!(matches!(
1036 builder.finalize(),
1037 Err(CascadeError::CapacityViolation(_))
1038 ));
1039 }
1040
1041 #[test]
1042 #[cfg(feature = "builder")]
1043 fn cascade_builder_test_exclude_threaded_too_many() {
1044 let mut builder = CascadeBuilder::default(1, 3);
1045 let mut exclude_set = ExcludeSet::default();
1046 builder.include(b"1".to_vec()).ok();
1047 builder.exclude_threaded(&mut exclude_set, b"2".to_vec());
1048 builder.exclude_threaded(&mut exclude_set, b"3".to_vec());
1049 builder.exclude_threaded(&mut exclude_set, b"4".to_vec());
1050 builder.exclude_threaded(&mut exclude_set, b"5".to_vec());
1051 assert!(matches!(
1052 builder.collect_exclude_set(&mut exclude_set),
1053 Err(CascadeError::CapacityViolation(_))
1054 ));
1055 }
1056
1057 #[test]
1058 #[cfg(feature = "builder")]
1059 fn cascade_builder_test_exclude_threaded() {
1060 let mut builder = CascadeBuilder::default(1, 3);
1061 let mut exclude_set = ExcludeSet::default();
1062 builder.include(b"1".to_vec()).ok();
1063 builder.exclude_threaded(&mut exclude_set, b"2".to_vec());
1064 builder.exclude_threaded(&mut exclude_set, b"3".to_vec());
1065 builder.exclude_threaded(&mut exclude_set, b"4".to_vec());
1066 builder.collect_exclude_set(&mut exclude_set).ok();
1067 builder.finalize().ok();
1068 }
1069
1070 #[cfg(feature = "builder")]
1071 fn cascade_builder_test_generate(hash_alg: HashAlgorithm, inverted: bool) {
1072 let total = 10_000_usize;
1073 let included = 100_usize;
1074
1075 let salt = vec![0u8; 16];
1076 let mut builder =
1077 CascadeBuilder::new(hash_alg, salt, included, (total - included) as usize);
1078 for i in 0..included {
1079 builder.include(i.to_le_bytes().to_vec()).ok();
1080 }
1081 for i in included..total {
1082 builder.exclude(i.to_le_bytes().to_vec()).ok();
1083 }
1084 let mut cascade = builder.finalize().unwrap();
1085
1086 if inverted {
1087 cascade.invert()
1088 }
1089
1090 // Ensure we can serialize / deserialize
1091 let cascade_bytes = cascade.to_bytes().expect("failed to serialize cascade");
1092
1093 let cascade = Cascade::from_bytes(cascade_bytes)
1094 .expect("failed to deserialize cascade")
1095 .expect("cascade should not be None here");
1096
1097 // Ensure each query gives the correct result
1098 for i in 0..included {
1099 assert!(cascade.has(i.to_le_bytes().to_vec()) == true ^ inverted)
1100 }
1101 for i in included..total {
1102 assert!(cascade.has(i.to_le_bytes().to_vec()) == false ^ inverted)
1103 }
1104 }
1105
1106 #[test]
1107 #[cfg(feature = "builder")]
1108 fn cascade_builder_test_generate_murmurhash3_inverted() {
1109 cascade_builder_test_generate(HashAlgorithm::MurmurHash3, true);
1110 }
1111
1112 #[test]
1113 #[cfg(feature = "builder")]
1114 fn cascade_builder_test_generate_murmurhash3() {
1115 cascade_builder_test_generate(HashAlgorithm::MurmurHash3, false);
1116 }
1117
1118 #[test]
1119 #[cfg(feature = "builder")]
1120 fn cascade_builder_test_generate_sha256l32() {
1121 cascade_builder_test_generate(HashAlgorithm::Sha256l32, false);
1122 }
1123
1124 #[test]
1125 #[cfg(feature = "builder")]
1126 fn cascade_builder_test_generate_sha256() {
1127 cascade_builder_test_generate(HashAlgorithm::Sha256, false);
1128 }
1129 }