cat_gateway/utils/
blake2b_hash.rs

1//! Types of Blake-2b Hash
2
3use blake2b_simd::Params;
4
5/// Generates a UUID string from the provided key and data using `BLAKE2b` hashing.
6///
7/// # Arguments
8/// - `key`: A string slice that is used as part of the hash function input.
9/// - `data`: A vector of strings which will be included in the `BLAKE2b` hash
10///   computation.
11///
12/// # Returns
13/// A UUID string generated from the `BLAKE2b` hash of the concatenated data with the key.
14pub(crate) fn generate_uuid_string_from_data(
15    key: &str,
16    data: &[String],
17) -> String {
18    // Where we will actually store the bytes we derive the UUID from.
19    let mut bytes: uuid::Bytes = uuid::Bytes::default();
20
21    // Generate a unique hash of the data.
22    let mut hasher = Params::new()
23        .hash_length(bytes.len())
24        .key(key.as_bytes())
25        .personal(b"Project Catalyst")
26        .to_state();
27
28    for datum in data {
29        hasher.update(datum.as_bytes());
30    }
31
32    // Finalize the hash and get the digest as a byte array
33    let hash = hasher.finalize();
34
35    // Create a new array containing the first 16 elements from the original array
36    bytes.copy_from_slice(hash.as_bytes());
37
38    // Convert the hash to a UUID
39    uuid::Builder::from_custom_bytes(bytes)
40        .as_uuid()
41        .as_hyphenated()
42        .to_string()
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_generate_uuid_string_from_data() {
51        let key = "test key";
52        let data = vec!["test1".to_string(), "test2".to_string()];
53
54        // Call the function under test
55        let uuid_str = generate_uuid_string_from_data(key, &data);
56
57        // Verify that the output is a valid UUID string
58        assert!(uuid::Uuid::parse_str(&uuid_str).is_ok());
59    }
60
61    #[test]
62    fn test_generate_uuid_string_from_data_empty_data() {
63        let key = "test key";
64        let data: Vec<String> = vec![];
65
66        // Call the function under test
67        let uuid_str = generate_uuid_string_from_data(key, &data);
68
69        // Verify that the output is a valid UUID string
70        assert!(uuid::Uuid::parse_str(&uuid_str).is_ok());
71    }
72
73    #[test]
74    fn test_generate_uuid_string_from_data_empty_key() {
75        let key = "";
76        let data = vec!["test1".to_string(), "test2".to_string()];
77
78        // Call the function under test
79        let uuid_str = generate_uuid_string_from_data(key, &data);
80
81        // Verify that the output is a valid UUID string
82        assert!(uuid::Uuid::parse_str(&uuid_str).is_ok());
83    }
84}