Skip to main content

dope_runtime/random/
mod.rs

1//! Runtime-owned randomness bound to one exact generative driver domain.
2
3use std::{hash, marker, mem};
4
5use dope_core::{driver, driver::schedule::sequence, random::Seed};
6use o3::base::marker::ThreadBound;
7
8mod sip;
9
10pub(crate) use sip::Sip;
11
12type SipHasher24 = Sip<2, 4>;
13
14/// Owned hashing state that remains confined to its creating thread.
15pub type OwnedHasher = Sip<1, 3>;
16
17pub(crate) fn derive_seed(seed: &Seed, domain: Domain) -> Seed {
18    seed.map(|words| Key::new(words).derive(domain, ()).into_words())
19}
20
21type Invariant<'d> = marker::PhantomData<(fn(&'d ()) -> &'d (), ThreadBound)>;
22
23/// Owned, thread-bound hash key derived from already acquired seed material.
24/// Clones retain the same hash namespace without acquiring OS entropy or a
25/// driver capability.
26#[derive(Clone)]
27pub struct HashSeed {
28    state: (Key, ThreadBound),
29}
30
31impl HashSeed {
32    pub fn from_seed(seed: &Seed, domain: Domain) -> Self {
33        Self {
34            state: (
35                Key::new(*seed.as_ref()).derive(domain, ()),
36                ThreadBound::NEW,
37            ),
38        }
39    }
40
41    pub fn hash<T: hash::Hash + ?Sized>(&self, input: &T) -> u64 {
42        let mut state = self.state.0.hasher(());
43        input.hash(&mut state);
44        hash::Hasher::finish(&state)
45    }
46
47    /// Hashes one complete byte string without `Hash` framing.
48    pub fn hash_bytes(&self, input: &[u8]) -> u64 {
49        self.state.0.hasher(()).hash(input)
50    }
51}
52
53impl hash::BuildHasher for HashSeed {
54    type Hasher = OwnedHasher;
55
56    fn build_hasher(&self) -> Self::Hasher {
57        self.state.0.hasher(())
58    }
59}
60
61/// Keyed hash builder issued for one exact generative driver domain.
62///
63/// The driver lifetime is invariant and cannot be widened. Building a hasher
64/// preserves the same invariant driver lifetime.
65pub struct HashState<'d> {
66    state: (Key, Invariant<'d>),
67}
68
69impl<'d> HashState<'d> {
70    pub(crate) fn for_seed(seed: &Seed, domain: Domain) -> Self {
71        Self {
72            state: (
73                Key::new(*seed.as_ref()).derive(domain, ()),
74                marker::PhantomData,
75            ),
76        }
77    }
78}
79
80impl<'d> hash::BuildHasher for HashState<'d> {
81    type Hasher = Hasher<'d>;
82
83    fn build_hasher(&self) -> Self::Hasher {
84        self.state.0.hasher(sip::Branded(self.state.1))
85    }
86}
87
88/// Hashing state retaining the exact driver brand of its key source.
89pub type Hasher<'d> = Sip<1, 3, sip::Branded<'d>>;
90
91/// Compile-time purpose separating random roots without runtime state.
92/// Implementations use a stable, globally distinct domain.
93pub trait Purpose {
94    const DOMAIN: Domain;
95}
96
97/// Keyed words and permutations supplied by a purpose-bound random owner.
98/// Word generation and permutation rounds occupy separate domains even when
99/// their compile-time lane is the same.
100pub trait Entropy<P: Purpose> {
101    fn word<const LANE: u64>(&self, input: u64) -> Word<P, LANE>;
102    fn permute<const LANE: u64>(&self, value: u64) -> Word<P, LANE>;
103
104    /// Derives an independent owned hash key, without exporting the root or its
105    /// driver capability. Hash keys occupy a separate domain from public words
106    /// and permutations, including when their compile-time lane is the same.
107    fn hash_seed<const LANE: u64>(&self) -> HashSeed;
108}
109
110type RootState<'d, P> = (Key, Invariant<'d>, marker::PhantomData<fn(P) -> P>);
111type ProcessState<P> = (Key, marker::PhantomData<(fn(P) -> P, ThreadBound)>);
112
113/// Non-cloneable secret root bound invariantly to one driver domain.
114/// Protocol authorities retain it for that lifetime and use compile-time lanes
115/// to separate streams; storage is exactly the two secret key words.
116pub struct Root<'d, P: Purpose> {
117    state: RootState<'d, P>,
118}
119
120impl<'d, P: Purpose> Root<'d, P> {
121    const fn new(seed: Key) -> Self {
122        Self {
123            state: (seed, marker::PhantomData, marker::PhantomData),
124        }
125    }
126
127    /// Hashes a typed identity in a compile-time lane without materializing an
128    /// intermediate byte representation.
129    pub fn hash<const LANE: u64, T: hash::Hash + ?Sized>(&self, input: &T) -> Word<P, LANE> {
130        self.state.0.hash::<P, LANE, T>(input)
131    }
132}
133
134/// Non-cloneable process-owned secret root without a fabricated owner lifetime.
135pub struct Process<P: Purpose> {
136    state: ProcessState<P>,
137}
138
139impl<P: Purpose> Process<P> {
140    pub fn random() -> Result<Self, dope_core::Errno> {
141        let seed = Key::new(*Seed::acquire()?.as_ref()).derive(P::DOMAIN, ());
142        Ok(Self {
143            state: (seed, marker::PhantomData),
144        })
145    }
146}
147
148impl<P: Purpose> Entropy<P> for Root<'_, P> {
149    fn word<const LANE: u64>(&self, input: u64) -> Word<P, LANE> {
150        self.state.0.hash::<P, LANE, _>(&input)
151    }
152
153    fn permute<const LANE: u64>(&self, value: u64) -> Word<P, LANE> {
154        self.state.0.permute::<P, LANE>(value)
155    }
156
157    fn hash_seed<const LANE: u64>(&self) -> HashSeed {
158        self.state.0.hash_seed::<LANE>()
159    }
160}
161
162impl<P: Purpose> Entropy<P> for Process<P> {
163    fn word<const LANE: u64>(&self, input: u64) -> Word<P, LANE> {
164        self.state.0.hash::<P, LANE, _>(&input)
165    }
166
167    fn permute<const LANE: u64>(&self, value: u64) -> Word<P, LANE> {
168        self.state.0.permute::<P, LANE>(value)
169    }
170
171    fn hash_seed<const LANE: u64>(&self) -> HashSeed {
172        self.state.0.hash_seed::<LANE>()
173    }
174}
175
176impl<'d, P: Purpose> Root<'d, P> {
177    /// Consumes a fresh identity from the driver before deriving a purpose root.
178    /// Repeated acquisition never reuses the same derivation input.
179    pub fn try_acquire(driver: &driver::Context<'_, 'd>) -> Result<Self, sequence::Exhausted> {
180        let driver = driver.driver_ref();
181        let instance = driver.try_next_id()?;
182        let seed = Key::new(*driver.random_seed().as_ref());
183        Ok(Self::new(seed.derive(P::DOMAIN, instance)))
184    }
185}
186
187const _: () = assert!(mem::size_of::<HashState<'static>>() == 2 * mem::size_of::<u64>());
188const _: () = assert!(mem::size_of::<HashSeed>() == 2 * mem::size_of::<u64>());
189const _: () = assert!(mem::size_of::<OwnedHasher>() == mem::size_of::<(usize, [u64; 5])>());
190const _: () = assert!(mem::size_of::<Hasher<'static>>() == mem::size_of::<OwnedHasher>());
191
192/// Secret key retained by one runtime authority.
193#[repr(transparent)]
194#[derive(Clone)]
195struct Key([u64; 2]);
196
197impl Key {
198    const fn new(words: [u64; 2]) -> Self {
199        Self(words)
200    }
201
202    const fn into_words(self) -> [u64; 2] {
203        self.0
204    }
205
206    fn derive(&self, domain: Domain, instance: impl hash::Hash) -> Self {
207        let mut state = self.prefix(domain);
208        instance.hash(&mut state);
209        Self::from_hasher(state)
210    }
211
212    fn from_hasher(state: SipHasher24) -> Self {
213        Self([0, 1].map(|word| {
214            let mut state = state;
215            hash::Hasher::write_u64(&mut state, word);
216            hash::Hasher::finish(&state)
217        }))
218    }
219
220    fn hasher<P>(&self, proof: P) -> Sip<1, 3, P> {
221        Sip::new(self.0[0], self.0[1], proof)
222    }
223
224    fn hash_seed<const LANE: u64>(&self) -> HashSeed {
225        HashSeed {
226            state: (Self::from_hasher(self.lane::<LANE>(2)), ThreadBound::NEW),
227        }
228    }
229
230    fn hash<P, const LANE: u64, T: hash::Hash + ?Sized>(&self, input: &T) -> Word<P, LANE> {
231        let mut state = self.lane::<LANE>(0);
232        input.hash(&mut state);
233        Word::new(hash::Hasher::finish(&state))
234    }
235
236    fn permute<P, const LANE: u64>(&self, value: u64) -> Word<P, LANE> {
237        let state = self.lane::<LANE>(1);
238        let mut left = (value >> 32) as u32;
239        let mut right = value as u32;
240        let mut round = 0;
241        while round < 4 {
242            let input = ((round as u64) << 32) | u64::from(right);
243            let mut hash = state;
244            hash::Hasher::write_u64(&mut hash, input);
245            let next = left ^ hash::Hasher::finish(&hash) as u32;
246            left = right;
247            right = next;
248            round += 1;
249        }
250        Word::new((u64::from(left) << 32) | u64::from(right))
251    }
252
253    fn lane<const LANE: u64>(&self, kind: u8) -> SipHasher24 {
254        let mut state = SipHasher24::new(self.0[0], self.0[1], ());
255        hash::Hasher::write_u64(&mut state, LANE);
256        hash::Hasher::write_u8(&mut state, kind);
257        state
258    }
259
260    fn prefix(&self, domain: Domain) -> SipHasher24 {
261        let mut state = SipHasher24::new(self.0[0], self.0[1], ());
262        hash::Hasher::write(&mut state, &domain.namespace);
263        hash::Hasher::write_u64(&mut state, domain.instance);
264        state
265    }
266}
267
268/// Stable, human-readable ownership of one independent random namespace.
269#[derive(Clone, Copy, PartialEq, Eq, Hash)]
270#[repr(transparent)]
271pub struct Namespace([u8; 8]);
272
273impl Namespace {
274    pub const fn new(name: [u8; 8]) -> Self {
275        Self(name)
276    }
277
278    pub const fn fixed(self) -> Domain {
279        self.instance(0)
280    }
281
282    pub const fn instance(self, instance: u64) -> Domain {
283        Domain {
284            namespace: self.0,
285            instance,
286        }
287    }
288}
289
290/// Stable separation between one owned namespace and one exact instance.
291#[derive(Clone, Copy, PartialEq, Eq, Hash)]
292pub struct Domain {
293    namespace: [u8; 8],
294    instance: u64,
295}
296
297/// One purpose- and lane-bound random word.
298#[repr(transparent)]
299pub struct Word<P, const LANE: u64>(u64, marker::PhantomData<fn(P) -> P>);
300
301impl<P, const LANE: u64> Word<P, LANE> {
302    const fn new(value: u64) -> Self {
303        Self(value, marker::PhantomData)
304    }
305
306    /// Consumes this purpose-bound word into its canonical big-endian encoding.
307    pub const fn into_bytes(self) -> [u8; 8] {
308        self.0.to_be_bytes()
309    }
310}
311
312const _: () = {
313    assert!(mem::size_of::<Key>() == 2 * mem::size_of::<u64>());
314    assert!(mem::size_of::<Namespace>() == mem::size_of::<u64>());
315    assert!(mem::size_of::<Domain>() == 2 * mem::size_of::<u64>());
316    assert!(mem::size_of::<Word<(), 0>>() == mem::size_of::<u64>());
317};