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