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