Skip to main content

ore_rs/scheme/
chained.rs

1//! Variable-length / chained-prefix BlockORE over 6-bit blocks.
2//!
3//! Lifts the fixed-N packed-prefix cap (≤ 14 blocks) by deriving every
4//! per-block secret from an incremental **AES-CMAC accumulator** over the
5//! prefix, instead of packing the raw prefix into one AES block. This enables
6//! arbitrary-length plaintexts — strings in particular. Design:
7//! `docs/plans/2026-06-15-ore-v2-cmac-accumulator-spec.md` (the A2 gate).
8//!
9//! **Status: wire format (scheme id `0x03`) frozen as of 0.9.0.**
10//! `src/scheme/chained/compat_vectors.rs` pins the bytes, padded and
11//! unpadded; a change that alters them breaks every stored chained
12//! ciphertext.
13//!
14//! Per block `n` (prefix `x[0..n-1]`, accumulator state `S_n`):
15//! - **PRP** `π_n` (shape ii): keystream = `STREAM_BLOCKS` CMAC tags on the
16//!   `PRP_STREAM` branch → `LemireFyPrp::from_stream` (no per-block key
17//!   schedule).
18//! - **left tag** `f[n] = ro(n, xt[n])` — the `RO_KEY` branch at the permuted
19//!   symbol (so the left/right masks cancel at compare time).
20//! - **right block**: `H(ro(n, j), nonce) ⊕ indicator`, as the fixed-N scheme.
21//!
22//! Comparison is lexicographic: scan `min(len_a, len_b)` blocks; if a prefix
23//! matches throughout, the shorter sorts first. A comparison reveals the
24//! common-prefix length.
25//!
26//! **Length.** The header stores the block count, and the size is
27//! `7 + 25*count + 16` bytes for a full ciphertext (`7 + 17*count` for a
28//! left), so every ciphertext gives its block count with no comparison or
29//! query. Unpadded, a string of `n` UTF-8 bytes has `count = ⌈8n/6⌉`, which
30//! is strictly increasing in `n`, so the ciphertext gives `n` exactly. The
31//! string encryptors therefore pad by default
32//! ([`Padding`](crate::scheme::chained::Padding)): the string is extended
33//! with NUL bytes to a length bucket, and a ciphertext reveals only the
34//! bucket. The default is powers of two with a 16-byte floor: 16, 32, 64
35//! bytes and so on
36//! ([`Padding::PowerOfTwo`](crate::scheme::chained::Padding::PowerOfTwo)).
37//! Padmé (Nikitin et al., PETS 2019) was considered and set aside: at
38//! database string lengths it hides little (see the variant docs and
39//! <https://github.com/cipherstash/ore.rs/issues/104>).
40//!
41//! Padding with NUL bytes keeps order and equality for strings that do not
42//! end in NUL. NUL bytes decompose to zero blocks, the same zero bits the
43//! decomposition already fills a final partial block with. Where the shorter
44//! of two strings ends, the longer one has a non-zero bit somewhere in its
45//! remaining bytes (its last byte is not NUL, though bytes before it may
46//! be), and the shorter string has only zeros there, so the shorter sorts
47//! first, as "shorter sorts first" requires. Equal strings have equal
48//! lengths, so they pad to the same bucket. A string that ends in NUL would
49//! pad to the same blocks as the string without it, so the padded encryptors
50//! refuse it ([`OreError::TrailingNul`](crate::OreError::TrailingNul)).
51//! Postgres `text` and `jsonb` cannot hold NUL. Pad blocks cannot be told
52//! apart from the string's own blocks in a ciphertext: each block's PRP is
53//! keyed by its position and prefix.
54//!
55//! The header also carries the padding policy, and the comparators return
56//! `None` for two ciphertexts made under different policies: an unpadded
57//! `"abc"` and a padded `"abc"` have different blocks, and would compare
58//! unequal. Stored values and the queries that compare with them must use
59//! one policy.
60//!
61//! A cipher also has a longest string it encrypts
62//! ([`Options::with_max_bytes`](crate::scheme::chained::Options::with_max_bytes),
63//! default [`DEFAULT_MAX_STR_BYTES`](crate::scheme::chained::DEFAULT_MAX_STR_BYTES)
64//! = 1024 bytes); a longer one is refused
65//! ([`OreError::TooLong`](crate::OreError::TooLong)). Ciphertext size and
66//! encryption time grow with the padded length, and the string comes from
67//! the caller, so without a ceiling one 1025-byte string costs a 2048-byte
68//! bucket, 2731 blocks and a 68 KB ciphertext. The ceiling is not on the
69//! wire: the comparators accept any block count the policy admits.
70//!
71//! The scheme takes no string, bytes or symbols directly: every plaintext
72//! arrives sealed, as an `OrderPlaintext` vitaminc has encoded, and text is
73//! the only target it pads. The scheme encrypts any sequence of 6-bit
74//! symbols, and the tests use that entry point directly (symbols a string
75//! never produces, unpadded), but raw symbols cannot be padded with zero
76//! symbols, since a trailing zero symbol is a real value there, so they are
77//! not offered as an API (#110).
78//!
79//! **Fixed-width plaintexts.** A sealed `OrderPlaintext` of any fixed
80//! width goes in unpadded (every value of its target has one width, so
81//! there is nothing to hide): a `u128`, a decimal, a timestamp, a uuid. The
82//! ciphertext is tagged [`Padding::None`](crate::scheme::chained::Padding::None), and the string ceiling is not
83//! checked. The block count is a length, not a type: a `u128` and an
84//! unpadded 16-byte string are both 22 blocks, and under one key an equal
85//! encoding gives an equal ciphertext. vitaminc's salt carries the target,
86//! so a space of one target never meets another's terms.
87//!
88//! The scheme takes a sealed plaintext through [`crate::OreScheme`] and nothing
89//! else. Text (`OrderTarget::Text`) is padded under the cipher's
90//! [`Options`](crate::scheme::chained::Options); bytes (`OrderTarget::Bytes`) are not, since NUL padding
91//! would refuse every value that ends in a zero byte, but are refused past
92//! the ceiling as text is; a fixed-width target is neither padded nor
93//! bounded, its length being the target's. vitaminc's text and bytes encodings start with a marker byte, so
94//! no plaintext is empty and every term this version makes has a keyed block.
95//! Version 0.9 encrypted the empty string under [`Padding::None`](crate::scheme::chained::Padding::None) or
96//! `Padding::PowerOfTwo { min_bytes: 0 }` to a term with no blocks: the
97//! header, and a nonce in a full ciphertext. Such terms can be in stored
98//! data, so the comparators still accept a block count of 0: the term is
99//! `Equal` to itself and below every other term under the same policy.
100//!
101//! **Stored rows compare offline.** A full ciphertext carries its
102//! deterministic left half (`xt`, `f`), so anyone holding two stored full
103//! ciphertexts can run `compare_raw_slices` with no
104//! query and learn their order and common-prefix length. The legacy scheme
105//! has the same exposure. There is no right-only storage path yet (plan
106//! §5(b)).
107
108use std::cmp::Ordering;
109use std::convert::TryFrom;
110use std::num::{NonZeroU16, NonZeroUsize};
111use std::sync::Mutex;
112
113use rand::TryRng;
114use subtle_ng::{Choice, ConditionallySelectable, ConstantTimeEq};
115use vitaminc_context::Context;
116use vitaminc_ore::{OrderPlaintext, OrderTarget};
117use vitaminc_protected::{Controlled, Protected};
118use vitaminc_random::SafeRand;
119use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
120
121#[cfg(test)]
122use crate::ciphertext::ParseError;
123use crate::ciphertext::{parse_header, WireHeader, WIRE_HEADER_LEN};
124use crate::primitives::cmac::{final_block, prefix_block, Branch, CmacAccumulator, WIDTH_BIT6};
125use crate::primitives::hash::FixedPiZ2Hash;
126use crate::primitives::prp::LemireFyPrp;
127use crate::primitives::{stack, AesBlock, Hash, HashKey, Prp};
128use crate::scheme::decompose::{num_blocks_6bit, Blocks6};
129use crate::scheme::keys;
130use crate::scheme::width::FirstDiff;
131use crate::{OreError, OreScheme, Query, Term};
132
133const VERSION: u8 = 0x02;
134pub(crate) const SCHEME_ID: u8 = 0x03;
135/// The common wire header of this scheme.
136const WIRE: WireHeader = WireHeader {
137    version: VERSION,
138    scheme_id: SCHEME_ID,
139};
140const DOMAIN: usize = 64;
141/// CMAC tags per block for the PRP keystream: ⌈(DOMAIN−1)·8 / 16⌉ = 32.
142const STREAM_BLOCKS: usize = 32;
143const F_LEN: usize = 16;
144const RIGHT_LEN: usize = DOMAIN / 8; // 8
145/// The padding policy tag after the common wire header: a kind byte and a
146/// big-endian `u16` (see [`Padding`]).
147const PADDING_LEN: usize = 3;
148const HEADER_LEN: usize = WIRE_HEADER_LEN + PADDING_LEN;
149const NONCE_LEN: usize = 16;
150
151/// The only input the caller's key is evaluated on (spec §3): ends in
152/// `'t'` (`0x74`), outside every legacy PRF input's byte 15. See
153/// `scheme::keys`.
154const ROOT_LABEL: [u8; 16] = *b"ORE.v2.chainroot";
155const _: () = assert!(
156    ROOT_LABEL[15] > 14,
157    "root label collides with a legacy PRF input"
158);
159/// Label for the accumulator key under the salted key (spec §3).
160const ACC_KEY_LABEL: [u8; 16] = *b"ORE.v2.chain.acc";
161
162/// Serialised length of a full ciphertext with `count` blocks.
163#[inline]
164fn total_len(count: usize) -> usize {
165    HEADER_LEN + count + count * F_LEN + NONCE_LEN + count * RIGHT_LEN
166}
167
168/// Serialised length of a left-only ciphertext (`header ‖ xt ‖ f`) — the prefix
169/// of a full ciphertext, with no nonce/right half. Matches `VarLeft::to_bytes`.
170#[inline]
171fn left_len(count: usize) -> usize {
172    HEADER_LEN + count + count * F_LEN
173}
174
175// Raw-byte accessors into a serialised full ciphertext (see `to_bytes`).
176#[inline]
177fn xt_at(s: &[u8], i: usize) -> u8 {
178    s[HEADER_LEN + i]
179}
180#[inline]
181fn f_at(s: &[u8], count: usize, i: usize) -> &[u8] {
182    let o = HEADER_LEN + count + i * F_LEN;
183    &s[o..o + F_LEN]
184}
185#[inline]
186fn nonce_at(s: &[u8], count: usize) -> &[u8] {
187    let o = HEADER_LEN + count + count * F_LEN;
188    &s[o..o + NONCE_LEN]
189}
190#[inline]
191fn right_at(s: &[u8], count: usize, i: usize) -> &[u8] {
192    let o = HEADER_LEN + count + count * F_LEN + NONCE_LEN + i * RIGHT_LEN;
193    &s[o..o + RIGHT_LEN]
194}
195
196/// How the string encryptors pad a string before encrypting it, so that a
197/// ciphertext reveals a length bucket rather than the exact length (see the
198/// module docs).
199///
200/// Lengths are in UTF-8 bytes. The policy belongs with the key: stored
201/// values and the queries that compare with them must use the same one,
202/// and changing it means re-encrypting the stored values. The comparators refuse to compare ciphertexts
203/// made under different policies.
204///
205/// Padding hides the exact length in the ciphertext only: the time the
206/// encryptor takes still depends on the exact length of the string.
207///
208/// More policies may follow (a growth ratio between buckets, boundaries
209/// fitted to the data), so the enum is non-exhaustive.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum Padding {
213    /// No padding: the ciphertext reveals the exact length.
214    None,
215    /// Pad to `min_bytes` if the string fits, and otherwise to the smallest
216    /// power of two that holds it. With the default 16-byte floor the
217    /// buckets are 16, 32, 64, 128 bytes and so on: a ciphertext reveals
218    /// about `log₂ L` of a length `L`, every string up to `min_bytes` long
219    /// pads to the same length, and above the floor padding less than
220    /// doubles a length. A
221    /// string that would pad past [`MAX_STR_BYTES`] is refused
222    /// ([`OreError::TooManyBlocks`]), so with the default floor the longest
223    /// bucket is 32768 bytes; the cipher's own ceiling
224    /// ([`Options::with_max_bytes`]) is usually far lower.
225    ///
226    /// Chosen over Padmé (Nikitin et al., PETS 2019). Padmé leaves only
227    /// `O(log log L)` bits of the length and adds under 12.5%, but it was
228    /// designed for kilobyte-to-gigabyte messages. At database string
229    /// lengths its buckets are narrow: below 9 bytes it changes nothing,
230    /// from 9 to 31 bytes it rounds only to an even length, and from 32 to
231    /// 63 to a multiple of 4. Powers of two cost more blocks and leak more
232    /// in theory, but their buckets are far wider where strings actually
233    /// are. The simulation behind the choice is in
234    /// <https://github.com/cipherstash/ore.rs/issues/104>.
235    PowerOfTwo {
236        /// Floor below which every string pads to one bucket.
237        min_bytes: u16,
238    },
239    /// Pad every string to `max_bytes`, so ciphertexts reveal nothing of
240    /// the length. Longer strings are refused
241    /// ([`OreError::ExceedsPadding`]).
242    Fixed {
243        /// The length every string pads to. Non-zero: vitaminc puts a
244        /// marker byte before every text, so no value fits in 0.
245        max_bytes: NonZeroU16,
246    },
247}
248
249impl Default for Padding {
250    /// Powers of two with a 16-byte floor.
251    fn default() -> Self {
252        Padding::PowerOfTwo { min_bytes: 16 }
253    }
254}
255
256impl Padding {
257    /// The length in bytes a string of `len` bytes pads to, which is what a
258    /// ciphertext reveals of it. Errors as the string encryptors do:
259    /// [`OreError::ExceedsPadding`] if `len` exceeds a fixed length, and
260    /// [`OreError::TooManyBlocks`] if the padded string has more blocks than
261    /// the wire format can number.
262    pub fn padded_len(self, len: usize) -> Result<usize, OreError> {
263        let padded = match self {
264            Padding::None => len,
265            Padding::PowerOfTwo { min_bytes } if len <= min_bytes.into() => min_bytes.into(),
266            Padding::PowerOfTwo { .. } => len
267                .checked_next_power_of_two()
268                .ok_or(OreError::TooManyBlocks)?,
269            Padding::Fixed { max_bytes } if len <= max_bytes.get().into() => max_bytes.get().into(),
270            Padding::Fixed { .. } => return Err(OreError::ExceedsPadding),
271        };
272        if padded > MAX_STR_BYTES {
273            return Err(OreError::TooManyBlocks);
274        }
275        Ok(padded)
276    }
277
278    /// The policy as it appears in the wire header.
279    fn to_wire(self) -> [u8; PADDING_LEN] {
280        let (kind, n) = match self {
281            Padding::None => (0, 0),
282            Padding::PowerOfTwo { min_bytes } => (1, min_bytes),
283            Padding::Fixed { max_bytes } => (2, max_bytes.get()),
284        };
285        let [hi, lo] = n.to_be_bytes();
286        [kind, hi, lo]
287    }
288
289    /// Parse a policy written by [`Self::to_wire`]. A policy no cipher
290    /// could have been initialised with is refused, as is an unknown kind.
291    fn from_wire(tag: [u8; PADDING_LEN]) -> Option<Self> {
292        let [kind, hi, lo] = tag;
293        let n = u16::from_be_bytes([hi, lo]);
294        let padding = match kind {
295            0 if n == 0 => Padding::None,
296            1 => Padding::PowerOfTwo { min_bytes: n },
297            2 => Padding::Fixed {
298                max_bytes: NonZeroU16::new(n)?,
299            },
300            _ => return None,
301        };
302        padding.padded_len(0).ok().map(|_| padding)
303    }
304
305    /// Whether a ciphertext of `count` blocks can have been made under this
306    /// policy: the block count of some length the policy pads to. The
307    /// parsers and comparators refuse a header whose count and policy no
308    /// cipher could have produced together.
309    fn admits_count(self, count: usize) -> bool {
310        match self {
311            Padding::None => true,
312            Padding::Fixed { max_bytes } => count == num_blocks_6bit(max_bytes.get().into()),
313            Padding::PowerOfTwo { min_bytes } => {
314                let min_bytes = usize::from(min_bytes);
315                count == num_blocks_6bit(min_bytes)
316                    || (0..=MAX_STR_BYTES.ilog2()).any(|k| {
317                        let bucket = 1usize << k;
318                        bucket > min_bytes && count == num_blocks_6bit(bucket)
319                    })
320            }
321        }
322    }
323}
324
325/// The longest string a cipher encrypts unless [`Options::with_max_bytes`]
326/// says otherwise: 1024 UTF-8 bytes, a 1024-byte bucket under the default
327/// padding.
328pub const DEFAULT_MAX_STR_BYTES: NonZeroUsize = match NonZeroUsize::new(1024) {
329    Some(n) => n,
330    None => NonZeroUsize::MIN,
331};
332
333/// Per-cipher settings, passed to [`OreAes128Bit6Chained::init_with`]:
334/// the salt the key is derived under, and the string encryptors' padding
335/// policy and ceiling. Like the key, they belong to the values that are
336/// compared together: stored values and the queries that compare with them
337/// use the same ones.
338///
339/// ```rust
340/// use ore_rs::scheme::chained::{OreAes128Bit6Chained, Options, Padding};
341/// use ore_rs::OreScheme;
342/// use std::num::NonZeroUsize;
343/// use vitaminc_context::Context;
344/// use vitaminc_ore::{order, OrderTarget, Physical};
345/// use vitaminc_protected::Protected;
346///
347/// let options = Options::default()
348///     .with_salt(&Context::from_encoded(&b"users.email"[..]))
349///     .with_padding(Padding::PowerOfTwo { min_bytes: 32 })
350///     .with_max_bytes(NonZeroUsize::new(256).unwrap());
351/// let ore = OreAes128Bit6Chained::init_with(Protected::new([0u8; 16]), options).unwrap();
352/// let text = |s: &str| order(OrderTarget::Text, None, Physical::Text(s)).unwrap();
353/// // The ceiling counts the marker byte vitaminc puts before the text.
354/// assert!(ore.encrypt_plaintext(&text(&"a".repeat(255))).is_ok());
355/// assert!(ore.encrypt_plaintext(&text(&"a".repeat(256))).is_err());
356/// ```
357#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct Options {
359    salt: Vec<u8>,
360    padding: Padding,
361    max_bytes: NonZeroUsize,
362}
363
364impl Default for Options {
365    /// An empty salt, [`Padding::default`] and [`DEFAULT_MAX_STR_BYTES`].
366    fn default() -> Self {
367        Self {
368            salt: Vec::new(),
369            padding: Padding::default(),
370            max_bytes: DEFAULT_MAX_STR_BYTES,
371        }
372    }
373}
374
375impl Options {
376    /// The defaults; see [`Default`].
377    pub fn new() -> Self {
378        Self::default()
379    }
380
381    /// The salt the key is derived under: a name for what the key is for
382    /// (a data set, a tenant, a plaintext type). Ciphertexts under different
383    /// salts share no key material; nothing on the wire records the salt,
384    /// so a mismatched pair compares to a confident, meaningless result,
385    /// `Equal` included. The default is empty. The context a vitaminc
386    /// space derives, or any bytes as `Context::from_encoded(bytes)`. See
387    /// [`OreAes128Bit6Chained::init_with`].
388    pub fn with_salt(self, salt: &Context<'_>) -> Self {
389        Self {
390            salt: salt.as_bytes().to_vec(),
391            ..self
392        }
393    }
394
395    /// The padding policy the string encryptors apply.
396    pub fn with_padding(self, padding: Padding) -> Self {
397        Self { padding, ..self }
398    }
399
400    /// The longest string, in UTF-8 bytes, the cipher encrypts; a longer
401    /// one returns [`OreError::TooLong`]. Bounds what one input can cost in
402    /// ciphertext size and encryption time, and how many length buckets the
403    /// ciphertexts can show. Under [`Padding::Fixed`] the fixed length is also a
404    /// ceiling, and the lower of the two applies. `init_with` refuses a
405    /// ceiling that pads past [`MAX_STR_BYTES`].
406    pub fn with_max_bytes(self, max_bytes: NonZeroUsize) -> Self {
407        Self { max_bytes, ..self }
408    }
409
410    /// The salt; see [`Self::with_salt`].
411    pub fn salt(&self) -> &[u8] {
412        &self.salt
413    }
414
415    /// The padding policy.
416    pub fn padding(&self) -> Padding {
417        self.padding
418    }
419
420    /// The longest string the cipher encrypts; see [`Self::with_max_bytes`].
421    pub fn max_bytes(&self) -> NonZeroUsize {
422        self.ceiling()
423    }
424
425    /// `max_bytes`, or the fixed length if that is lower.
426    fn ceiling(&self) -> NonZeroUsize {
427        match self.padding {
428            Padding::Fixed { max_bytes } => self.max_bytes.min(NonZeroUsize::from(max_bytes)),
429            _ => self.max_bytes,
430        }
431    }
432
433    /// Why a cipher cannot be initialised with these options, if it cannot.
434    fn check(&self) -> Result<(), OreError> {
435        // The policy must pad the empty string and the longest string.
436        self.padding
437            .padded_len(0)
438            .map_err(|_| OreError::InitFailed)?;
439        self.padding
440            .padded_len(self.ceiling().get())
441            .map_err(|_| OreError::InitFailed)?;
442        Ok(())
443    }
444}
445
446/// Left half of a chained ciphertext: per-block permuted symbol + tag.
447/// Crate-private: a [`Query`] carries its bytes.
448#[derive(Clone, Debug)]
449pub(crate) struct VarLeft {
450    xt: Vec<u8>,
451    f: Vec<[u8; F_LEN]>,
452    padding: Padding,
453}
454
455/// Right half: per-ciphertext nonce + per-block masked bitvectors.
456#[derive(Clone, Debug)]
457pub(crate) struct VarRight {
458    nonce: [u8; NONCE_LEN],
459    blocks: Vec<[u8; RIGHT_LEN]>,
460}
461
462/// Full variable-length ciphertext. Crate-private: a [`Term`] carries its
463/// bytes.
464#[derive(Clone, Debug)]
465pub(crate) struct VarCipherText {
466    left: VarLeft,
467    right: VarRight,
468}
469
470impl VarLeft {
471    /// `header ‖ xt ‖ f` (no nonce/right half).
472    pub fn to_bytes(&self) -> Vec<u8> {
473        let count = self.xt.len();
474        let mut out = Vec::with_capacity(left_len(count));
475        write_header(count, self.padding, &mut out);
476        out.extend_from_slice(&self.xt);
477        for fb in &self.f {
478            out.extend_from_slice(fb);
479        }
480        out
481    }
482
483    /// The padding policy the plaintext was encrypted under, for the tests.
484    #[cfg(test)]
485    pub fn padding(&self) -> Padding {
486        self.padding
487    }
488}
489
490/// Read `xt` and `f` out of a validated left view (a `VarLeft` or the
491/// prefix of a full ciphertext) of `count` blocks, tagged `padding`.
492#[cfg(test)]
493fn parse_left_view(data: &[u8], count: usize, padding: Padding) -> VarLeft {
494    let xt = data[HEADER_LEN..HEADER_LEN + count].to_vec();
495    let mut f = Vec::with_capacity(count);
496    for n in 0..count {
497        let mut fb = [0u8; F_LEN];
498        fb.copy_from_slice(f_at(data, count, n));
499        f.push(fb);
500    }
501    VarLeft { xt, f, padding }
502}
503
504impl VarCipherText {
505    /// `header ‖ xt ‖ f ‖ nonce ‖ right`.
506    pub fn to_bytes(&self) -> Vec<u8> {
507        let count = self.left.xt.len();
508        let mut out = Vec::with_capacity(total_len(count));
509        write_header(count, self.left.padding, &mut out);
510        out.extend_from_slice(&self.left.xt);
511        for fb in &self.left.f {
512            out.extend_from_slice(fb);
513        }
514        out.extend_from_slice(&self.right.nonce);
515        for rb in &self.right.blocks {
516            out.extend_from_slice(rb);
517        }
518        out
519    }
520
521    /// The padding policy the plaintext was encrypted under, for the tests.
522    #[cfg(test)]
523    pub fn padding(&self) -> Padding {
524        self.left.padding
525    }
526
527    /// Parse the bytes produced by [`Self::to_bytes`], for the tests.
528    #[cfg(test)]
529    pub fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
530        let (count, padding) = parse_chained_header(data).ok_or(ParseError)?;
531        if data.len() != total_len(count) {
532            return Err(ParseError);
533        }
534        // Same rule as the comparators (and the fixed-width parsers): a symbol
535        // outside the 6-bit domain is not a ciphertext of this scheme.
536        if !symbols_in_domain(data, count) {
537            return Err(ParseError);
538        }
539        let left = parse_left_view(data, count, padding);
540        let mut nonce = [0u8; NONCE_LEN];
541        nonce.copy_from_slice(nonce_at(data, count));
542        let mut blocks = Vec::with_capacity(count);
543        for n in 0..count {
544            let mut rb = [0u8; RIGHT_LEN];
545            rb.copy_from_slice(right_at(data, count, n));
546            blocks.push(rb);
547        }
548        Ok(VarCipherText {
549            left,
550            right: VarRight { nonce, blocks },
551        })
552    }
553}
554
555/// Write the wire header: version, scheme id, block count, padding policy.
556///
557/// Every ciphertext has at most `u16::MAX` blocks: encryption refuses more
558/// ([`OreError::TooManyBlocks`]) and parsing reads the count from a `u16`.
559/// Were a longer one made, the saturated count would not match its body, so
560/// every parser would refuse the bytes.
561fn write_header(count: usize, padding: Padding, out: &mut Vec<u8>) {
562    WIRE.write(u16::try_from(count).unwrap_or(u16::MAX), out);
563    out.extend_from_slice(&padding.to_wire());
564}
565
566/// The block count and padding policy of a serialised view, if its header
567/// is this scheme's and the count is one the policy can produce.
568fn parse_chained_header(view: &[u8]) -> Option<(usize, Padding)> {
569    let ((ver, sid, count), body) = parse_header(view).ok()?;
570    if ver != VERSION || sid != SCHEME_ID {
571        return None;
572    }
573    let tag = <[u8; PADDING_LEN]>::try_from(body.get(..PADDING_LEN)?).ok()?;
574    let padding = Padding::from_wire(tag)?;
575    padding.admits_count(count).then_some((count, padding))
576}
577
578/// The block counts of two serialised views, if both headers are this
579/// scheme's and they share a padding policy. The comparators refuse
580/// ciphertexts made under different policies (see the module docs).
581fn parse_pair(a: &[u8], b: &[u8]) -> Option<(usize, usize)> {
582    let (ca, pa) = parse_chained_header(a)?;
583    let (cb, pb) = parse_chained_header(b)?;
584    (pa == pb).then_some((ca, cb))
585}
586
587/// Variable-length / chained-prefix ORE cipher (6-bit blocks).
588///
589/// Per-encryption nonces come from a [`SafeRand`] seeded from the OS when
590/// the cipher is made, behind a mutex, so the cipher is `Send + Sync`.
591pub struct OreAes128Bit6Chained {
592    /// Dedicated CMAC accumulator key (subsumes the fixed-N `prf1`/`prf2`).
593    k_acc: [u8; 16],
594    /// The salt the key was derived under, and the string encryptors'
595    /// padding policy and ceiling.
596    options: Options,
597    rng: Mutex<SafeRand>,
598}
599
600// Opaque Debug: never render key material.
601impl std::fmt::Debug for OreAes128Bit6Chained {
602    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
603        f.debug_struct("OreAes128Bit6Chained")
604            .field("options", &self.options)
605            .finish_non_exhaustive()
606    }
607}
608
609impl OreAes128Bit6Chained {
610    /// Initialise from one 16-byte key with the default [`Options`]: an
611    /// empty salt, text padded with powers of two from a 16-byte floor,
612    /// and at most [`DEFAULT_MAX_STR_BYTES`] long.
613    pub fn init(key: Protected<[u8; 16]>) -> Result<Self, OreError> {
614        Self::init_with(key, Options::default())
615    }
616
617    /// Initialise from one 16-byte key and a salt, with the other options
618    /// at their defaults: `init_with(key, Options::default().with_salt(salt))`.
619    /// The same constructor as [`OreAes128Bit6::init_with_salt`](crate::scheme::bit2_w6::OreAes128Bit6::init_with_salt).
620    pub fn init_with_salt(key: Protected<[u8; 16]>, salt: &Context<'_>) -> Result<Self, OreError> {
621        Self::init_with(key, Options::default().with_salt(salt))
622    }
623
624    /// Initialise from one 16-byte key and the given [`Options`]: the salt
625    /// naming what the key is for, the string padding policy and the
626    /// string ceiling. Returns [`OreError::InitFailed`] for a policy that
627    /// would pad the empty string or the longest string past
628    /// [`MAX_STR_BYTES`].
629    ///
630    /// The CMAC accumulator derives every per-block secret from one key
631    /// via branch tags (spec §3), keyed by `AES_{k_salt}(ACC_KEY_LABEL)`
632    /// with `k_salt = CMAC_{AES_key(ROOT_LABEL)}(salt)`; see the
633    /// crate-private `scheme::keys` for the stages and their argument.
634    ///
635    /// Ciphertexts under different salts share no key material, but
636    /// nothing on the wire records the salt, so the comparators cannot
637    /// refuse a mismatched pair: they return a confident, meaningless
638    /// result, `Equal` included (a zero-block term, which 0.9 made for the
639    /// empty string, has no key material and compares `Equal` under any
640    /// salts), so no result confirms that two salts match. Keep the salt with the identity of the stored
641    /// data, as you keep the key.
642    ///
643    /// Fails ([`OreError::Random`]) if the OS random number generator could
644    /// not seed the nonce generator.
645    pub fn init_with(key: Protected<[u8; 16]>, options: Options) -> Result<Self, OreError> {
646        Self::init_with_rng(key, options, SafeRand::from_entropy()?)
647    }
648
649    /// [`Self::init_with`] with every nonce drawn from `seed`, so a test can
650    /// pin a full ciphertext's bytes. Never ship a seeded cipher: two values
651    /// encrypted under one seed share their nonces.
652    #[cfg(any(test, feature = "test-support"))]
653    pub fn init_seeded(
654        key: Protected<[u8; 16]>,
655        options: Options,
656        seed: [u8; 32],
657    ) -> Result<Self, OreError> {
658        use vitaminc_random::SeedableRng;
659        Self::init_with_rng(key, options, SafeRand::from_seed(seed))
660    }
661
662    fn init_with_rng(
663        key: Protected<[u8; 16]>,
664        options: Options,
665        rng: SafeRand,
666    ) -> Result<Self, OreError> {
667        options.check()?;
668        let k_salt = keys::salted(&keys::root(key.risky_ref(), &ROOT_LABEL), options.salt());
669        let k_acc = *keys::subkey(&k_salt, &ACC_KEY_LABEL);
670        Ok(Self {
671            k_acc,
672            options,
673            rng: Mutex::new(rng),
674        })
675    }
676
677    /// Draw one nonce; see the Bit6 sibling.
678    fn fill_nonce(&self, nonce: &mut [u8; NONCE_LEN]) {
679        let mut rng = self
680            .rng
681            .lock()
682            .unwrap_or_else(|poisoned| poisoned.into_inner());
683        match rng.try_fill_bytes(nonce) {
684            Ok(()) => {}
685            Err(never) => match never {},
686        }
687    }
688
689    /// The options this cipher was initialised with.
690    pub fn options(&self) -> &Options {
691        &self.options
692    }
693
694    /// The padding policy the string encryptors apply.
695    pub fn padding(&self) -> Padding {
696        self.options.padding()
697    }
698
699    /// Derive the per-block PRP from the accumulator's `PRP_STREAM` branch.
700    fn prp_at(&self, acc: &CmacAccumulator, n: u16) -> LemireFyPrp<DOMAIN> {
701        let mut stream = [0u8; STREAM_BLOCKS * 16];
702        for (c, chunk) in stream.chunks_mut(16).enumerate() {
703            chunk.copy_from_slice(&acc.finalize(&final_block(
704                Branch::PrpStream,
705                n,
706                c as u16,
707                WIDTH_BIT6,
708            )));
709        }
710        let prp = LemireFyPrp::<DOMAIN>::from_stream(&stream);
711        stream.zeroize();
712        prp
713    }
714
715    /// Full Left+Right ciphertext for raw symbols `x` (one 6-bit symbol per
716    /// element), for the tests: symbols a string never produces, over the
717    /// whole domain. A value `>= 64` returns [`OreError::PrpError`]. The
718    /// symbols are not padded, and the ciphertext is tagged
719    /// [`Padding::None`]. Not public; see the module docs.
720    #[cfg(test)]
721    pub(crate) fn encrypt_var(&self, x: &[u8]) -> Result<VarCipherText, OreError> {
722        stack::scrubbed(|| self.encrypt_blocks(&check_symbols(x)?, Padding::None))
723    }
724
725    /// Full ciphertext over blocks already known to be in the 6-bit
726    /// domain, without the stack scrub. Every caller runs it inside
727    /// [`stack::scrubbed`]: building a block's PRP and running the
728    /// accumulator leave their secrets in dead stack (see
729    /// `primitives::stack`).
730    /// `padding` is the policy `x` was padded under, for the header.
731    fn encrypt_blocks<B: AsRef<[u8]>>(
732        &self,
733        x: &Blocks6<B>,
734        padding: Padding,
735    ) -> Result<VarCipherText, OreError> {
736        let count = x.len();
737        if count > u16::MAX as usize {
738            return Err(OreError::TooManyBlocks);
739        }
740
741        let mut acc = CmacAccumulator::new(&self.k_acc);
742        let mut nonce = [0u8; NONCE_LEN];
743        self.fill_nonce(&mut nonce);
744        let hasher = FixedPiZ2Hash::new(HashKey::from_slice(&nonce));
745
746        let mut xt = Vec::with_capacity(count);
747        let mut f = Vec::with_capacity(count);
748        let mut blocks = Vec::with_capacity(count);
749
750        // Scratch for the RO_KEY tags (then the H outputs) of one block. Every
751        // entry is rewritten by the next block, so it is wiped once after the
752        // loop rather than once per block.
753        let mut ro = [AesBlock::default(); DOMAIN];
754
755        for n in 0..count {
756            let sym = x.symbol(n);
757            let n16 = n as u16;
758            let prp = self.prp_at(&acc, n16);
759            let permuted = prp.permute(sym).get();
760            xt.push(permuted);
761
762            // ro_key for every domain value; f[n] = ro(n, xt[n]).
763            for (j, blk) in ro.iter_mut().enumerate() {
764                blk.copy_from_slice(&acc.finalize(&final_block(
765                    Branch::RoKey,
766                    n16,
767                    j as u16,
768                    WIDTH_BIT6,
769                )));
770            }
771            // f[n] = ro(n, xt[n]), derived directly rather than read from `ro`
772            // at the secret index `permuted` (a 1 KiB table spans many cache
773            // lines). Same bytes as `encrypt_left_var`.
774            f.push(acc.finalize(&final_block(
775                Branch::RoKey,
776                n16,
777                permuted as u16,
778                WIDTH_BIT6,
779            )));
780
781            // right block = H-mask ⊕ indicator (trashes `ro`).
782            let mut rb = [0u8; RIGHT_LEN];
783            hasher.hash_all_into(&mut ro, &mut rb);
784            prp.indicator_mask_xor(sym, &mut rb);
785            blocks.push(rb);
786
787            acc.absorb(&prefix_block(n16, sym.get()));
788        }
789
790        // `ro` held key-derived RO_KEY tags (then H outputs) for the last block.
791        for blk in ro.iter_mut() {
792            blk.as_mut_slice().zeroize();
793        }
794
795        Ok(VarCipherText {
796            left: VarLeft { xt, f, padding },
797            right: VarRight { nonce, blocks },
798        })
799    }
800
801    /// Left-only ciphertext for raw symbols, for the tests; see
802    /// [`Self::encrypt_var`].
803    #[cfg(test)]
804    pub(crate) fn encrypt_left_var(&self, x: &[u8]) -> Result<VarLeft, OreError> {
805        stack::scrubbed(|| self.encrypt_left_blocks(&check_symbols(x)?, Padding::None))
806    }
807
808    /// Left-only ciphertext over blocks already known to be in the 6-bit
809    /// domain, without the stack scrub; see [`Self::encrypt_blocks`].
810    fn encrypt_left_blocks<B: AsRef<[u8]>>(
811        &self,
812        x: &Blocks6<B>,
813        padding: Padding,
814    ) -> Result<VarLeft, OreError> {
815        let count = x.len();
816        if count > u16::MAX as usize {
817            return Err(OreError::TooManyBlocks);
818        }
819
820        let mut acc = CmacAccumulator::new(&self.k_acc);
821        let mut xt = Vec::with_capacity(count);
822        let mut f = Vec::with_capacity(count);
823
824        for n in 0..count {
825            let sym = x.symbol(n);
826            let n16 = n as u16;
827            let prp = self.prp_at(&acc, n16);
828            let permuted = prp.permute(sym).get();
829            xt.push(permuted);
830            f.push(acc.finalize(&final_block(
831                Branch::RoKey,
832                n16,
833                permuted as u16,
834                WIDTH_BIT6,
835            )));
836            acc.absorb(&prefix_block(n16, sym.get()));
837        }
838        Ok(VarLeft { xt, f, padding })
839    }
840
841    /// Encrypt a string (UTF-8 bytes → MSB-first 6-bit blocks), padded under
842    /// the cipher's [`Padding`] policy: the text path over raw UTF-8, for
843    /// the tests. The sealed path, [`OreScheme::encrypt_plaintext`], runs
844    /// the same code over vitaminc's text encoding.
845    #[cfg(test)]
846    pub(crate) fn encrypt_str(&self, s: &str) -> Result<VarCipherText, OreError> {
847        self.encrypt_padded_bytes(s.as_bytes())
848    }
849
850    /// Left-only string ciphertext, padded and refused as
851    /// [`Self::encrypt_str`] does.
852    #[cfg(test)]
853    pub(crate) fn encrypt_left_str(&self, s: &str) -> Result<VarLeft, OreError> {
854        self.encrypt_left_padded_bytes(s.as_bytes())
855    }
856
857    /// Encrypt bytes already encoded so that byte order is value order,
858    /// padded with NUL bytes under the cipher's [`Padding`] policy and
859    /// refused past its ceiling: the text path.
860    ///
861    /// Errors:
862    /// - [`OreError::TrailingNul`] if the policy pads and the bytes end in
863    ///   NUL;
864    /// - [`OreError::ExceedsPadding`] if the policy is [`Padding::Fixed`]
865    ///   and the bytes are longer;
866    /// - [`OreError::TooManyBlocks`] if the padded bytes are longer than
867    ///   [`MAX_STR_BYTES`];
868    /// - [`OreError::TooLong`] if the bytes are longer than the cipher's
869    ///   [`Options::max_bytes`].
870    ///
871    /// The ciphertext reveals the length bucket under the policy (the
872    /// exact length for [`Padding::None`]), and comparisons reveal the
873    /// order and common-prefix length; see the module docs. Crate-private:
874    /// the only bytes this scheme takes arrive sealed.
875    pub(crate) fn encrypt_padded_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
876        stack::scrubbed(|| {
877            self.encrypt_blocks(
878                &padded_bytes_to_blocks(bytes, &self.options)?,
879                self.padding(),
880            )
881        })
882    }
883
884    /// [`Self::encrypt_padded_bytes`], for the left half.
885    pub(crate) fn encrypt_left_padded_bytes(&self, bytes: &[u8]) -> Result<VarLeft, OreError> {
886        stack::scrubbed(|| {
887            self.encrypt_left_blocks(
888                &padded_bytes_to_blocks(bytes, &self.options)?,
889                self.padding(),
890            )
891        })
892    }
893
894    /// Encrypt bytes already encoded so that byte order is value order,
895    /// unpadded: the path for a fixed-width plaintext and for vitaminc's
896    /// bytes target. The cipher's [`Options`] do not apply; the ciphertext
897    /// is tagged [`Padding::None`]. Bytes longer than [`MAX_STR_BYTES`]
898    /// return [`OreError::TooManyBlocks`] before any block is made. The
899    /// bytes are borrowed, so a large plaintext is never copied onto the
900    /// stack.
901    pub(crate) fn encrypt_unpadded_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
902        stack::scrubbed(|| self.encrypt_blocks(&bytes_to_blocks(bytes)?, Padding::None))
903    }
904
905    /// [`Self::encrypt_unpadded_bytes`], for the left half.
906    pub(crate) fn encrypt_left_unpadded_bytes(&self, bytes: &[u8]) -> Result<VarLeft, OreError> {
907        stack::scrubbed(|| self.encrypt_left_blocks(&bytes_to_blocks(bytes)?, Padding::None))
908    }
909}
910
911impl crate::sealed::Sealed for OreAes128Bit6Chained {}
912
913/// How a sealed plaintext goes in: bytes unpadded but refused past the
914/// ceiling, since their length is the caller's; a fixed-width target
915/// unpadded, with no ceiling, since its length is the target's; text, and
916/// any other target of no fixed width, padded under the cipher's options
917/// and refused past its ceiling. A variable-width target vitaminc adds
918/// later is padded until it is given a path of its own, so it can never
919/// go in revealing its exact length.
920enum Path {
921    Padded,
922    Unpadded,
923}
924
925impl OreAes128Bit6Chained {
926    fn path(&self, plaintext: &OrderPlaintext) -> Result<Path, OreError> {
927        match plaintext.target() {
928            OrderTarget::Bytes => {
929                if plaintext.bytes().risky_ref().len() > self.options.max_bytes().get() {
930                    return Err(OreError::TooLong);
931                }
932                Ok(Path::Unpadded)
933            }
934            target if target.width().is_some() => Ok(Path::Unpadded),
935            _ => Ok(Path::Padded),
936        }
937    }
938}
939
940impl OreScheme for OreAes128Bit6Chained {
941    /// Text is padded under the cipher's [`Options`]; bytes and
942    /// fixed-width plaintexts go in unpadded. Text and bytes are refused
943    /// past the cipher's ceiling ([`OreError::TooLong`]).
944    fn encrypt_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Term, OreError> {
945        let bytes = plaintext.bytes().risky_ref();
946        let ct = match self.path(plaintext)? {
947            Path::Padded => self.encrypt_padded_bytes(bytes)?,
948            Path::Unpadded => self.encrypt_unpadded_bytes(bytes)?,
949        };
950        Ok(Term::new(ct.to_bytes()))
951    }
952
953    fn encrypt_query_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Query, OreError> {
954        let bytes = plaintext.bytes().risky_ref();
955        let left = match self.path(plaintext)? {
956            Path::Padded => self.encrypt_left_padded_bytes(bytes)?,
957            Path::Unpadded => self.encrypt_left_unpadded_bytes(bytes)?,
958        };
959        Ok(Query::new(left.to_bytes()))
960    }
961
962    /// Compare two serialised full ciphertexts (lexicographic; shorter prefix
963    /// sorts first). `None` if either is not a well-formed ciphertext of this
964    /// scheme, or if they were padded under different policies.
965    fn compare_raw_slices(a: &[u8], b: &[u8]) -> Option<Ordering> {
966        let (ca, cb) = parse_pair(a, b)?;
967        if a.len() != total_len(ca) || b.len() != total_len(cb) {
968            return None;
969        }
970        if !symbols_in_domain(a, ca) || !symbols_in_domain(b, cb) {
971            return None;
972        }
973        // Only `a`'s left half and `b`'s right half are read (Lewi-Wu
974        // asymmetry); the left-only query path is `compare_left_to_full`.
975        Some(Self::compare_views(a, ca, b, cb))
976    }
977
978    /// Compare a left-only (query) ciphertext `left` — produced by
979    /// [`OreScheme::encrypt_query_plaintext`] — against a stored
980    /// full ciphertext `full`. This is the Lewi-Wu query path: a comparison
981    /// needs only the query's left half (`xt`/`f`) and the stored ciphertext's
982    /// right half, so the smaller left-only artifact suffices. This does not
983    /// make stored data safe at rest: a stored *full* ciphertext also carries
984    /// its left half, so two stored rows compare offline (see the module docs). Returns `left`'s order relative to
985    /// `full` (`Less` ⇒ the query plaintext sorts before the stored one).
986    /// `None` if either input is malformed, or if they were padded under
987    /// different policies.
988    fn compare_left_to_full(left: &[u8], full: &[u8]) -> Option<Ordering> {
989        let (cl, cf) = parse_pair(left, full)?;
990        // `left` is `header ‖ xt ‖ f` (no nonce/right); `full` is complete.
991        if left.len() != left_len(cl) || full.len() != total_len(cf) {
992            return None;
993        }
994        if !symbols_in_domain(left, cl) || !symbols_in_domain(full, cf) {
995            return None;
996        }
997        Some(Self::compare_views(left, cl, full, cf))
998    }
999}
1000
1001impl OreAes128Bit6Chained {
1002    /// Core comparator. `a` supplies the **left view** (`header ‖ xt ‖ f` — the
1003    /// layout is identical for a `VarLeft` and the left prefix of a full
1004    /// ciphertext, so the `xt_at`/`f_at` accessors work on either); `b` supplies
1005    /// the **right half**. Constant-time scan of the shared prefix; if it
1006    /// matches throughout, the shorter sorts first; otherwise the first
1007    /// differing block is resolved via the random oracle against `b`'s right
1008    /// block. `a` reads only `xt`/`f`, `b` reads `xt`/`f`/`nonce`/`right`.
1009    ///
1010    /// The scan reads every block of the shared prefix, including `b`'s right
1011    /// blocks, and latches the first differing block's `xt`, `f` and `right`
1012    /// as it goes; the resolution step works from the latched copies, so no
1013    /// load is indexed by the position of the first difference. A direct
1014    /// `right_at(b, cb, l)` after the scan was the one load whose cache state
1015    /// depended on `l` (the scan never needed the right blocks), and dudect
1016    /// measured it as a timing signal; see `docs/reviews/`.
1017    fn compare_views(a: &[u8], ca: usize, b: &[u8], cb: usize) -> Ordering {
1018        let min_count = ca.min(cb);
1019        let mut is_equal = Choice::from(1u8);
1020        let mut diff = FirstDiff::<RIGHT_LEN>::new();
1021        for n in 0..min_count {
1022            let differs = !xt_at(a, n).ct_eq(&xt_at(b, n)) | !f_at(a, ca, n).ct_eq(f_at(b, cb, n));
1023            // Set for exactly one `n`: the first differing block.
1024            let first = is_equal & differs;
1025            diff.latch(xt_at(a, n), f_at(a, ca, n), right_at(b, cb, n), first);
1026            is_equal.conditional_assign(&Choice::from(0u8), first);
1027        }
1028
1029        if bool::from(is_equal) {
1030            // Shared prefix matches throughout — shorter sorts first.
1031            return ca.cmp(&cb);
1032        }
1033
1034        let hasher = FixedPiZ2Hash::new(HashKey::from_slice(nonce_at(b, cb)));
1035        if diff.resolve(&hasher) == 1 {
1036            Ordering::Greater
1037        } else {
1038            Ordering::Less
1039        }
1040    }
1041}
1042
1043impl Drop for OreAes128Bit6Chained {
1044    fn drop(&mut self) {
1045        self.k_acc.zeroize();
1046    }
1047}
1048
1049// The marker for the wipe above, which vitaminc-ore asks of a space's engine.
1050impl ZeroizeOnDrop for OreAes128Bit6Chained {}
1051
1052/// Whether every `xt` symbol of a serialised view is inside the 64-element
1053/// domain. The comparator reads the right block at `xt[l]`; a symbol of 64 or
1054/// more would select no byte and silently read 0. `xt` is public, so this may
1055/// branch.
1056fn symbols_in_domain(view: &[u8], count: usize) -> bool {
1057    (0..count).all(|i| usize::from(xt_at(view, i)) < DOMAIN)
1058}
1059
1060/// Longest string, in UTF-8 bytes, whose block count fits the wire format's
1061/// `u16`: `⌈8n/6⌉ ≤ 65_535` gives `n ≤ 49_151`.
1062pub const MAX_STR_BYTES: usize = u16::MAX as usize * 6 / 8;
1063
1064const _: () = assert!(num_blocks_6bit(MAX_STR_BYTES) <= u16::MAX as usize);
1065const _: () = assert!(num_blocks_6bit(MAX_STR_BYTES + 1) > u16::MAX as usize);
1066
1067/// Check raw symbols for the tests' `encrypt_var` and `encrypt_left_var`,
1068/// refusing more blocks than the wire format can number *before* scanning
1069/// them.
1070#[cfg(test)]
1071fn check_symbols(x: &[u8]) -> Result<Blocks6<&[u8]>, OreError> {
1072    if x.len() > u16::MAX as usize {
1073        return Err(OreError::TooManyBlocks);
1074    }
1075    Blocks6::check(x)
1076}
1077
1078/// Decompose `s`, padded with NUL bytes under `padding`, into 6-bit blocks,
1079/// refusing a string too long for the policy or the wire format *before*
1080/// allocating or decomposing it. The decomposition is the whole plaintext
1081/// (it inverts), so the buffer is wiped when dropped. For the tests.
1082#[cfg(test)]
1083fn str_to_blocks(s: &str, options: &Options) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
1084    padded_bytes_to_blocks(s.as_bytes(), options)
1085}
1086
1087/// Decompose `bytes`, padded with NUL bytes under `options`, into 6-bit
1088/// blocks; see [`str_to_blocks`].
1089fn padded_bytes_to_blocks(
1090    bytes: &[u8],
1091    options: &Options,
1092) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
1093    if bytes.len() > MAX_STR_BYTES {
1094        return Err(OreError::TooManyBlocks);
1095    }
1096    let padding = options.padding();
1097    let padded = padding.padded_len(bytes.len())?;
1098    if bytes.len() > options.max_bytes().get() {
1099        return Err(OreError::TooLong);
1100    }
1101    if padding != Padding::None {
1102        refuse_trailing_nul(bytes)?;
1103    }
1104    Ok(Blocks6::decompose_padded(
1105        bytes,
1106        Zeroizing::new(vec![0u8; num_blocks_6bit(padded)]),
1107    ))
1108}
1109
1110/// Decompose `bytes` into 6-bit blocks, unpadded, refusing input too long
1111/// for the wire format *before* allocating or decomposing it. The fixed-
1112/// width and bytes path: the decomposition is the whole plaintext (it inverts), so
1113/// the buffer is wiped when dropped.
1114fn bytes_to_blocks(bytes: &[u8]) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
1115    if bytes.len() > MAX_STR_BYTES {
1116        return Err(OreError::TooManyBlocks);
1117    }
1118    Ok(Blocks6::decompose(
1119        bytes,
1120        Zeroizing::new(vec![0u8; num_blocks_6bit(bytes.len())]),
1121    ))
1122}
1123
1124/// Refuse a string that ends in NUL: padded, it would encrypt to the same
1125/// blocks as the string without it. One branch on the last byte, which
1126/// reveals only whether the encryption is refused.
1127///
1128/// The branch must be taken here, not left to the caller. Compiled to a
1129/// select, the check would hand back a `Result` that depends on the secret
1130/// byte, and every caller's `?` would branch on it. `black_box` on the error
1131/// cannot be hoisted above the condition, so the compiler has to branch,
1132/// and each path returns a constant. Kept out of line so that the one
1133/// branch, which the taint harness accepts, has a frame of its own
1134/// (`packages/ct-taint/valgrind.supp`).
1135#[inline(never)]
1136fn refuse_trailing_nul(bytes: &[u8]) -> Result<(), OreError> {
1137    if bytes.last() == Some(&0) {
1138        return Err(core::hint::black_box(OreError::TrailingNul));
1139    }
1140    Ok(())
1141}
1142
1143#[cfg(kani)]
1144mod kani_proofs {
1145    use super::*;
1146
1147    /// For every floor and every length the wire format can hold, the
1148    /// power-of-two rule never shrinks a string, stays within the wire
1149    /// limit, and maps a padded length to itself. Order and equality under
1150    /// padding need exactly the first of these (the module docs).
1151    #[kani::proof]
1152    fn power_of_two_never_shrinks_and_is_idempotent() {
1153        let min_bytes: u16 = kani::any();
1154        let len: usize = kani::any();
1155        kani::assume(len <= MAX_STR_BYTES);
1156        let padding = Padding::PowerOfTwo { min_bytes };
1157        if let Ok(padded) = padding.padded_len(len) {
1158            assert!(padded >= len);
1159            assert!(padded <= MAX_STR_BYTES);
1160            assert!(padded.is_power_of_two() || padded == usize::from(min_bytes));
1161            assert!(matches!(padding.padded_len(padded), Ok(again) if again == padded));
1162        }
1163    }
1164
1165    /// The power-of-two rule is monotone: a longer string never pads to a
1166    /// shorter length, so bucket sizes order like lengths.
1167    #[kani::proof]
1168    fn power_of_two_is_monotone() {
1169        let min_bytes: u16 = kani::any();
1170        let a: usize = kani::any();
1171        let b: usize = kani::any();
1172        kani::assume(a <= b && b <= MAX_STR_BYTES);
1173        let padding = Padding::PowerOfTwo { min_bytes };
1174        if let (Ok(pa), Ok(pb)) = (padding.padded_len(a), padding.padded_len(b)) {
1175            assert!(pa <= pb);
1176        }
1177    }
1178
1179    /// A fixed length accepts exactly the strings that fit, and pads them
1180    /// all to that length.
1181    #[kani::proof]
1182    fn fixed_pads_everything_that_fits() {
1183        let max_bytes: NonZeroU16 = kani::any();
1184        let len: usize = kani::any();
1185        kani::assume(len <= MAX_STR_BYTES);
1186        let padding = Padding::Fixed { max_bytes };
1187        let max_bytes = max_bytes.get();
1188        match padding.padded_len(len) {
1189            Ok(padded) => {
1190                assert!(len <= usize::from(max_bytes) && padded == usize::from(max_bytes))
1191            }
1192            Err(OreError::ExceedsPadding) => assert!(len > usize::from(max_bytes)),
1193            Err(OreError::TooManyBlocks) => assert!(usize::from(max_bytes) > MAX_STR_BYTES),
1194            Err(_) => assert!(false),
1195        }
1196    }
1197}
1198
1199#[cfg(test)]
1200mod compat_vectors;
1201
1202#[cfg(test)]
1203mod tests {
1204    use super::*;
1205    use crate::testing::{
1206        bytes_pt, ceiling, fixed_key, fixed_padding, i128_pt, salt, text_pt, u128_pt,
1207    };
1208
1209    fn ore() -> OreAes128Bit6Chained {
1210        OreAes128Bit6Chained::init(fixed_key(0x11)).unwrap()
1211    }
1212
1213    fn ore_with(padding: Padding) -> OreAes128Bit6Chained {
1214        OreAes128Bit6Chained::init_with(fixed_key(0x11), Options::default().with_padding(padding))
1215            .unwrap()
1216    }
1217
1218    /// `ore_with`, with its own ceiling.
1219    fn ore_with_max(padding: Padding, max_bytes: usize) -> OreAes128Bit6Chained {
1220        let options = Options::default()
1221            .with_padding(padding)
1222            .with_max_bytes(ceiling(max_bytes));
1223        OreAes128Bit6Chained::init_with(fixed_key(0x11), options).unwrap()
1224    }
1225
1226    /// The ceiling: the default is 1024 bytes, a cipher can set its own, a
1227    /// fixed padding length is also a ceiling, and one the policy cannot
1228    /// pad is refused at init.
1229    #[test]
1230    fn strings_over_the_ceiling_are_refused() {
1231        type C = OreAes128Bit6Chained;
1232        let c = ore();
1233        assert_eq!(c.options().max_bytes(), DEFAULT_MAX_STR_BYTES);
1234        assert!(c.encrypt_str(&"a".repeat(1024)).is_ok());
1235        assert!(matches!(
1236            c.encrypt_str(&"a".repeat(1025)),
1237            Err(OreError::TooLong)
1238        ));
1239        assert!(matches!(
1240            c.encrypt_left_str(&"a".repeat(1025)),
1241            Err(OreError::TooLong)
1242        ));
1243
1244        let small = C::init_with(
1245            fixed_key(0x11),
1246            Options::default().with_max_bytes(ceiling(100)),
1247        )
1248        .unwrap();
1249        assert!(small.encrypt_str(&"a".repeat(100)).is_ok());
1250        assert!(matches!(
1251            small.encrypt_str(&"a".repeat(101)),
1252            Err(OreError::TooLong)
1253        ));
1254        // A refused string costs nothing: the ceiling is checked before
1255        // any block is derived, and under `None` too.
1256        let unpadded = C::init_with(
1257            fixed_key(0x11),
1258            Options::default()
1259                .with_padding(Padding::None)
1260                .with_max_bytes(ceiling(8)),
1261        )
1262        .unwrap();
1263        assert!(unpadded.encrypt_str("12345678").is_ok());
1264        assert!(matches!(
1265            unpadded.encrypt_str("123456789"),
1266            Err(OreError::TooLong)
1267        ));
1268
1269        // Under a fixed length the lower of the two applies, and a string
1270        // past the fixed length is still `ExceedsPadding`.
1271        let fixed = ore_with(fixed_padding(200));
1272        assert_eq!(fixed.options().max_bytes().get(), 200);
1273        assert!(fixed.encrypt_str(&"a".repeat(200)).is_ok());
1274        assert!(matches!(
1275            fixed.encrypt_str(&"a".repeat(201)),
1276            Err(OreError::ExceedsPadding)
1277        ));
1278        let fixed_low = C::init_with(
1279            fixed_key(0x11),
1280            Options::default()
1281                .with_padding(fixed_padding(200))
1282                .with_max_bytes(ceiling(50)),
1283        )
1284        .unwrap();
1285        assert_eq!(fixed_low.options().max_bytes().get(), 50);
1286        assert!(matches!(
1287            fixed_low.encrypt_str(&"a".repeat(51)),
1288            Err(OreError::TooLong)
1289        ));
1290        // The fixed length still sets the ciphertext size.
1291        assert_eq!(
1292            fixed_low.encrypt_str("abc").unwrap().to_bytes().len(),
1293            total_len(num_blocks_6bit(200))
1294        );
1295
1296        // Refused at init: the longest string would pad past the wire
1297        // limit. (A ceiling of 0 does not compile.)
1298        assert!(matches!(
1299            C::init_with(
1300                fixed_key(0x11),
1301                Options::default().with_max_bytes(ceiling(32769))
1302            ),
1303            Err(OreError::InitFailed)
1304        ));
1305        assert!(C::init_with(
1306            fixed_key(0x11),
1307            Options::default().with_max_bytes(ceiling(32768))
1308        )
1309        .is_ok());
1310        assert!(C::init_with(
1311            fixed_key(0x11),
1312            Options::default()
1313                .with_padding(Padding::None)
1314                .with_max_bytes(ceiling(MAX_STR_BYTES))
1315        )
1316        .is_ok());
1317        assert!(matches!(
1318            C::init_with(
1319                fixed_key(0x11),
1320                Options::default()
1321                    .with_padding(Padding::None)
1322                    .with_max_bytes(ceiling(MAX_STR_BYTES + 1))
1323            ),
1324            Err(OreError::InitFailed)
1325        ));
1326    }
1327
1328    /// One of each kind of policy, with a floor and a fixed length that the
1329    /// tests' strings cross.
1330    const POLICIES: [Padding; 4] = [
1331        Padding::None,
1332        Padding::PowerOfTwo { min_bytes: 16 },
1333        Padding::PowerOfTwo { min_bytes: 0 },
1334        fixed_padding(48),
1335    ];
1336
1337    /// Symbols passed straight to `encrypt_var` / `encrypt_left_var` are
1338    /// checked: a value outside the 6-bit domain is refused, and in-domain
1339    /// symbols encrypt exactly as the string path's decomposition does.
1340    #[test]
1341    fn raw_symbols_are_checked() {
1342        let c = ore();
1343        assert!(matches!(
1344            c.encrypt_var(&[1, 64, 2]),
1345            Err(OreError::PrpError(_))
1346        ));
1347        assert!(matches!(
1348            c.encrypt_left_var(&[1, 64, 2]),
1349            Err(OreError::PrpError(_))
1350        ));
1351
1352        let unpadded = ore_with(Padding::None);
1353        let blocks =
1354            str_to_blocks("alice", &Options::default().with_padding(Padding::None)).unwrap();
1355        assert_eq!(
1356            unpadded
1357                .encrypt_left_var(blocks.as_bytes())
1358                .unwrap()
1359                .to_bytes(),
1360            unpadded.encrypt_left_str("alice").unwrap().to_bytes()
1361        );
1362    }
1363
1364    /// `init` is the empty salt; another salt gives unrelated ciphertexts,
1365    /// and the same salt reproduces them. The two salts have equal
1366    /// lengths, so the length prefix alone cannot separate them.
1367    #[test]
1368    fn salt_separates_keys() {
1369        type C = OreAes128Bit6Chained;
1370        let plain = C::init(fixed_key(0x42)).unwrap();
1371        let empty = C::init_with_salt(fixed_key(0x42), &Context::empty()).unwrap();
1372        let col_a = C::init_with_salt(fixed_key(0x42), &salt(b"users.email")).unwrap();
1373        let col_a2 = C::init_with_salt(fixed_key(0x42), &salt(b"users.email")).unwrap();
1374        let col_b = C::init_with_salt(fixed_key(0x42), &salt(b"users.phone")).unwrap();
1375        let col_a_opts = C::init_with(
1376            fixed_key(0x42),
1377            Options::default().with_salt(&salt(b"users.email")),
1378        )
1379        .unwrap();
1380        assert_eq!(col_a.options().salt(), b"users.email");
1381
1382        let left = |c: &C| c.encrypt_left_str("alice").unwrap().to_bytes();
1383        assert_eq!(left(&plain), left(&empty));
1384        assert_eq!(left(&col_a), left(&col_a2));
1385        assert_eq!(left(&col_a), left(&col_a_opts));
1386        assert_ne!(left(&plain), left(&col_a));
1387        assert_ne!(left(&col_a), left(&col_b));
1388
1389        let a = col_a.encrypt_str("alice").unwrap().to_bytes();
1390        let b = col_b.encrypt_str("alice").unwrap().to_bytes();
1391        assert_ne!(C::compare_raw_slices(&a, &b), Some(Ordering::Equal));
1392        assert_eq!(
1393            C::compare_raw_slices(&a, &col_a2.encrypt_str("alice").unwrap().to_bytes()),
1394            Some(Ordering::Equal)
1395        );
1396        // Fixed-width plaintexts too.
1397        assert_ne!(
1398            col_a.encrypt_query_plaintext(&u128_pt(7)).unwrap(),
1399            col_b.encrypt_query_plaintext(&u128_pt(7)).unwrap()
1400        );
1401    }
1402
1403    /// A cross-salt comparison can answer `Equal`: the unpadded empty
1404    /// string (a 0.9 term; vitaminc's marker byte means 0.10 makes none)
1405    /// has no blocks, so there is no key material to differ.
1406    /// The docs therefore promise nothing about cross-salt results.
1407    #[test]
1408    fn cross_salt_empty_strings_compare_equal() {
1409        type C = OreAes128Bit6Chained;
1410        let options = Options::default().with_padding(Padding::None);
1411        let a = C::init_with(
1412            fixed_key(0x42),
1413            options.clone().with_salt(&salt(b"users.email")),
1414        )
1415        .unwrap();
1416        let b = C::init_with(fixed_key(0x42), options.with_salt(&salt(b"users.phone"))).unwrap();
1417        let a = a.encrypt_str("").unwrap().to_bytes();
1418        let b = b.encrypt_str("").unwrap().to_bytes();
1419        assert_eq!(C::compare_raw_slices(&a, &b), Some(Ordering::Equal));
1420    }
1421
1422    #[test]
1423    fn strings_over_the_wire_limit_are_rejected() {
1424        let c = ore();
1425        let too_long = "a".repeat(MAX_STR_BYTES + 1);
1426        assert!(matches!(
1427            c.encrypt_str(&too_long),
1428            Err(OreError::TooManyBlocks)
1429        ));
1430        assert!(matches!(
1431            c.encrypt_left_str(&too_long),
1432            Err(OreError::TooManyBlocks)
1433        ));
1434    }
1435
1436    /// Raw symbols over the wire limit are refused on their length, before
1437    /// any symbol is checked: out-of-domain symbols give `TooManyBlocks`,
1438    /// not `PrpError`.
1439    #[test]
1440    fn raw_symbols_over_the_wire_limit_are_rejected() {
1441        let c = ore();
1442        let too_many = vec![64u8; u16::MAX as usize + 1];
1443        assert!(matches!(
1444            c.encrypt_var(&too_many),
1445            Err(OreError::TooManyBlocks)
1446        ));
1447        assert!(matches!(
1448            c.encrypt_left_var(&too_many),
1449            Err(OreError::TooManyBlocks)
1450        ));
1451    }
1452
1453    #[test]
1454    fn comparators_reject_out_of_domain_symbols() {
1455        let c = ore();
1456        let a = c.encrypt_str("apple").unwrap().to_bytes();
1457        let b = c.encrypt_str("apricot").unwrap().to_bytes();
1458        let q = c.encrypt_left_str("apple").unwrap().to_bytes();
1459        assert!(OreAes128Bit6Chained::compare_raw_slices(&a, &b).is_some());
1460
1461        // First `xt` byte follows the header.
1462        let mut bad = a.clone();
1463        bad[HEADER_LEN] = DOMAIN as u8;
1464        let mut bad_q = q.clone();
1465        bad_q[HEADER_LEN] = DOMAIN as u8;
1466
1467        type C = OreAes128Bit6Chained;
1468        assert_eq!(C::compare_raw_slices(&bad, &b), None);
1469        assert_eq!(C::compare_raw_slices(&b, &bad), None);
1470        assert_eq!(C::compare_left_to_full(&bad_q, &b), None);
1471        assert_eq!(C::compare_left_to_full(&q, &bad), None);
1472    }
1473
1474    fn cmp(c: &OreAes128Bit6Chained, a: &str, b: &str) -> Ordering {
1475        let ca = c.encrypt_str(a).unwrap().to_bytes();
1476        let cb = c.encrypt_str(b).unwrap().to_bytes();
1477        OreAes128Bit6Chained::compare_raw_slices(&ca, &cb).unwrap()
1478    }
1479
1480    #[test]
1481    fn string_total_order_matches_lexicographic() {
1482        // Includes shared prefixes of different lengths, beyond 14 blocks,
1483        // across power-of-two buckets (16 and 17 bytes, 32 and 33), within
1484        // one (43 and 44), and interior NULs, which padding allows.
1485        let words = [
1486            "",
1487            "a",
1488            "a\0b",
1489            "ab",
1490            "abc",
1491            "abd",
1492            "ac",
1493            "b",
1494            "banana",
1495            "bananas",
1496            "sixteen bytes ok",
1497            "sixteen bytes ok!",
1498            "thirty-two bytes, on the nose!!!",
1499            "thirty-two bytes, on the nose!!!!",
1500            "the quick brown fox jumps over the lazy dog",
1501            "the quick brown fox jumps over the lazy dog.",
1502            "zzz",
1503        ];
1504        for padding in POLICIES {
1505            let c = ore_with(padding);
1506            for &a in &words {
1507                for &b in &words {
1508                    assert_eq!(
1509                        cmp(&c, a, b),
1510                        a.cmp(b),
1511                        "order mismatch for {a:?} vs {b:?} under {padding:?}"
1512                    );
1513                }
1514            }
1515        }
1516    }
1517
1518    #[test]
1519    fn power_of_two_lengths() {
1520        let p = |min_bytes, len| Padding::PowerOfTwo { min_bytes }.padded_len(len).unwrap();
1521        // Everything up to the floor is one bucket; above it, each bucket
1522        // doubles.
1523        for len in 0..=16 {
1524            assert_eq!(p(16, len), 16);
1525        }
1526        assert_eq!(p(16, 17), 32);
1527        assert_eq!(p(16, 32), 32);
1528        assert_eq!(p(16, 33), 64);
1529        assert_eq!(p(16, 1000), 1024);
1530        assert_eq!(p(16, 1025), 2048);
1531        // Without a floor the empty string stays empty, and a floor need
1532        // not be a power of two: it is one bucket below the powers of two.
1533        assert_eq!(p(0, 0), 0);
1534        assert_eq!(p(0, 1), 1);
1535        assert_eq!(p(0, 3), 4);
1536        assert_eq!(p(24, 20), 24);
1537        assert_eq!(p(24, 24), 24);
1538        assert_eq!(p(24, 25), 32);
1539        // The last bucket within the wire limit is 32768 bytes; longer
1540        // strings would pad past it.
1541        assert_eq!(p(16, 32768), 32768);
1542        for len in [32769, MAX_STR_BYTES] {
1543            assert!(matches!(
1544                Padding::PowerOfTwo { min_bytes: 16 }.padded_len(len),
1545                Err(OreError::TooManyBlocks)
1546            ));
1547        }
1548    }
1549
1550    #[test]
1551    fn padded_ciphertexts_reveal_only_the_bucket() {
1552        let c = ore();
1553        let size = |s: &str| c.encrypt_str(s).unwrap().to_bytes().len();
1554        let left_size = |s: &str| c.encrypt_left_str(s).unwrap().to_bytes().len();
1555        // Everything up to the 16-byte floor is one bucket of 22 blocks.
1556        for s in ["", "a", "abc", "sixteen bytes ok"] {
1557            assert_eq!(size(s), total_len(num_blocks_6bit(16)), "{s:?}");
1558            assert_eq!(left_size(s), left_len(num_blocks_6bit(16)), "{s:?}");
1559        }
1560        // 17 and 32 bytes share the next bucket; 33 starts another.
1561        assert_eq!(size("seventeen bytes!!"), total_len(num_blocks_6bit(32)));
1562        assert_eq!(
1563            size("thirty-two bytes, on the nose!!!"),
1564            total_len(num_blocks_6bit(32))
1565        );
1566        assert_eq!(
1567            size("thirty-two bytes, on the nose!!!!"),
1568            total_len(num_blocks_6bit(64))
1569        );
1570
1571        let fixed = ore_with(fixed_padding(48));
1572        for s in ["", "abc", &"x".repeat(48)] {
1573            assert_eq!(
1574                fixed.encrypt_str(s).unwrap().to_bytes().len(),
1575                total_len(num_blocks_6bit(48))
1576            );
1577        }
1578    }
1579
1580    #[test]
1581    fn padded_strings_must_not_end_in_nul() {
1582        for padding in POLICIES {
1583            let c = ore_with(padding);
1584            let full = c.encrypt_str("a\0");
1585            let left = c.encrypt_left_str("a\0");
1586            if padding == Padding::None {
1587                // Unpadded, the length tells "a\0" from "a".
1588                assert_eq!(cmp(&c, "a", "a\0"), Ordering::Less);
1589            } else {
1590                assert!(matches!(full, Err(OreError::TrailingNul)), "{:?}", padding);
1591                assert!(matches!(left, Err(OreError::TrailingNul)), "{:?}", padding);
1592            }
1593            // An interior NUL is fine either way.
1594            assert!(c.encrypt_str("a\0b").is_ok());
1595        }
1596    }
1597
1598    #[test]
1599    fn fixed_padding_refuses_longer_strings() {
1600        let c = ore_with(fixed_padding(8));
1601        assert!(c.encrypt_str("12345678").is_ok());
1602        assert!(matches!(
1603            c.encrypt_str("123456789"),
1604            Err(OreError::ExceedsPadding)
1605        ));
1606        assert!(matches!(
1607            c.encrypt_left_str("123456789"),
1608            Err(OreError::ExceedsPadding)
1609        ));
1610    }
1611
1612    #[test]
1613    fn padding_policies_past_the_wire_limit_are_refused() {
1614        type C = OreAes128Bit6Chained;
1615        let max = MAX_STR_BYTES as u16;
1616        let with = |padding| Options::default().with_padding(padding);
1617        assert!(C::init_with(fixed_key(0x11), with(fixed_padding(max))).is_ok());
1618        assert!(matches!(
1619            C::init_with(fixed_key(0x11), with(fixed_padding(max + 1))),
1620            Err(OreError::InitFailed)
1621        ));
1622        // A floor at the limit is allowed, one past it is not.
1623        assert!(C::init_with(
1624            fixed_key(0x11),
1625            with(Padding::PowerOfTwo { min_bytes: max })
1626        )
1627        .is_ok());
1628        assert!(matches!(
1629            C::init_with(
1630                fixed_key(0x11),
1631                with(Padding::PowerOfTwo { min_bytes: max + 1 })
1632            ),
1633            Err(OreError::InitFailed)
1634        ));
1635        // Under the default policy, a string past the last power of two
1636        // within the limit would pad past it, and is refused before any
1637        // work is done (and before the ceiling is consulted).
1638        let c = ore_with_max(Padding::default(), 32768);
1639        for len in [32769, MAX_STR_BYTES] {
1640            assert!(matches!(
1641                c.encrypt_str(&"a".repeat(len)),
1642                Err(OreError::TooManyBlocks)
1643            ));
1644        }
1645    }
1646
1647    /// Ciphertexts under different policies do not compare: an unpadded and
1648    /// a padded "abc" would compare unequal.
1649    #[test]
1650    fn comparators_refuse_mixed_policies() {
1651        type C = OreAes128Bit6Chained;
1652        for pa in POLICIES {
1653            for pb in POLICIES {
1654                let a = ore_with(pa);
1655                let b = ore_with(pb);
1656                let full_a = a.encrypt_str("abc").unwrap().to_bytes();
1657                let full_b = b.encrypt_str("abc").unwrap().to_bytes();
1658                let left_a = a.encrypt_left_str("abc").unwrap().to_bytes();
1659                let expected = (pa == pb).then_some(Ordering::Equal);
1660                assert_eq!(C::compare_raw_slices(&full_a, &full_b), expected);
1661                assert_eq!(C::compare_left_to_full(&left_a, &full_b), expected);
1662            }
1663        }
1664    }
1665
1666    #[test]
1667    fn padding_tag_round_trips_and_rejects_unknown_kinds() {
1668        let c = ore();
1669        let bytes = c.encrypt_str("abc").unwrap().to_bytes();
1670        let ct = VarCipherText::from_slice(&bytes).unwrap();
1671        assert_eq!(ct.padding(), Padding::default());
1672        assert_eq!(
1673            c.encrypt_left_str("abc").unwrap().padding(),
1674            Padding::default()
1675        );
1676
1677        type C = OreAes128Bit6Chained;
1678        let tag = WIRE_HEADER_LEN;
1679        let tampered = |at: usize, value: u8| {
1680            let mut t = bytes.clone();
1681            t[at] = value;
1682            t
1683        };
1684        for bad in [
1685            tampered(tag, 3),        // unknown kind
1686            tampered(tag, 0),        // Padding::None with a non-zero length
1687            tampered(tag + 1, 0xff), // a floor past the wire limit
1688        ] {
1689            assert!(VarCipherText::from_slice(&bad).is_err());
1690            assert_eq!(C::compare_raw_slices(&bad, &bad), None);
1691        }
1692    }
1693
1694    /// Every string over {NUL, 'a', 'b'} of up to four bytes that a padding
1695    /// policy accepts (no trailing NUL), plus strings at the 16- and 32-byte
1696    /// bucket edges, each also with a two-byte character straddling the edge.
1697    fn small_alphabet_strings() -> Vec<String> {
1698        let mut out = vec![String::new()];
1699        let mut layer = vec![String::new()];
1700        for _ in 0..4 {
1701            layer = layer
1702                .iter()
1703                .flat_map(|s| ["\0", "a", "b"].iter().map(move |c| format!("{s}{c}")))
1704                .collect();
1705            out.extend(layer.iter().cloned());
1706        }
1707        out.retain(|s| !s.ends_with('\0'));
1708        for n in [15, 16, 17, 31, 32, 33] {
1709            out.push("a".repeat(n));
1710            // `n - 1` ASCII bytes and a two-byte character: `n + 1` bytes.
1711            out.push(format!("{}é", "a".repeat(n - 1)));
1712        }
1713        out
1714    }
1715
1716    /// Both comparators reproduce byte order over every pair of the small
1717    /// alphabet's strings, under every policy: interior NULs, prefixes that
1718    /// end at every block position, and both sides of each bucket edge.
1719    #[test]
1720    fn small_alphabet_total_order_under_every_policy() {
1721        type C = OreAes128Bit6Chained;
1722        let strings = small_alphabet_strings();
1723        for padding in POLICIES {
1724            let c = ore_with(padding);
1725            let fulls: Vec<Vec<u8>> = strings
1726                .iter()
1727                .map(|s| c.encrypt_str(s).unwrap().to_bytes())
1728                .collect();
1729            let lefts: Vec<Vec<u8>> = strings
1730                .iter()
1731                .map(|s| c.encrypt_left_str(s).unwrap().to_bytes())
1732                .collect();
1733            for (i, a) in strings.iter().enumerate() {
1734                for (j, b) in strings.iter().enumerate() {
1735                    let expected = Some(a.as_bytes().cmp(b.as_bytes()));
1736                    assert_eq!(
1737                        C::compare_raw_slices(&fulls[i], &fulls[j]),
1738                        expected,
1739                        "full {a:?} vs {b:?} under {padding:?}"
1740                    );
1741                    assert_eq!(
1742                        C::compare_left_to_full(&lefts[i], &fulls[j]),
1743                        expected,
1744                        "left {a:?} vs {b:?} under {padding:?}"
1745                    );
1746                }
1747            }
1748        }
1749    }
1750
1751    /// Under the default policy, every length from 0 to 70 bytes lands in
1752    /// its bucket, and each string sorts below the next longer one and
1753    /// below itself with one more byte, across every bucket edge.
1754    #[test]
1755    fn default_buckets_at_every_length() {
1756        type C = OreAes128Bit6Chained;
1757        let c = ore();
1758        let bucket = |n: usize| if n <= 16 { 16 } else { n.next_power_of_two() };
1759        let mut prev: Option<Vec<u8>> = None;
1760        for n in 0..=70 {
1761            let s = "a".repeat(n);
1762            let full = c.encrypt_str(&s).unwrap().to_bytes();
1763            let left = c.encrypt_left_str(&s).unwrap().to_bytes();
1764            assert_eq!(
1765                full.len(),
1766                total_len(num_blocks_6bit(bucket(n))),
1767                "{n} bytes"
1768            );
1769            assert_eq!(
1770                left.len(),
1771                left_len(num_blocks_6bit(bucket(n))),
1772                "{n} bytes"
1773            );
1774            let longer = c.encrypt_str(&format!("{s}b")).unwrap().to_bytes();
1775            assert_eq!(
1776                C::compare_raw_slices(&full, &longer),
1777                Some(Ordering::Less),
1778                "{n} bytes"
1779            );
1780            assert_eq!(
1781                C::compare_left_to_full(&left, &longer),
1782                Some(Ordering::Less),
1783                "{n} bytes"
1784            );
1785            if let Some(prev) = &prev {
1786                assert_eq!(
1787                    C::compare_raw_slices(prev, &full),
1788                    Some(Ordering::Less),
1789                    "{n} bytes"
1790                );
1791            }
1792            prev = Some(full);
1793        }
1794    }
1795
1796    /// Two policies that pad a string to the same length produce the same
1797    /// blocks, since padding is only NUL extension, and the tag alone keeps
1798    /// their ciphertexts from comparing.
1799    #[test]
1800    fn same_blocks_under_different_policies_do_not_compare() {
1801        type C = OreAes128Bit6Chained;
1802        let cases = [
1803            (
1804                Padding::PowerOfTwo { min_bytes: 16 },
1805                fixed_padding(16),
1806                "sixteen bytes ok",
1807            ),
1808            (
1809                Padding::PowerOfTwo { min_bytes: 16 },
1810                Padding::PowerOfTwo { min_bytes: 8 },
1811                "seventeen bytes!!",
1812            ),
1813            (
1814                fixed_padding(4),
1815                Padding::PowerOfTwo { min_bytes: 0 },
1816                "abc",
1817            ),
1818        ];
1819        for (pa, pb, s) in cases {
1820            let (a, b) = (ore_with(pa), ore_with(pb));
1821            let left_a = a.encrypt_left_str(s).unwrap().to_bytes();
1822            let left_b = b.encrypt_left_str(s).unwrap().to_bytes();
1823            assert_eq!(
1824                left_a[..WIRE_HEADER_LEN],
1825                left_b[..WIRE_HEADER_LEN],
1826                "{s:?}"
1827            );
1828            assert_ne!(left_a[..HEADER_LEN], left_b[..HEADER_LEN], "{s:?}");
1829            assert_eq!(left_a[HEADER_LEN..], left_b[HEADER_LEN..], "{s:?}");
1830            let full_b = b.encrypt_str(s).unwrap().to_bytes();
1831            assert_eq!(C::compare_left_to_full(&left_a, &full_b), None, "{s:?}");
1832            let full_a = a.encrypt_str(s).unwrap().to_bytes();
1833            assert_eq!(C::compare_raw_slices(&full_a, &full_b), None, "{s:?}");
1834        }
1835    }
1836
1837    /// The longest fixed length the wire format allows, 65535 blocks,
1838    /// encrypts, round trips and compares. About ten seconds unoptimised,
1839    /// so it runs only on request:
1840    /// `cargo test -p ore-rs fixed_padding_at_the_wire_limit -- --ignored`.
1841    #[test]
1842    #[ignore = "65535-block ciphertexts: about ten seconds unoptimised"]
1843    fn fixed_padding_at_the_wire_limit() {
1844        type C = OreAes128Bit6Chained;
1845        let c = ore_with_max(fixed_padding(MAX_STR_BYTES as u16), MAX_STR_BYTES);
1846        let full = c.encrypt_str("alice").unwrap().to_bytes();
1847        assert_eq!(full.len(), total_len(u16::MAX as usize));
1848        assert_eq!(VarCipherText::from_slice(&full).unwrap().to_bytes(), full);
1849        let left = c.encrypt_left_str("alicf").unwrap().to_bytes();
1850        assert_eq!(left.len(), left_len(u16::MAX as usize));
1851        assert_eq!(
1852            C::compare_left_to_full(&left, &full),
1853            Some(Ordering::Greater)
1854        );
1855    }
1856
1857    /// A header's block count must be one its policy can produce.
1858    #[test]
1859    fn policies_admit_only_their_own_block_counts() {
1860        let blocks = num_blocks_6bit;
1861        let pow16 = Padding::PowerOfTwo { min_bytes: 16 };
1862        for count in [blocks(16), blocks(32), blocks(64), blocks(32768)] {
1863            assert!(pow16.admits_count(count), "{}", count);
1864        }
1865        for count in [0, blocks(8), blocks(16) + 1, blocks(48), blocks(65536)] {
1866            assert!(!pow16.admits_count(count), "{}", count);
1867        }
1868        // A floor that is not a power of two is a bucket of its own.
1869        let pow24 = Padding::PowerOfTwo { min_bytes: 24 };
1870        assert!(pow24.admits_count(blocks(24)));
1871        assert!(pow24.admits_count(blocks(32)));
1872        assert!(!pow24.admits_count(blocks(16)));
1873        // Without a floor: 0, 1, 2, 4, 8, ... bytes.
1874        let pow0 = Padding::PowerOfTwo { min_bytes: 0 };
1875        for len in [0, 1, 2, 4, 8, 1024] {
1876            assert!(pow0.admits_count(blocks(len)), "{}", len);
1877        }
1878        assert!(!pow0.admits_count(blocks(3)));
1879        let fixed = fixed_padding(48);
1880        assert!(fixed.admits_count(blocks(48)));
1881        assert!(!fixed.admits_count(blocks(48) - 1));
1882        for count in [0, 1, 1000, u16::MAX as usize] {
1883            assert!(Padding::None.admits_count(count));
1884        }
1885    }
1886
1887    /// A ciphertext whose tag names a policy that cannot produce its block
1888    /// count was made by no cipher, and is refused: rewriting an unpadded
1889    /// ciphertext's tag does not smuggle it in among padded ciphertexts.
1890    #[test]
1891    fn parsers_reject_counts_the_policy_cannot_produce() {
1892        type C = OreAes128Bit6Chained;
1893        let retag = |bytes: &[u8], padding: Padding| {
1894            let mut t = bytes.to_vec();
1895            t[WIRE_HEADER_LEN..HEADER_LEN].copy_from_slice(&padding.to_wire());
1896            t
1897        };
1898        // 4 blocks, claimed to be padded to 16 bytes (22 blocks).
1899        let unpadded = ore_with(Padding::None)
1900            .encrypt_str("abc")
1901            .unwrap()
1902            .to_bytes();
1903        let forged = retag(&unpadded, Padding::default());
1904        assert!(VarCipherText::from_slice(&forged).is_err());
1905        let genuine = ore().encrypt_str("abc").unwrap().to_bytes();
1906        assert_eq!(C::compare_raw_slices(&forged, &genuine), None);
1907        assert_eq!(C::compare_raw_slices(&forged, &forged), None);
1908        let left = retag(
1909            &ore_with(Padding::None)
1910                .encrypt_left_str("abc")
1911                .unwrap()
1912                .to_bytes(),
1913            Padding::default(),
1914        );
1915        assert_eq!(C::compare_left_to_full(&left, &genuine), None);
1916
1917        // 22 blocks claimed as a fixed 48 bytes (64 blocks): refused. As a
1918        // fixed 16 bytes (22 blocks): a count that policy produces, accepted.
1919        assert!(VarCipherText::from_slice(&retag(&genuine, fixed_padding(48))).is_err());
1920        assert!(VarCipherText::from_slice(&retag(&genuine, fixed_padding(16))).is_ok());
1921
1922        // A fixed length of 0 is no policy: refused even on the one
1923        // ciphertext it could describe, the empty string's.
1924        let mut empty = ore_with(Padding::None).encrypt_str("").unwrap().to_bytes();
1925        assert!(VarCipherText::from_slice(&empty).is_ok());
1926        empty[WIRE_HEADER_LEN..HEADER_LEN].copy_from_slice(&[2, 0, 0]);
1927        assert!(VarCipherText::from_slice(&empty).is_err());
1928        assert_eq!(C::compare_raw_slices(&empty, &empty), None);
1929    }
1930
1931    #[test]
1932    fn equality_same_plaintext_across_nonces() {
1933        let c = ore();
1934        let a = c.encrypt_str("hello world").unwrap().to_bytes();
1935        let b = c.encrypt_str("hello world").unwrap().to_bytes();
1936        assert_ne!(a, b, "nonces should differ"); // different nonce streams
1937        assert_eq!(
1938            OreAes128Bit6Chained::compare_raw_slices(&a, &b),
1939            Some(Ordering::Equal)
1940        );
1941    }
1942
1943    #[test]
1944    fn serialize_roundtrip() {
1945        let c = ore();
1946        let ct = c.encrypt_str("roundtrip me").unwrap();
1947        let bytes = ct.to_bytes();
1948        let parsed = VarCipherText::from_slice(&bytes).unwrap();
1949        assert_eq!(parsed.to_bytes(), bytes);
1950    }
1951
1952    #[test]
1953    fn beyond_packed_cap() {
1954        // > 14 6-bit blocks (the fixed-N cap) must work and order correctly.
1955        let c = ore();
1956        let long_a = "aaaaaaaaaaaaaaaaaaaaaaaa"; // 24 bytes -> 32 blocks
1957        let long_b = "aaaaaaaaaaaaaaaaaaaaaaab";
1958        assert_eq!(cmp(&c, long_a, long_b), Ordering::Less);
1959        assert_eq!(cmp(&c, long_a, long_a), Ordering::Equal);
1960    }
1961
1962    /// A fixed-width plaintext is an unpadded ciphertext of its width's
1963    /// block count on the wire: a `u128` is 22 blocks, as an unpadded
1964    /// 16-byte string is, and the comparators order the two. The count
1965    /// is a length, not a type; vitaminc's salt keeps targets apart.
1966    #[test]
1967    fn fixed_width_plaintexts_are_unpadded_terms() {
1968        let c = ore();
1969        let n = c.encrypt_plaintext(&u128_pt(7)).unwrap();
1970        let n_left = c.encrypt_query_plaintext(&u128_pt(7)).unwrap();
1971        assert_eq!(n.as_bytes().len(), total_len(22));
1972        assert_eq!(n_left.as_bytes().len(), left_len(22));
1973        assert_eq!(
1974            parse_chained_header(n.as_bytes()),
1975            Some((22, Padding::None))
1976        );
1977        // The same bytes as the unpadded bytes path over the encoding.
1978        assert_eq!(
1979            n_left.as_bytes(),
1980            c.encrypt_left_unpadded_bytes(&7u128.to_be_bytes())
1981                .unwrap()
1982                .to_bytes()
1983        );
1984        assert_eq!(
1985            OreAes128Bit6Chained::compare_left_to_full(n_left.as_bytes(), n.as_bytes()),
1986            Some(Ordering::Equal)
1987        );
1988        // Padded text of 22 blocks carries another policy tag, which the
1989        // comparators refuse; an unpadded 16-byte string compares.
1990        let s16_padded = c.encrypt_str("0123456789abcdef").unwrap().to_bytes();
1991        let s16 = ore_with(Padding::None)
1992            .encrypt_str("0123456789abcdef")
1993            .unwrap()
1994            .to_bytes();
1995        assert_eq!(
1996            parse_chained_header(&s16_padded).map(|(count, _)| count),
1997            Some(22)
1998        );
1999        assert_eq!(
2000            OreAes128Bit6Chained::compare_raw_slices(n.as_bytes(), &s16_padded),
2001            None
2002        );
2003        assert!(OreAes128Bit6Chained::compare_raw_slices(n.as_bytes(), &s16).is_some());
2004    }
2005
2006    /// Text goes in padded under the cipher's options; bytes and
2007    /// fixed-width plaintexts do not, whatever the options say.
2008    #[test]
2009    fn only_text_is_padded() {
2010        let c = ore();
2011        let text = c.encrypt_plaintext(&text_pt("alice")).unwrap();
2012        assert_eq!(
2013            parse_chained_header(text.as_bytes()),
2014            Some((num_blocks_6bit(16), Padding::default()))
2015        );
2016        let bytes = c.encrypt_plaintext(&bytes_pt(b"alice")).unwrap();
2017        assert_eq!(
2018            parse_chained_header(bytes.as_bytes()),
2019            Some((num_blocks_6bit(6), Padding::None))
2020        );
2021        let n = c.encrypt_plaintext(&i128_pt(-1)).unwrap();
2022        assert_eq!(
2023            parse_chained_header(n.as_bytes()),
2024            Some((22, Padding::None))
2025        );
2026        // Bytes ending in NUL are taken: nothing pads them.
2027        assert!(c.encrypt_plaintext(&bytes_pt(b"\0")).is_ok());
2028        // Text is checked against the ceiling, counting vitaminc's marker.
2029        let small = ore_with_max(Padding::None, 8);
2030        assert!(small.encrypt_plaintext(&text_pt("1234567")).is_ok());
2031        assert!(matches!(
2032            small.encrypt_plaintext(&text_pt("12345678")),
2033            Err(OreError::TooLong)
2034        ));
2035        // Bytes are checked against it too, marker included; a fixed-width
2036        // plaintext is not.
2037        assert!(small.encrypt_plaintext(&bytes_pt(&[0u8; 7])).is_ok());
2038        assert!(matches!(
2039            small.encrypt_plaintext(&bytes_pt(&[0u8; 8])),
2040            Err(OreError::TooLong)
2041        ));
2042        assert!(matches!(
2043            small.encrypt_query_plaintext(&bytes_pt(&[0u8; 8])),
2044            Err(OreError::TooLong)
2045        ));
2046        assert!(small.encrypt_plaintext(&u128_pt(u128::MAX)).is_ok());
2047    }
2048
2049    /// Unpadded bytes past the wire limit are refused by their length,
2050    /// before any block is made, and the longest that fit are taken.
2051    #[test]
2052    fn unpadded_bytes_past_the_wire_limit_are_refused_by_length() {
2053        let c = ore();
2054        let too_wide = vec![0u8; MAX_STR_BYTES + 1];
2055        assert!(matches!(
2056            c.encrypt_unpadded_bytes(&too_wide),
2057            Err(OreError::TooManyBlocks)
2058        ));
2059        assert!(matches!(
2060            c.encrypt_left_unpadded_bytes(&too_wide),
2061            Err(OreError::TooManyBlocks)
2062        ));
2063        assert!(c
2064            .encrypt_left_unpadded_bytes(&too_wide[..MAX_STR_BYTES])
2065            .is_ok());
2066    }
2067
2068    #[test]
2069    fn signed_128_orders_across_zero() {
2070        let c = ore();
2071        let vals = [i128::MIN, -1, 0, 1, i128::MAX];
2072        let cts: Vec<Vec<u8>> = vals
2073            .iter()
2074            .map(|&v| c.encrypt_plaintext(&i128_pt(v)).unwrap().into_bytes())
2075            .collect();
2076        for (i, a) in cts.iter().enumerate() {
2077            for (j, b) in cts.iter().enumerate() {
2078                assert_eq!(
2079                    OreAes128Bit6Chained::compare_raw_slices(a, b),
2080                    Some(vals[i].cmp(&vals[j])),
2081                    "{} vs {}",
2082                    vals[i],
2083                    vals[j]
2084                );
2085            }
2086        }
2087    }
2088
2089    #[test]
2090    fn cross_scheme_bytes_rejected() {
2091        let c = ore();
2092        let mut bytes = c.encrypt_str("x").unwrap().to_bytes();
2093        bytes[1] = 0x02; // pretend it's the fixed-N scheme id
2094        assert_eq!(
2095            OreAes128Bit6Chained::compare_raw_slices(&bytes, &bytes),
2096            None
2097        );
2098    }
2099
2100    #[test]
2101    fn left_query_path_and_artifact_rejection() {
2102        let c = ore();
2103        let left = c.encrypt_left_str("hi").unwrap().to_bytes();
2104        let full = c.encrypt_str("hi").unwrap().to_bytes();
2105        // The query path accepts (left, full) and reports the order.
2106        assert_eq!(
2107            OreAes128Bit6Chained::compare_left_to_full(&left, &full),
2108            Some(Ordering::Equal)
2109        );
2110        // A left-only artifact is not a full ciphertext, and vice versa, so the
2111        // length checks reject the swapped/mismatched cases.
2112        assert_eq!(OreAes128Bit6Chained::compare_raw_slices(&left, &full), None);
2113        assert_eq!(
2114            OreAes128Bit6Chained::compare_left_to_full(&full, &full),
2115            None
2116        );
2117    }
2118
2119    #[test]
2120    fn empty_string_sorts_first() {
2121        let c = ore();
2122        assert_eq!(cmp(&c, "", "a"), Ordering::Less);
2123        assert_eq!(cmp(&c, "", ""), Ordering::Equal);
2124    }
2125
2126    // --- Property tests --------------------------------------------------
2127    //
2128    // The contract under test is "the comparator reproduces the lexicographic
2129    // order of the plaintext", over arbitrary inputs and (independent) lengths —
2130    // not just the hand-picked words above. Lengths are capped so each case
2131    // stays cheap (~97 AES ops/block) while still routinely exceeding the
2132    // 14-block fixed-N packed-prefix cap.
2133    const PROP_MAX_BLOCKS: usize = 32;
2134
2135    /// Map arbitrary bytes into the 6-bit block domain, length-capped.
2136    fn to_domain(v: &[u8]) -> Vec<u8> {
2137        v.iter().take(PROP_MAX_BLOCKS).map(|b| b & 0x3f).collect()
2138    }
2139
2140    fn enc(c: &OreAes128Bit6Chained, x: &[u8]) -> Vec<u8> {
2141        c.encrypt_var(x).unwrap().to_bytes()
2142    }
2143
2144    quickcheck! {
2145        /// Headline contract: the comparator reproduces the lexicographic order
2146        /// of the underlying 6-bit block sequences, for arbitrary blocks and
2147        /// arbitrary (independent) lengths — the full domain `0..64`, including
2148        /// values that string inputs never produce.
2149        fn prop_block_order_matches_lex(a: Vec<u8>, b: Vec<u8>) -> bool {
2150            let c = ore();
2151            let (a, b) = (to_domain(&a), to_domain(&b));
2152            let (ea, eb) = (enc(&c, &a), enc(&c, &b));
2153            OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(&b))
2154        }
2155
2156        /// Lewi-Wu query path: a left-only (query) ciphertext compared against a
2157        /// stored full ciphertext reproduces the plaintext order —
2158        /// `compare_left_to_full(left(a), full(b)) == a.cmp(b)`.
2159        fn prop_left_query_matches_full(a: Vec<u8>, b: Vec<u8>) -> bool {
2160            let c = ore();
2161            let (a, b) = (to_domain(&a), to_domain(&b));
2162            let left_a = c.encrypt_left_var(&a).unwrap().to_bytes();
2163            let full_b = enc(&c, &b);
2164            OreAes128Bit6Chained::compare_left_to_full(&left_a, &full_b)
2165                == Some(a.cmp(&b))
2166        }
2167
2168        /// Same, with a forced shared prefix — exercises the constant-time
2169        /// prefix scan and first-differing-block selection at controlled common
2170        /// lengths (independent random inputs almost never share a prefix).
2171        fn prop_shared_prefix_order(prefix: Vec<u8>, sa: Vec<u8>, sb: Vec<u8>) -> bool {
2172            let c = ore();
2173            let p = to_domain(&prefix);
2174            let mut a = p.clone();
2175            a.extend(to_domain(&sa));
2176            a.truncate(PROP_MAX_BLOCKS);
2177            let mut b = p;
2178            b.extend(to_domain(&sb));
2179            b.truncate(PROP_MAX_BLOCKS);
2180            let (ea, eb) = (enc(&c, &a), enc(&c, &b));
2181            OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(&b))
2182        }
2183
2184        /// String comparison matches `str::cmp` across arbitrary Unicode and
2185        /// independent lengths, under every padding policy: the MSB-first
2186        /// 6-bit packing is order-preserving with tail zero-padding, whether
2187        /// the decomposition's own or a padding policy's (cross-length and
2188        /// cross-bucket prefix cases included). A padding policy refuses a
2189        /// trailing NUL, so those are trimmed.
2190        fn prop_string_order_matches_str(a: String, b: String) -> bool {
2191            let a: String = a.chars().take(12).collect();
2192            let b: String = b.chars().take(12).collect();
2193            let (a, b) = (a.trim_end_matches('\0'), b.trim_end_matches('\0'));
2194            POLICIES.iter().all(|&padding| {
2195                let c = ore_with(padding);
2196                let ea = c.encrypt_str(a).unwrap().to_bytes();
2197                let eb = c.encrypt_str(b).unwrap().to_bytes();
2198                OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(b))
2199            })
2200        }
2201
2202        /// A string sharing a prefix with another: the case where padding
2203        /// meets real blocks. Covers both strings in one bucket and in
2204        /// different ones.
2205        fn prop_padded_prefix_order(prefix: String, tail: String) -> bool {
2206            let a: String = prefix.chars().take(20).collect();
2207            let a = a.trim_end_matches('\0');
2208            let b: String = a.chars().chain(tail.chars().take(8)).collect();
2209            let b = b.trim_end_matches('\0');
2210            POLICIES[1..3].iter().all(|&padding| {
2211                let c = ore_with(padding);
2212                let ea = c.encrypt_str(a).unwrap().to_bytes();
2213                let eb = c.encrypt_str(b).unwrap().to_bytes();
2214                OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(b))
2215            })
2216        }
2217
2218        /// A power-of-two bucket never shrinks a length, less than doubles
2219        /// it, is monotone, and maps a bucket length to itself.
2220        fn prop_power_of_two_buckets(a: u16, b: u16) -> bool {
2221            // Halved, so that every length is within the wire limit.
2222            let (a, b) = (usize::from(a) / 2, usize::from(b) / 2);
2223            let p = |n| Padding::PowerOfTwo { min_bytes: 0 }.padded_len(n).unwrap();
2224            let pa = p(a);
2225            pa >= a && pa < 2 * a.max(1) && (a > b || pa <= p(b)) && p(pa) == pa
2226        }
2227
2228        /// A padded string encrypts to the blocks of the string extended with
2229        /// NULs to its bucket under no padding: only the header tag differs.
2230        /// Padding is NUL extension and nothing more. A string too long for a
2231        /// fixed length is refused.
2232        fn prop_padding_is_nul_extension(s: String) -> bool {
2233            let s: String = s.chars().take(40).collect();
2234            let s = s.trim_end_matches('\0');
2235            let unpadded = ore_with(Padding::None);
2236            POLICIES.iter().all(|&padding| {
2237                let c = ore_with(padding);
2238                let Ok(padded) = padding.padded_len(s.len()) else {
2239                    return matches!(padding, Padding::Fixed { .. })
2240                        && matches!(c.encrypt_left_str(s), Err(OreError::ExceedsPadding))
2241                        && matches!(c.encrypt_str(s), Err(OreError::ExceedsPadding));
2242                };
2243                let mut extended = s.to_owned();
2244                extended.extend(std::iter::repeat_n('\0', padded - s.len()));
2245                let left = c.encrypt_left_str(s).unwrap();
2246                let a = left.to_bytes();
2247                let b = unpadded.encrypt_left_str(&extended).unwrap().to_bytes();
2248                left.padding() == padding
2249                    && a[..WIRE_HEADER_LEN] == b[..WIRE_HEADER_LEN]
2250                    && a[HEADER_LEN..] == b[HEADER_LEN..]
2251            })
2252        }
2253
2254        /// Under every policy, two encryptions of a string compare Equal to
2255        /// each other and to its left ciphertext, and the full ciphertext
2256        /// round trips with its policy.
2257        fn prop_string_equality_under_every_policy(s: String) -> bool {
2258            type C = OreAes128Bit6Chained;
2259            let s: String = s.chars().take(12).collect();
2260            let s = s.trim_end_matches('\0');
2261            POLICIES.iter().all(|&padding| {
2262                let c = ore_with(padding);
2263                let a = c.encrypt_str(s).unwrap().to_bytes();
2264                let b = c.encrypt_str(s).unwrap().to_bytes();
2265                let l = c.encrypt_left_str(s).unwrap().to_bytes();
2266                C::compare_raw_slices(&a, &b) == Some(Ordering::Equal)
2267                    && C::compare_left_to_full(&l, &b) == Some(Ordering::Equal)
2268                    && VarCipherText::from_slice(&a)
2269                        .map(|ct| ct.to_bytes() == a && ct.padding() == padding)
2270                        .unwrap_or(false)
2271            })
2272        }
2273
2274        /// A padding policy refuses exactly the strings that end in NUL; no
2275        /// padding accepts them all.
2276        fn prop_padding_refuses_exactly_trailing_nul(s: String, nul: bool) -> bool {
2277            let mut s: String = s.chars().take(11).collect();
2278            if nul {
2279                s.push('\0');
2280            }
2281            let ends_in_nul = s.ends_with('\0');
2282            POLICIES.iter().all(|&padding| {
2283                let c = ore_with(padding);
2284                let (full, left) = (c.encrypt_str(&s), c.encrypt_left_str(&s));
2285                if padding != Padding::None && ends_in_nul {
2286                    matches!(full, Err(OreError::TrailingNul))
2287                        && matches!(left, Err(OreError::TrailingNul))
2288                } else {
2289                    full.is_ok() && left.is_ok()
2290                }
2291            })
2292        }
2293
2294        /// Arbitrary bytes, and a valid ciphertext with one byte changed, are
2295        /// parsed and compared without panicking.
2296        fn prop_parsers_never_panic(bytes: Vec<u8>, at: usize, value: u8) -> bool {
2297            type C = OreAes128Bit6Chained;
2298            let good = ore().encrypt_str("alice").unwrap().to_bytes();
2299            let mut changed = good.clone();
2300            changed[at % good.len()] = value;
2301            for x in [&bytes, &changed] {
2302                let _ = VarCipherText::from_slice(x);
2303                let _ = C::compare_raw_slices(x, x);
2304                let _ = C::compare_raw_slices(x, &good);
2305                let _ = C::compare_left_to_full(x, &good);
2306                let _ = C::compare_left_to_full(&good, x);
2307            }
2308            true
2309        }
2310
2311        /// `u128` plaintexts order as the integers, on both the full and
2312        /// the query path.
2313        fn prop_u128_order(a: u128, b: u128) -> bool {
2314            let c = ore();
2315            let ca = c.encrypt_plaintext(&u128_pt(a)).unwrap();
2316            let cb = c.encrypt_plaintext(&u128_pt(b)).unwrap();
2317            let la = c.encrypt_query_plaintext(&u128_pt(a)).unwrap();
2318            OreAes128Bit6Chained::compare_raw_slices(ca.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2319                && OreAes128Bit6Chained::compare_left_to_full(la.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2320        }
2321
2322        fn prop_i128_order(a: i128, b: i128) -> bool {
2323            let c = ore();
2324            let ca = c.encrypt_plaintext(&i128_pt(a)).unwrap();
2325            let cb = c.encrypt_plaintext(&i128_pt(b)).unwrap();
2326            let la = c.encrypt_query_plaintext(&i128_pt(a)).unwrap();
2327            OreAes128Bit6Chained::compare_raw_slices(ca.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2328                && OreAes128Bit6Chained::compare_left_to_full(la.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2329        }
2330
2331        /// Two encryptions of one plaintext (fresh nonces each) compare Equal,
2332        /// and never produce identical bytes (the nonce streams differ).
2333        fn prop_equality_across_nonces(x: Vec<u8>) -> bool {
2334            let c = ore();
2335            let x = to_domain(&x);
2336            let (a, b) = (enc(&c, &x), enc(&c, &x));
2337            let equal = OreAes128Bit6Chained::compare_raw_slices(&a, &b)
2338                == Some(Ordering::Equal);
2339            // Empty plaintexts have no right blocks, so their bytes can collide;
2340            // only require nonce divergence when there is masked material.
2341            let distinct = x.is_empty() || a != b;
2342            equal && distinct
2343        }
2344
2345        /// The left ciphertext is deterministic (it has no nonce) and is
2346        /// byte-identical to the left half embedded in a full ciphertext — the
2347        /// two encrypt paths must not drift.
2348        fn prop_left_deterministic_and_consistent(x: Vec<u8>) -> bool {
2349            let c = ore();
2350            let x = to_domain(&x);
2351            let l1 = c.encrypt_left_var(&x).unwrap().to_bytes();
2352            let l2 = c.encrypt_left_var(&x).unwrap().to_bytes();
2353            let full = c.encrypt_var(&x).unwrap();
2354            l1 == l2 && full.left.to_bytes() == l1
2355        }
2356
2357        /// Serialised full ciphertexts round-trip through `from_slice`.
2358        fn prop_serialize_roundtrip(x: Vec<u8>) -> bool {
2359            let c = ore();
2360            let x = to_domain(&x);
2361            let bytes = enc(&c, &x);
2362            match VarCipherText::from_slice(&bytes) {
2363                Ok(ct) => ct.to_bytes() == bytes,
2364                Err(_) => false,
2365            }
2366        }
2367    }
2368
2369    /// Every block's PRP tables for `s`, which must not survive an
2370    /// encryption in dead stack (review of #82 and #83).
2371    fn block_tables(ore: &OreAes128Bit6Chained, s: &str) -> Vec<Vec<u8>> {
2372        let blocks = str_to_blocks(s, &ore.options).unwrap();
2373        let mut acc = CmacAccumulator::new(&ore.k_acc);
2374        let mut needles = Vec::new();
2375        for (n, &sym) in blocks.as_bytes().iter().enumerate() {
2376            let prp = ore.prp_at(&acc, n as u16);
2377            let symbols = (0..64).map(crate::primitives::Symbol::<64>::from_low_bits);
2378            needles.push(symbols.clone().map(|i| prp.permute(i).get()).collect());
2379            needles.push(symbols.map(|i| prp.invert(i).get()).collect());
2380            acc.absorb(&prefix_block(n as u16, sym));
2381        }
2382        needles
2383    }
2384
2385    fn assert_no_block_tables(
2386        encrypt: fn(&OreAes128Bit6Chained, &str),
2387        unscrubbed: fn(&OreAes128Bit6Chained, &str),
2388    ) {
2389        use crate::primitives::stack::{residue, SCRUB_BYTES};
2390        const S: &str = "a chained residue test string";
2391        let needles = block_tables(&ore(), S);
2392
2393        // Positive control and depth, as in the Bit6 residue tests.
2394        let dead = residue::after(move || unscrubbed(&ore(), S));
2395        assert!(needles.iter().any(|n| residue::contains(&dead, n)));
2396        let depth = residue::depth(&dead);
2397        assert!(
2398            depth < SCRUB_BYTES,
2399            "encryption reached {} bytes of stack, past the {}-byte scrub",
2400            depth,
2401            SCRUB_BYTES
2402        );
2403
2404        let dead = residue::after(move || encrypt(&ore(), S));
2405        for (i, needle) in needles.iter().enumerate() {
2406            assert!(
2407                !residue::contains(&dead, needle),
2408                "block {} {} left in dead stack",
2409                i / 2,
2410                ["permutation", "inverse"][i % 2]
2411            );
2412        }
2413    }
2414
2415    #[test]
2416    fn encrypt_str_leaves_no_prp_tables_on_the_stack() {
2417        assert_no_block_tables(
2418            |ore, s| {
2419                core::hint::black_box(ore.encrypt_str(s).unwrap());
2420            },
2421            |ore, s| {
2422                let blocks = str_to_blocks(s, &ore.options).unwrap();
2423                core::hint::black_box(ore.encrypt_blocks(&blocks, ore.padding()).unwrap());
2424            },
2425        );
2426    }
2427
2428    /// A bytes plaintext as large as the wire format allows, on the heap:
2429    /// the unpadded encryptors must borrow it. A copy on the stack would be
2430    /// larger than the optimised scrub and leave plaintext in dead stack.
2431    fn assert_no_large_plaintext(encrypt: fn(&OreAes128Bit6Chained, &OrderPlaintext)) {
2432        use crate::primitives::stack::{residue, SCRUB_BYTES};
2433        // vitaminc puts a marker byte before the bytes, so one less fits.
2434        const LEN: usize = MAX_STR_BYTES - 1;
2435        fn raw() -> Vec<u8> {
2436            (0..LEN).map(|i| (i * 37 + 11) as u8).collect()
2437        }
2438        // Windows from the start, middle and end of the array; a copy
2439        // that outgrew the scrub leaves at least its deepest part behind.
2440        let p = raw();
2441        let needles: Vec<Vec<u8>> = [0, LEN / 2, LEN - 64]
2442            .iter()
2443            .map(|&at| p[at..at + 64].to_vec())
2444            .collect();
2445
2446        // Positive control: a copy made under the scrub survives it when
2447        // it is larger than the scrub (optimised builds).
2448        if LEN > SCRUB_BYTES {
2449            let dead = residue::after(|| {
2450                let p = raw();
2451                stack::scrubbed(|| {
2452                    let mut copy = [0u8; LEN];
2453                    copy.copy_from_slice(&p);
2454                    core::hint::black_box(&copy);
2455                });
2456            });
2457            assert!(needles.iter().any(|n| residue::contains(&dead, n)));
2458        }
2459
2460        // A cipher whose ceiling admits the plaintext.
2461        let dead = residue::after(move || {
2462            encrypt(
2463                &ore_with_max(Padding::None, MAX_STR_BYTES),
2464                &bytes_pt(&raw()),
2465            )
2466        });
2467        for needle in &needles {
2468            assert!(
2469                !residue::contains(&dead, needle),
2470                "plaintext left in dead stack"
2471            );
2472        }
2473    }
2474
2475    #[test]
2476    fn encrypt_plaintext_leaves_no_large_array_on_the_stack() {
2477        assert_no_large_plaintext(|ore, p| {
2478            core::hint::black_box(ore.encrypt_plaintext(p).unwrap());
2479        });
2480    }
2481
2482    #[test]
2483    fn encrypt_query_plaintext_leaves_no_large_array_on_the_stack() {
2484        assert_no_large_plaintext(|ore, p| {
2485            core::hint::black_box(ore.encrypt_query_plaintext(p).unwrap());
2486        });
2487    }
2488
2489    #[test]
2490    fn encrypt_left_str_leaves_no_prp_tables_on_the_stack() {
2491        assert_no_block_tables(
2492            |ore, s| {
2493                core::hint::black_box(ore.encrypt_left_str(s).unwrap());
2494            },
2495            |ore, s| {
2496                let blocks = str_to_blocks(s, &ore.options).unwrap();
2497                core::hint::black_box(ore.encrypt_left_blocks(&blocks, ore.padding()).unwrap());
2498            },
2499        );
2500    }
2501
2502    /// `init` seeds the nonce generator from the OS: one cipher never
2503    /// repeats a nonce, and two ciphers under one key draw different
2504    /// streams. A constant seed would pass every other test.
2505    #[test]
2506    fn every_term_draws_a_fresh_nonce() {
2507        let term_bytes = |ore: &OreAes128Bit6Chained, p: &OrderPlaintext| {
2508            ore.encrypt_plaintext(p).unwrap().into_bytes()
2509        };
2510        let a = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
2511        let b = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
2512        let (a1, a2, b1) = (
2513            term_bytes(&a, &text_pt("alice")),
2514            term_bytes(&a, &text_pt("alice")),
2515            term_bytes(&b, &text_pt("alice")),
2516        );
2517        assert_ne!(a1, a2, "one cipher reused a nonce");
2518        assert_ne!(a1, b1, "two ciphers drew the same nonce stream");
2519        assert_eq!(
2520            OreAes128Bit6Chained::compare_raw_slices(&a1, &b1),
2521            Some(Ordering::Equal)
2522        );
2523    }
2524
2525    /// A thread that panics while holding the nonce lock does not stop
2526    /// encryption on the shared cipher: the generator is taken from the
2527    /// poisoned lock and still draws fresh nonces.
2528    #[test]
2529    fn a_poisoned_nonce_lock_still_encrypts() {
2530        let term_bytes = |ore: &OreAes128Bit6Chained, p: &OrderPlaintext| {
2531            ore.encrypt_plaintext(p).unwrap().into_bytes()
2532        };
2533        let ore = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
2534        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2535            let _guard = ore.rng.lock().unwrap();
2536            panic!("poison the nonce lock");
2537        }));
2538        assert!(ore.rng.is_poisoned());
2539        let (a, b) = (
2540            term_bytes(&ore, &text_pt("alice")),
2541            term_bytes(&ore, &text_pt("alice")),
2542        );
2543        assert_ne!(a, b, "a poisoned lock reused a nonce");
2544        assert_eq!(
2545            OreAes128Bit6Chained::compare_raw_slices(&a, &b),
2546            Some(Ordering::Equal)
2547        );
2548    }
2549}