Browse Source

allow hash function generation from a given seed

Lennart Braun 3 years ago
parent
commit
e2d5d9d822
3 changed files with 29 additions and 2 deletions
  1. 1 0
      cuckoo/Cargo.toml
  2. 18 1
      cuckoo/src/cuckoo.rs
  3. 10 1
      cuckoo/src/hash.rs

+ 1 - 0
cuckoo/Cargo.toml

@@ -9,3 +9,4 @@ edition = "2021"
 aes = "0.8.1"
 libm = "0.2.5"
 rand = "0.8.5"
+rand_chacha = "0.3.1"

+ 18 - 1
cuckoo/src/cuckoo.rs

@@ -1,6 +1,8 @@
 use crate::hash::HashFunction;
 use core::array;
 use libm::erf;
+use rand::{Rng, SeedableRng};
+use rand_chacha::ChaCha12Rng;
 use std::f64::consts::SQRT_2;
 
 const NUMBER_HASH_FUNCTIONS: usize = 3;
@@ -13,7 +15,22 @@ pub struct Parameters<H: HashFunction> {
 }
 
 impl<H: HashFunction> Parameters<H> {
-    /// Samples three hash functions
+    /// Samples three hash functions from given seed
+    pub fn from_seed(number_inputs: usize, seed: [u8; 32]) -> Self {
+        let number_buckets = Self::compute_number_buckets(number_inputs);
+        let mut rng = ChaCha12Rng::from_seed(seed);
+        let hash_function_descriptions = array::from_fn(|_| {
+            H::from_seed(number_buckets.try_into().unwrap(), rng.gen()).to_description()
+        });
+
+        Parameters::<H> {
+            number_inputs,
+            number_buckets,
+            hash_function_descriptions,
+        }
+    }
+
+    /// Samples three hash functions randomly
     pub fn sample(number_inputs: usize) -> Self {
         let number_buckets = Self::compute_number_buckets(number_inputs);
         let hash_function_descriptions =

+ 10 - 1
cuckoo/src/hash.rs

@@ -13,9 +13,12 @@ pub trait HashFunction {
     // type Range;
     type Description: Copy + Debug;
 
-    /// Sample hash function.
+    /// Sample a random hash function.
     fn sample(range_size: u64) -> Self;
 
+    /// Sample a hash function using a given seed.
+    fn from_seed(range_size: u64, seed: [u8; 32]) -> Self;
+
     fn from_description(description: Self::Description) -> Self;
     fn to_description(&self) -> Self::Description;
 
@@ -71,6 +74,12 @@ impl HashFunction for AesHashFunction {
         self.description.range_size
     }
 
+    fn from_seed(range_size: u64, seed: [u8; 32]) -> Self {
+        let mut rng = ChaCha12Rng::from_seed(seed);
+        let key = rng.gen();
+        Self::from_description(AesHashFunctionDescription { range_size, key })
+    }
+
     fn sample(range_size: u64) -> Self {
         let key: [u8; 16] = thread_rng().gen();
         Self::from_description(AesHashFunctionDescription { range_size, key })