Skip to main content

rapidhash/v1/
seed.rs

1//! Reliable seeding and secrets generation for the hash functions.
2
3use crate::util::mix::rapid_mix;
4
5/// The default seed used in the C++ implementation.
6pub(crate) const DEFAULT_SEED: u64 = 0xbdd89aa982704029;
7
8/// Used only for generating random secrets.
9const DEFAULT_SECRETS: [u64; 3] = [
10    0x2d358dccaa6c78a5,
11    0x8bb84b93962eacc9,
12    0x4b33a62ed433d4a3,
13];
14
15/// The default rapidhash secrets used in the C++ implementation.
16///
17/// We recommend generating your own secrets using the [`crate::v3::RapidSecrets::seed`] method to avoid
18/// trivial collision attacks if you need minimal HashDoS protection.
19pub const DEFAULT_RAPID_SECRETS: RapidSecrets = RapidSecrets::seed_cpp(DEFAULT_SEED);
20
21/// Hold the seed and secrets to be used by rapidhash.
22///
23/// RapidSecrets premix the seed and generate a set of other secrets based on the seed that are all
24/// used in the hashing process. There are some quality checks on the random values to ensure a
25/// reasonable distribution of entropy in the generated secrets.
26///
27/// Constructing this struct is fairly cheap, but unnecessary in the critical path. We therefore
28/// recommend instantiating it once and re-using the same instance for any persistent hashing. The
29/// `seed` method is marked `const` to also do so at compile time.
30///
31/// # Minimal HashDoS Protection
32/// We recommend changing the default seed and secrets to avoid
33/// [trivial collision attacks](https://liams.website/articles/seed-independent-collisions-on-wyhash-and-rapidhash).
34/// For persistent hashing, you can hard code your own randomized seed at compile time.
35///
36/// ```rust
37/// use rapidhash::v1::RapidSecrets;
38/// const DEFAULT_SECRETS: RapidSecrets = RapidSecrets::seed(0x123456);  // <-- change this value!
39///
40/// /// Export your chosen rapidhash version and secrets for use throughout your project.
41/// pub fn rapidhash(data: &[u8]) -> u64 {
42///     rapidhash::v1::rapidhash_v1_seeded(data, &DEFAULT_SECRETS)
43/// }
44/// ```
45///
46/// TODO: serde or serialization support.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub struct RapidSecrets {
49    /// The core rapidhash seed.
50    pub seed: u64,
51
52    /// The secrets, effectively other seeds used in the hashing process.
53    pub secrets: [u64; 3],
54}
55
56impl RapidSecrets {
57    /// Generate secrets from a given randomized seed.
58    ///
59    /// Note the chosen seed will be pre-mixed to further randomized it, and the secrets will be
60    /// computed based on the seed.
61    ///
62    /// If compatibility with the C++ implementation is required, use the `seed_cpp` method instead.
63    #[inline]
64    pub const fn seed(seed: u64) -> Self {
65        let seed = premix_seed(seed, 0);
66        let mut secrets = [0; 3];
67        secrets[0] = premix_seed(seed, 0);
68        secrets[1] = premix_seed(secrets[0], 1);
69        secrets[2] = premix_seed(secrets[1], 2);
70        Self { seed, secrets }
71    }
72
73    /// Creates a new `RapidSecrets` instance with a different seed and the same secrets.
74    ///
75    /// This is useful for in-memory hashing, so we can quickly use a different seed for other
76    /// HashMaps.
77    #[inline(always)]
78    pub const fn reseed(&self) -> Self {
79        Self {
80            seed: premix_seed(self.seed, 6),
81            secrets: self.secrets,
82        }
83    }
84
85    /// Creates a new `RapidSecrets` instance using a seed and secrets that are compatible with the
86    /// C++ implementation.
87    ///
88    /// Note that these **use the default secrets** and therefore are liable to some trivial
89    /// collision attacks, as randomising both the seed and secrets is necessary to provide minimal
90    /// HashDoS resistance.
91    #[inline(always)]
92    pub const fn seed_cpp(seed: u64) -> Self {
93        Self {
94            seed: rapidhash_seed(seed),
95            secrets: DEFAULT_SECRETS,
96        }
97    }
98}
99
100#[inline(always)]
101const fn rapidhash_seed(seed: u64) -> u64 {
102    seed ^ rapid_mix::<false>(seed ^ DEFAULT_SECRETS[0], DEFAULT_SECRETS[1])
103}
104
105#[inline]
106const fn premix_seed(mut seed: u64, i: usize) -> u64 {
107    seed ^= rapid_mix::<false>(seed ^ DEFAULT_SECRETS[2], DEFAULT_SECRETS[i]);
108
109    // ensure the seeds are of reasonable non-zero quality
110    const HI: u64 = 0xFFFF << 48;
111    const MI: u64 = 0xFFFF << 24;
112    const LO: u64 = 0xFFFF;
113
114    if (seed & HI) == 0 {
115        seed |= 1u64 << 63;
116    }
117
118    if (seed & MI) == 0 {
119        seed |= 1u64 << 31;
120    }
121
122    if (seed & LO) == 0 {
123        seed |= 1u64;
124    }
125
126    seed
127}