Skip to main content

sail_key/
lib.rs

1//! Content-addressed keys for solver queries.
2//!
3//! Two key versions exist:
4//! - **v2, [`PrefixHasher`]: the default-mode key (ADR 0008).** It binds the
5//!   mode, the solver identity (including the platform) and every raw byte
6//!   the solver process received, up to and including the check command.
7//! - **v1, [`query_key`]: stack only.** It is used for measurement, and is
8//!   the candidate key for the named opt-in mode (ADR 0010). It is described
9//!   below.
10//!
11//! A v1 [`QueryKey`] is a SHA-256 digest that binds:
12//! - the verification mode, so opt-in modes can never collide with default
13//!   mode (charter rule 8);
14//! - the exact solver identity: name, version string and binary hash
15//!   (rule 2);
16//! - the complete modelled state at the check: every push level and its
17//!   commands, every option in effect, `set-logic`/`set-info`, and the check
18//!   command itself (rule 2).
19//!
20//! Inputs are length-prefixed before hashing, so distinct inputs cannot
21//! produce the same byte stream. No normalization is applied (rule 5). A
22//! snapshot the session model could not follow exactly has no key.
23#![forbid(unsafe_code)]
24
25mod prefix_factory;
26
27use std::fmt;
28
29use sail_acceptance::key_prefix::{HashHost, Prefix};
30use sail_acceptance::query_prefix::{FramedCommand as CoreCommand, QueryPrefix as QueryState};
31use sail_acceptance::query_raw::PrefixFeed;
32use sail_session::Snapshot;
33use sha2::{Digest, Sha256};
34
35/// The exact identity of a solver binary.
36#[derive(Debug, Clone, PartialEq, Eq, Hash)]
37pub struct SolverIdentity {
38    /// Solver family, for example `"z3"`.
39    pub name: String,
40    /// The version string the solver reports, for example `"4.16.0"`.
41    pub version: String,
42    /// SHA-256 of the solver executable.
43    pub binary_sha256: [u8; 32],
44    /// Platform class, for example `"macos-aarch64"` (ADR 0004 update,
45    /// ADR 0010): the same binary can spend different effort on different
46    /// platforms.
47    pub platform: String,
48}
49
50impl SolverIdentity {
51    /// The platform class of this machine: `<os>-<arch>`.
52    #[must_use]
53    pub fn host_platform() -> String {
54        format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
55    }
56}
57
58/// The verification mode a result is produced under.
59#[derive(Debug, Clone, PartialEq, Eq, Hash)]
60pub enum Mode {
61    /// Default mode: observationally identical to plain Verus.
62    Default,
63    /// A named opt-in mode (recorded in `docs/divergences.md`).
64    OptIn(String),
65}
66
67/// A content-addressed key for one solver query.
68#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
69pub struct QueryKey(pub [u8; 32]);
70
71impl fmt::Display for QueryKey {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        for b in self.0 {
74            write!(f, "{b:02x}")?;
75        }
76        Ok(())
77    }
78}
79
80impl fmt::Debug for QueryKey {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(f, "QueryKey({self})")
83    }
84}
85
86fn field(hasher: &mut Sha256, bytes: &[u8]) {
87    hasher.update((bytes.len() as u64).to_le_bytes());
88    hasher.update(bytes);
89}
90
91/// Derives the key for `snapshot` under `mode` on `solver`, or `None` if the
92/// session model was inexact at that point.
93#[must_use]
94pub fn query_key(snapshot: &Snapshot, solver: &SolverIdentity, mode: &Mode) -> Option<QueryKey> {
95    if snapshot.inexact.is_some() {
96        return None;
97    }
98    let mut hasher = Sha256::new();
99    field(&mut hasher, b"sail-key/query/v1");
100    match mode {
101        Mode::Default => field(&mut hasher, b"mode:default"),
102        Mode::OptIn(name) => {
103            field(&mut hasher, b"mode:opt-in");
104            field(&mut hasher, name.as_bytes());
105        }
106    }
107    field(&mut hasher, solver.name.as_bytes());
108    field(&mut hasher, solver.version.as_bytes());
109    field(&mut hasher, &solver.binary_sha256);
110    field(&mut hasher, solver.platform.as_bytes());
111    let mut state = Vec::new();
112    snapshot.encode_state(&mut state);
113    field(&mut hasher, &state);
114    Some(QueryKey(hasher.finalize().into()))
115}
116
117/// The running v2 key of one solver process (ADR 0008).
118///
119/// Feed it every byte sent to the process, exactly as sent, in order. At a
120/// check, after feeding the check command's bytes, [`PrefixHasher::key`]
121/// gives the key. Nothing is normalized: whitespace and comments between
122/// commands count too.
123pub struct PrefixHasher {
124    prefix: Prefix<Sha256Host>,
125}
126
127// The source-bound hash primitive boundary: fresh, exact update, copied state,
128// and SHA-256 finalization. No result or cache provenance is inferred here.
129struct Sha256Host(Sha256);
130
131impl HashHost for Sha256Host {
132    fn append(&mut self, bytes: &[u8]) {
133        self.0.update(bytes);
134    }
135    fn duplicate(&self) -> Self {
136        Self(self.0.clone())
137    }
138    fn empty(&self) -> Self {
139        Self(Sha256::new())
140    }
141    fn finish(self) -> [u8; 32] {
142        self.0.finalize().into()
143    }
144}
145
146impl Clone for PrefixHasher {
147    fn clone(&self) -> Self {
148        Self {
149            prefix: self.prefix.duplicate(),
150        }
151    }
152}
153
154impl fmt::Debug for PrefixHasher {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(f, "PrefixHasher({} bytes)", self.len())
157    }
158}
159
160impl PrefixHasher {
161    /// A hasher for a new process of `solver` under `mode`.
162    #[must_use]
163    pub fn new(solver: &SolverIdentity, mode: &Mode) -> Self {
164        Self {
165            prefix: prefix_factory::new_prefix(Sha256Host(Sha256::new()), solver, mode),
166        }
167    }
168
169    /// Feeds the next bytes the process received without changing their order.
170    /// Counter overflow permanently removes exact-length authority.
171    pub fn update(&mut self, bytes: &[u8]) {
172        self.prefix.update(bytes);
173    }
174
175    /// Feeds a checked raw interval only at its exact next byte position.
176    /// Failure permanently removes exact-length authority without changing input forwarding.
177    pub fn feed(&mut self, feed: &PrefixFeed<'_>) -> bool {
178        self.prefix.feed(feed)
179    }
180
181    /// Bytes fed so far. Use [`Self::is_exact`] before relying on the counter.
182    #[must_use]
183    pub fn len(&self) -> u64 {
184        self.prefix.len()
185    }
186
187    /// Whether nothing has been fed yet.
188    #[must_use]
189    pub fn is_empty(&self) -> bool {
190        self.len() == 0
191    }
192
193    /// Whether the cumulative length still represents every supplied byte.
194    #[must_use]
195    pub fn is_exact(&self) -> bool {
196        self.prefix.is_exact()
197    }
198
199    /// The unchanged v2 key, including the end marker and cumulative length.
200    /// Cache users must also require [`Self::is_exact`].
201    #[must_use]
202    pub fn key(&self) -> QueryKey {
203        QueryKey(self.prefix.key())
204    }
205
206    /// Key for complete clean session silence, distinct from normal reply keys.
207    /// Feed all trailing bytes first and require [`Self::is_exact`].
208    #[must_use]
209    pub fn silence_key(&self) -> QueryKey {
210        QueryKey(self.prefix.silence_key())
211    }
212}
213
214/// Immutable borrow of one actual same-owner command transition.
215/// Its key is computed only when requested, without copying the hash for no-output commands.
216pub struct CommandFrame<'command, 'owner> {
217    frame: CoreCommand<'command, 'owner, Sha256Host>,
218}
219impl CommandFrame<'_, '_> {
220    /// The command's exact supported head bytes.
221    #[must_use]
222    pub fn head(&self) -> &[u8] {
223        self.frame.head()
224    }
225    /// Computes the default successful-command response count from this exact accepted head.
226    #[must_use]
227    pub fn policy(&self) -> sail_acceptance::query_policy::ResponsePolicy {
228        self.frame.policy()
229    }
230    /// The exact endpoint at this command transition.
231    #[must_use]
232    pub fn end(&self) -> usize {
233        self.frame.end()
234    }
235    /// Derives the unchanged v2 key while this transition's hash state is immutably borrowed.
236    #[must_use]
237    pub fn key(&self) -> QueryKey {
238        QueryKey(self.frame.key())
239    }
240}
241
242/// One cache session's jointly owned exact raw transcript and incremental v2 key.
243/// Unlike a detached hasher, this API cannot consume another transcript's feed tokens.
244pub struct SessionPrefix {
245    seed: Prefix<Sha256Host>,
246    session: QueryState<Sha256Host>,
247}
248
249impl SessionPrefix {
250    /// Starts exact framing for the actual solver identity and mode.
251    #[must_use]
252    pub fn new(solver: &SolverIdentity, mode: &Mode) -> Self {
253        let (session, seed) =
254            prefix_factory::new_session_seed(Sha256Host(Sha256::new()), solver, mode);
255        Self { seed, session }
256    }
257    /// Transfers a fresh actual solver input pipe into an independent delivery
258    /// checker seeded with this session's exact solver and mode header.
259    #[must_use]
260    pub fn delivery<Pipe: sail_acceptance::query_delivery::InputPipe>(
261        &self,
262        pipe: Pipe,
263    ) -> InputDelivery<Pipe> {
264        InputDelivery {
265            delivery: sail_acceptance::query_delivery::Delivery::new(pipe, self.seed.duplicate()),
266        }
267    }
268    /// Appends exactly the bytes received by this session.
269    pub fn append(&mut self, bytes: &[u8]) {
270        self.session.append(bytes);
271    }
272    /// Interprets only an exact command interval of this owner's bytes.
273    pub fn command<'a, 'b>(
274        &'b mut self,
275        offset: usize,
276        command: &'a [u8],
277    ) -> Option<CommandFrame<'a, 'b>> {
278        self.session
279            .command(offset, command)
280            .map(|frame| CommandFrame { frame })
281    }
282
283    /// Borrows all original bytes for pinned-solver replay.
284    #[must_use]
285    pub fn bytes(&self) -> &[u8] {
286        self.session.bytes()
287    }
288    /// Permanently refuses cache interpretation without changing the original bytes.
289    pub fn refuse(&mut self) {
290        self.session.refuse();
291    }
292    /// Whether interpretation remains valid under the checked same-owner invariant.
293    #[must_use]
294    pub fn valid(&self) -> bool {
295        self.session.valid()
296    }
297    /// Number of original bytes already included in this owner's hash.
298    #[must_use]
299    pub fn len(&self) -> u64 {
300        self.session.len()
301    }
302    /// Whether no input byte has entered this owner's hash.
303    #[must_use]
304    pub fn is_empty(&self) -> bool {
305        self.session.is_empty()
306    }
307    /// Whether the remaining original input is only whitespace/comments.
308    #[must_use]
309    pub fn trailing_trivia(&self) -> bool {
310        self.session.trailing_trivia()
311    }
312    /// Hashes the owned remainder; this does not claim EOF or a clean solver run.
313    pub fn hash_tail(&mut self) -> bool {
314        self.session.hash_tail()
315    }
316    /// The current same-owner normal-key candidate.
317    #[must_use]
318    pub fn key(&self) -> QueryKey {
319        QueryKey(self.session.key())
320    }
321    /// The current same-owner silence-key candidate; clean publication remains separate.
322    #[must_use]
323    pub fn silence_key(&self) -> QueryKey {
324        QueryKey(self.session.silence_key())
325    }
326}
327
328/// SHA-256 of a byte string, for solver binary identity and trace digests.
329#[must_use]
330pub fn sha256(bytes: &[u8]) -> [u8; 32] {
331    Sha256::digest(bytes).into()
332}
333
334/// Independent full-write accounting for one actual solver input pipe.
335/// Its closure check binds delivered bytes to the parser session terminal key.
336pub struct InputDelivery<Pipe> {
337    delivery: sail_acceptance::query_delivery::Delivery<Pipe, Sha256Host>,
338}
339impl<Pipe: sail_acceptance::query_delivery::InputPipe> InputDelivery<Pipe> {
340    /// Calls the owned pipe's full write and flush before acknowledging bytes.
341    pub fn write(&mut self, bytes: &[u8]) -> bool {
342        self.delivery.write(bytes)
343    }
344    /// Whether a delivery failure has permanently withheld eligibility.
345    #[must_use]
346    pub fn active(&self) -> bool {
347        self.delivery.active()
348    }
349    /// Checks acknowledged input against this session's parser terminal key.
350    #[must_use]
351    pub fn matches(&self, expected: QueryKey, complete: bool) -> bool {
352        self.delivery.matches(expected.0, complete)
353    }
354    /// Freezes this input once; no later writes can qualify or modify the token.
355    pub fn seal(&mut self, expected: QueryKey, complete: bool) -> Option<DeliveredInput> {
356        self.delivery
357            .seal(expected.0, complete)
358            .map(|delivered| DeliveredInput { delivered })
359    }
360    /// Closes the exact owned input pipe.
361    pub fn close(&mut self) {
362        self.delivery.close();
363    }
364}
365
366/// Frozen complete input for one actual solver delivery. This is not yet a
367/// clean solver-output or executable-image certificate.
368pub struct DeliveredInput {
369    delivered: sail_acceptance::query_delivery::Delivered<Sha256Host>,
370}
371impl DeliveredInput {
372    /// The complete-input key retained by the private delivery token.
373    #[must_use]
374    pub fn key(&self) -> QueryKey {
375        QueryKey(self.delivered.key())
376    }
377}