Skip to main content

ore_rs/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3// Library code does not panic: it returns an error or carries the invariant
4// in a type. Tests may. Clippy has no lint for `assert!`;
5// `scripts/no-runtime-asserts.py` covers that in CI.
6#![cfg_attr(
7    not(test),
8    deny(
9        clippy::panic,
10        clippy::unwrap_used,
11        clippy::expect_used,
12        clippy::unreachable,
13        clippy::todo,
14        clippy::unimplemented,
15        clippy::panic_in_result_fn
16    )
17)]
18
19mod block_ore;
20mod ciphertext;
21mod primitives;
22pub mod scheme;
23mod term;
24#[cfg(test)]
25pub(crate) mod testing;
26pub use crate::block_ore::{BlockOre, BlockOreSpace, ORE_KEY};
27pub(crate) use crate::ciphertext::*;
28pub use crate::term::{Query, Term};
29
30/// Timing-measurement entry points to private primitives, for the detached
31/// `ct-dudect` crate. Enabled only by the `ct-bench` feature; not public API.
32#[cfg(feature = "ct-bench")]
33#[doc(hidden)]
34pub mod ct_bench {
35    use crate::primitives::prp::{oblivious, LemireFyPrp};
36    use crate::primitives::{Prp, Symbol};
37
38    /// Build the 64-element Bit6 PRP from a 512-byte draw stream and return
39    /// one permuted value, so the construction is observably used. This is
40    /// the builder the schemes use (the target's oblivious builder).
41    pub fn lemire_fy_prp_from_stream(stream: &[u8; 512]) -> u8 {
42        LemireFyPrp::<64>::from_stream(stream)
43            .permute(Symbol::from_low_bits(0))
44            .get()
45    }
46
47    fn from_stream_with(
48        stream: &[u8; 512],
49        build: fn(&[u8; 512], &mut [u8; 64], &mut [u8; 64]),
50    ) -> u8 {
51        LemireFyPrp::<64>::from_stream_with(stream, build)
52            .permute(Symbol::from_low_bits(0))
53            .get()
54    }
55
56    /// As [`lemire_fy_prp_from_stream`], through the reference builder:
57    /// textbook Fisher–Yates with secret-indexed swaps and inverse fill.
58    /// Not used by any scheme; here for before/after timing.
59    pub fn lemire_fy_prp_from_stream_reference(stream: &[u8; 512]) -> u8 {
60        from_stream_with(stream, oblivious::reference::build)
61    }
62
63    /// As [`lemire_fy_prp_from_stream`], through the byte-at-a-time
64    /// `subtle_ng` oblivious builder whatever the target.
65    pub fn lemire_fy_prp_from_stream_scalar_oblivious(stream: &[u8; 512]) -> u8 {
66        from_stream_with(stream, oblivious::scalar::build)
67    }
68
69    /// As [`lemire_fy_prp_from_stream`], through the portable SWAR
70    /// oblivious builder whatever the target.
71    pub fn lemire_fy_prp_from_stream_swar_oblivious(stream: &[u8; 512]) -> u8 {
72        from_stream_with(stream, oblivious::swar::build)
73    }
74
75    // -----------------------------------------------------------------
76    // Mechanism isolation: the two halves of the reference builder, and a
77    // control for each with the same work at public addresses. Each keeps
78    // its table in one 64-byte-aligned line, as `LemireFyPrp<64>` does.
79    // -----------------------------------------------------------------
80
81    /// One 64-byte, line-aligned table.
82    #[repr(C, align(64))]
83    pub struct Line(pub [u8; 64]);
84
85    /// Lemire draw for step `i`, reduced to `0..=i`: the builders' own
86    /// [`oblivious::lemire_draw`], so the benches cannot drift from it.
87    #[inline(always)]
88    fn draw(stream: &[u8; 512], i: usize) -> usize {
89        usize::from(oblivious::lemire_draw(stream, i))
90    }
91
92    /// The reference builder's Fisher–Yates swap loop alone (no inverse
93    /// fill): swaps at the secret draw-derived index. The loop is
94    /// `oblivious::reference::build`'s, restated so it can be timed
95    /// without the fill; a test pins it to that builder's permutation.
96    #[inline(never)]
97    pub fn fy_swaps_only(stream: &[u8; 512], out: &mut Line) {
98        for (k, p) in out.0.iter_mut().enumerate() {
99            *p = k as u8;
100        }
101        for i in (1..64).rev() {
102            let j = draw(stream, i);
103            out.0.swap(i, j);
104        }
105    }
106
107    /// Control for [`fy_swaps_only`]: the same draws and the same swaps,
108    /// but at the public index `i - 1` (the draw is computed and kept live,
109    /// then not used as an address).
110    #[inline(never)]
111    pub fn fy_swaps_public(stream: &[u8; 512], out: &mut Line) {
112        for (k, p) in out.0.iter_mut().enumerate() {
113            *p = k as u8;
114        }
115        for i in (1..64).rev() {
116            core::hint::black_box(draw(stream, i));
117            out.0.swap(i, i - 1);
118        }
119    }
120
121    /// The permutation the builders build for `stream`, computed outside
122    /// any measured region by the reference builder itself, to feed
123    /// [`inverse_fill_only`].
124    pub fn permutation_for(stream: &[u8; 512]) -> Line {
125        let mut l = Line([0u8; 64]);
126        let mut inverse = [0u8; 64];
127        oblivious::reference::build(stream, &mut l.0, &mut inverse);
128        l
129    }
130
131    /// The reference builder's inverse fill alone: `inverse[perm[k]] = k`,
132    /// stores at secret offsets.
133    #[inline(never)]
134    pub fn inverse_fill_only(perm: &Line, out: &mut Line) {
135        for (index, val) in perm.0.iter().enumerate() {
136            out.0[*val as usize & 63] = index as u8;
137        }
138    }
139
140    /// Control for [`inverse_fill_only`]: the same loads and stores, at the
141    /// public offset `index` (the loaded value is kept live, not used as an
142    /// address).
143    #[inline(never)]
144    pub fn inverse_fill_public(perm: &Line, out: &mut Line) {
145        for (index, val) in perm.0.iter().enumerate() {
146            core::hint::black_box(*val);
147            out.0[index] = index as u8;
148        }
149    }
150
151    #[cfg(test)]
152    mod tests {
153        use super::*;
154
155        /// The isolated swap loop and inverse fill build exactly what the
156        /// reference builder builds, so the isolation benches time the real
157        /// construction.
158        #[test]
159        fn isolation_halves_match_the_reference_builder() {
160            for seed in 0u8..16 {
161                let stream: [u8; 512] =
162                    core::array::from_fn(|k| (k as u8).wrapping_mul(167) ^ seed.wrapping_mul(29));
163                let mut want_perm = [0u8; 64];
164                let mut want_inverse = [0u8; 64];
165                oblivious::reference::build(&stream, &mut want_perm, &mut want_inverse);
166
167                let mut swaps = Line([0u8; 64]);
168                fy_swaps_only(&stream, &mut swaps);
169                assert_eq!(swaps.0, want_perm);
170
171                let mut inverse = Line([0u8; 64]);
172                inverse_fill_only(&permutation_for(&stream), &mut inverse);
173                assert_eq!(inverse.0, want_inverse);
174            }
175        }
176    }
177}
178use primitives::PrpError;
179use std::cmp::Ordering;
180use thiserror::Error;
181use vitaminc_ore::OrderPlaintext;
182
183/// Fixed-size block array, the input to the fixed-N encryption routines.
184/// `N` is the block count. For the legacy scheme a block is a plaintext
185/// byte; for Bit6 a 6-bit symbol. The fixed-N path caps `N` at 15 (legacy)
186/// or 14 (Bit6) by the AES-as-PRF input packing.
187pub(crate) type PlainText<const N: usize> = [u8; N];
188
189/// Errors returned by scheme initialisation and encryption.
190///
191/// New schemes and policies add variants, so the enum is non-exhaustive.
192#[derive(Debug, Error)]
193#[non_exhaustive]
194pub enum OreError {
195    /// Cipher initialisation failed (e.g., key material rejected by an
196    /// underlying primitive).
197    #[error("Failed to initialize cipher")]
198    InitFailed,
199    /// A pseudo-random permutation primitive returned an error.
200    #[error(transparent)]
201    PrpError(#[from] PrpError),
202    /// The OS random number generator could not seed the scheme's
203    /// generator, from which every per-ciphertext nonce is drawn.
204    #[error("Randomness Error")]
205    Random(#[from] vitaminc_random::RandomError),
206    /// A text or bytes plaintext, whose width varies, on a fixed-width
207    /// scheme. Only the chained scheme takes them.
208    #[error("Variable-length plaintext on a fixed-width scheme")]
209    VariableLength,
210    /// The plaintext exceeds the maximum block count the wire format can
211    /// represent (the chained scheme encodes the block count as a `u16`).
212    #[error("Too many blocks")]
213    TooManyBlocks,
214    /// A string longer than the fixed length its padding policy pads to.
215    #[error("String longer than its padding")]
216    ExceedsPadding,
217    /// A string longer than the cipher's ceiling
218    /// (`scheme::chained::Options::max_bytes`).
219    #[error("String longer than the cipher's maximum")]
220    TooLong,
221    /// A string that ends in NUL, refused by a padding policy: padded with
222    /// NULs, it would encrypt the same as the string without them.
223    #[error("String ends in NUL")]
224    TrailingNul,
225    /// A plaintext encoded as another target than the space it was handed
226    /// to (`BlockOre`'s `encrypt_plaintext` or `encrypt_query` called
227    /// directly, with a space of another target).
228    #[error("Plaintext of another target than the space's")]
229    TargetMismatch,
230}
231
232mod sealed {
233    pub trait Sealed {}
234}
235
236/// An ORE scheme: encrypts a sealed [`OrderPlaintext`] to a stored
237/// [`Term`] or a [`Query`], and compares the serialised bytes of either
238/// without a key.
239///
240/// The plaintext comes from vitaminc-ore, which owns the encodings:
241/// `vitaminc_ore::order()` makes one from a value and a target, and
242/// [`BlockOre`] is the typed way in, which routes a plaintext to
243/// the right engine by its width. A scheme here takes nothing else, so no
244/// caller can hand it bytes that skipped the encoding.
245///
246/// Sealed: the schemes are this crate's. [`scheme::bit2_w6::OreAes128Bit6`]
247/// takes fixed-width plaintexts of up to 10 bytes,
248/// [`scheme::chained::OreAes128Bit6Chained`] takes any plaintext, and the
249/// legacy [`scheme::bit2::OreAes128`] takes fixed-width plaintexts of up to
250/// 15 bytes.
251pub trait OreScheme: sealed::Sealed {
252    /// Encrypt `plaintext` to a full ciphertext, for storage. Carries a
253    /// random nonce, so one value has many terms, which compare `Equal`.
254    fn encrypt_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Term, OreError>;
255
256    /// Encrypt `plaintext` to a query: the left half alone, which is what
257    /// a comparison against a stored term needs from the other side.
258    /// Deterministic under one key and salt.
259    fn encrypt_query_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Query, OreError>;
260
261    /// Compare two serialised full ciphertexts (the bytes of two
262    /// [`Term`]s) without a key. `None` if either is not a well-formed
263    /// ciphertext of this scheme, or the two were not made to compare: on
264    /// the fixed-width schemes (Bit6 and legacy), a different block
265    /// count; on the chained scheme, a different padding policy. The
266    /// chained scheme compares terms of different block counts, across
267    /// length buckets too, lexicographically: a plaintext that is a
268    /// prefix of the other sorts first.
269    fn compare_raw_slices(a: &[u8], b: &[u8]) -> Option<Ordering>;
270
271    /// Compare a serialised query (the bytes of a [`Query`]) with a
272    /// serialised full ciphertext: the order of the queried value against
273    /// the stored one, `Less` when the query sorts first. `None` as
274    /// [`compare_raw_slices`](Self::compare_raw_slices) is `None`, and
275    /// for a full ciphertext passed as the query or a query as the term.
276    fn compare_left_to_full(left: &[u8], full: &[u8]) -> Option<Ordering>;
277}
278
279/// A fixed-N BlockORE engine: encrypts `N` blocks to typed halves whose
280/// serialised bytes compare in plaintext order. Crate-private: the block
281/// count is only known when a plaintext arrives, so the public surface is
282/// [`OreScheme`], over sealed plaintexts and bytes.
283pub(crate) trait OreCipher: Sized {
284    /// Block type for the Left half of a ciphertext (per-block PRF tag plus
285    /// permuted plaintext byte).
286    type LeftBlockType: CipherTextBlock;
287    /// Block type for the Right half of a ciphertext (per-block masked
288    /// truth-table row).
289    type RightBlockType: CipherTextBlock;
290
291    /// Wire-format header for this scheme's serialised artifacts, or
292    /// `None` for the legacy headerless format. Schemes introduced from
293    /// ORE v2 onwards must set this; see [`WireHeader`].
294    const WIRE_HEADER: Option<WireHeader> = None;
295
296    /// Number of distinct per-block symbols (`xt` values) the scheme
297    /// produces: 256 for the byte-wide legacy scheme, 64 for Bit6. Parsers
298    /// reject a ciphertext whose `xt` holds a symbol outside `0..SYMBOL_DOMAIN`,
299    /// since the comparator indexes the right block by it.
300    const SYMBOL_DOMAIN: usize = 256;
301
302    /// Encrypt `input` and return only the Left half of the ciphertext:
303    /// the query side.
304    fn encrypt_left<const N: usize>(&self, input: &PlainText<N>)
305        -> Result<Left<Self, N>, OreError>;
306
307    /// Encrypt `input` and return the full Left+Right ciphertext suitable
308    /// for storage and subsequent comparison against any other ciphertext.
309    fn encrypt<const N: usize>(
310        &self,
311        input: &PlainText<N>,
312    ) -> Result<CipherText<Self, N>, OreError>;
313}
314
315#[cfg(test)]
316#[macro_use]
317extern crate quickcheck;