ordeal_cert/query.rs
1//! The certificate-carried query, term and extended query
2//! (`ordeal-cert/v2`..`v4`, issue #192 phases 4–7, TR-072) — the data
3//! types and their trusted re-checks, extracted from `ordeal::query`
4//! (TR-075) so a re-checker can be built without the solver.
5//!
6//! Every `recheck` here calls the trusted `ordeal-lrat` functions exactly
7//! as `ordeal` always did (the code moved verbatim); the solver-side
8//! constructors (`QueryTerm::flatten`, `QueryTerm::flatten_sliver`) and
9//! the `*CheckResult` verdict types stay in `ordeal::query`, which
10//! re-exports everything here.
11//!
12//! Always compiled (no feature gate, no dependencies beyond
13//! `ordeal-lrat`); the JSON envelopes are in [`crate::cert_bundle`]
14//! behind the `json` feature. The canonical texts and content hashes are
15//! computed HERE so the CLI's blocks and the API's bundles are
16//! byte-for-byte the same.
17
18use crate::certificate::Certificate;
19use crate::sha256::sha256_hex;
20use crate::witness::SatCertificate;
21use ordeal_lrat::blast_kernel as k;
22
23/// The "no image" entry of a term or extended map: a node that has none
24/// (the inside of a folded constant). `ordeal::dag::NO_IMAGE` is this
25/// constant.
26pub const NO_IMAGE: usize = usize::MAX;
27
28/// The `query.encoding` value of a DAG over the phase-3 node kinds: a
29/// `DagNode` list (`[op, args…]` per node, operands as indices of earlier
30/// nodes), a `0`/`1` constant table, root indices and compaction hints.
31/// Since #192 phase 5 a DAG that uses one of the five derived-op node kinds
32/// (`bvnot`, `neg`, `rotl`, `sdiv`, `srem`) is tagged [`QUERY_ENCODING_V2`]
33/// instead, so a v0.27.0 reader refuses it rather than misreading it; a DAG
34/// without them keeps this tag, and v0.27.0 readers keep reading it.
35/// [`QueryDag::encoding`] picks the tag; readers accept both and reject any
36/// other.
37pub const QUERY_ENCODING: &str = "ordeal-dag/v1";
38
39/// The `query.encoding` value of a DAG that uses a derived-op node kind
40/// (`ordeal-dag/v1` plus `bvnot`, `neg`, `rotl`, `sdiv`, `srem`; #192
41/// phase 5). Readers from v0.28.0 on.
42pub const QUERY_ENCODING_V2: &str = "ordeal-dag/v2";
43
44/// The `query.encoding` value of a DAG whose compaction hints ask for the
45/// mux fold ([`MUX_FOLD_HINT`], issue #314): the node kinds of
46/// `ordeal-dag/v2`, compacted with `blast_kernel::mux_fold`. Readers from
47/// v0.38.0 on. An older reader has no such fold — it would push a gate
48/// where this lowering folded one away and re-derive a different CNF — so
49/// it must refuse the block by its tag rather than report a mismatch.
50pub const QUERY_ENCODING_V3: &str = "ordeal-dag/v3";
51
52/// The compaction hint that asks the trusted `blast_kernel::compact` for
53/// its checked two-level fold of a mux with equal arms (issue #314). It
54/// names no source node: where the fold does not apply it means "no
55/// sharing". Spelled `u64::MAX` on the wire on every target
56/// ([`wire_usize`]). No release up to v0.37.0 ever wrote it.
57pub const MUX_FOLD_HINT: usize = usize::MAX;
58
59/// Is `encoding` one this reader decodes?
60pub fn encoding_supported(encoding: &str) -> bool {
61 encoding == QUERY_ENCODING || encoding == QUERY_ENCODING_V2 || encoding == QUERY_ENCODING_V3
62}
63
64/// The lowered query: exactly the inputs the proven lowering (and the
65/// trusted re-check) consumes.
66#[derive(Clone, Default, PartialEq, Eq)]
67pub struct QueryDag {
68 /// The term DAG, topologically ordered (every operand is an earlier
69 /// node) — the closed `term.rs` fragment.
70 pub nodes: Vec<k::DagNode>,
71 /// The constant table the `Const(s, w)` nodes slice, LSB first.
72 pub bits: Vec<bool>,
73 /// The asserted boolean nodes (one per assertion).
74 pub roots: Vec<usize>,
75 /// The structural-hashing hints the solver compacted with (untrusted
76 /// advice: `compact` checks each one; a wrong hint costs a duplicate
77 /// gate, never a wrong value). Carried so the re-encoded CNF is the
78 /// CNF the proof refutes, gate for gate.
79 pub hints: Vec<usize>,
80}
81
82impl std::fmt::Debug for QueryDag {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 f.debug_struct("QueryDag")
85 .field("nodes", &self.nodes.len())
86 .field("bits", &self.bits.len())
87 .field("roots", &self.roots)
88 .field("hints", &self.hints.len())
89 .field("sha256", &self.sha256())
90 .finish()
91 }
92}
93
94/// A node as its `[op, args…]` spelling: the operator mnemonic and its
95/// integer arguments in the order the constructor takes them
96/// (`Var(w)` → `("var", [w])`, `Const(s, w)` → `("const", [s, w])`,
97/// `Extract(hi, lo, a)` → `("extract", [hi, lo, a])`, `ZeroExt(a, by)` →
98/// `("zero_ext", [a, by])`, `Ite(c, t, e)` → `("ite", [c, t, e])`, binary
99/// ops → `(op, [a, b])`, `Not(a)` → `("not", [a])`).
100pub fn node_op(node: &k::DagNode) -> (&'static str, Vec<usize>) {
101 use k::DagNode as N;
102 match *node {
103 N::Var(w) => ("var", vec![w]),
104 N::Const(s, w) => ("const", vec![s, w]),
105 N::Add(a, b) => ("add", vec![a, b]),
106 N::Sub(a, b) => ("sub", vec![a, b]),
107 N::Mul(a, b) => ("mul", vec![a, b]),
108 N::Udiv(a, b) => ("udiv", vec![a, b]),
109 N::Urem(a, b) => ("urem", vec![a, b]),
110 N::And(a, b) => ("and", vec![a, b]),
111 N::Or(a, b) => ("or", vec![a, b]),
112 N::Xor(a, b) => ("xor", vec![a, b]),
113 N::Shl(a, b) => ("shl", vec![a, b]),
114 N::Lshr(a, b) => ("lshr", vec![a, b]),
115 N::Ashr(a, b) => ("ashr", vec![a, b]),
116 N::Rotr(a, b) => ("rotr", vec![a, b]),
117 N::Extract(hi, lo, a) => ("extract", vec![hi, lo, a]),
118 N::Concat(a, b) => ("concat", vec![a, b]),
119 N::ZeroExt(a, by) => ("zero_ext", vec![a, by]),
120 N::SignExt(a, by) => ("sign_ext", vec![a, by]),
121 N::Ite(c, t, e) => ("ite", vec![c, t, e]),
122 N::Eq(a, b) => ("eq", vec![a, b]),
123 N::Ne(a, b) => ("ne", vec![a, b]),
124 N::Ult(a, b) => ("ult", vec![a, b]),
125 N::Ule(a, b) => ("ule", vec![a, b]),
126 N::Ugt(a, b) => ("ugt", vec![a, b]),
127 N::Uge(a, b) => ("uge", vec![a, b]),
128 N::Slt(a, b) => ("slt", vec![a, b]),
129 N::Sle(a, b) => ("sle", vec![a, b]),
130 N::Sgt(a, b) => ("sgt", vec![a, b]),
131 N::Sge(a, b) => ("sge", vec![a, b]),
132 N::Not(a) => ("not", vec![a]),
133 N::BoolAnd(a, b) => ("bool_and", vec![a, b]),
134 N::BoolOr(a, b) => ("bool_or", vec![a, b]),
135 N::BvNot(a) => ("bvnot", vec![a]),
136 N::Neg(a) => ("neg", vec![a]),
137 N::Rotl(a, b) => ("rotl", vec![a, b]),
138 N::Sdiv(a, b) => ("sdiv", vec![a, b]),
139 N::Srem(a, b) => ("srem", vec![a, b]),
140 }
141}
142
143/// Is this one of the five derived-op node kinds of #192 phase 5 (the ones
144/// `ordeal-dag/v1` cannot express)?
145pub fn node_is_derived(node: &k::DagNode) -> bool {
146 use k::DagNode as N;
147 matches!(
148 node,
149 N::BvNot(_) | N::Neg(_) | N::Rotl(_, _) | N::Sdiv(_, _) | N::Srem(_, _)
150 )
151}
152
153/// The inverse of [`node_op`]: `None` for an unknown mnemonic or a wrong
154/// argument count (a reader reports that as malformed; well-formedness of
155/// the operands is the trusted `dag_wf`'s job, not the reader's).
156pub fn node_from_op(op: &str, args: &[usize]) -> Option<k::DagNode> {
157 use k::DagNode as N;
158 let one = || if args.len() == 1 { Some(args[0]) } else { None };
159 let two = || {
160 if args.len() == 2 {
161 Some((args[0], args[1]))
162 } else {
163 None
164 }
165 };
166 let three = || {
167 if args.len() == 3 {
168 Some((args[0], args[1], args[2]))
169 } else {
170 None
171 }
172 };
173 Some(match op {
174 "var" => N::Var(one()?),
175 "const" => {
176 let (s, w) = two()?;
177 N::Const(s, w)
178 }
179 "add" => {
180 let (a, b) = two()?;
181 N::Add(a, b)
182 }
183 "sub" => {
184 let (a, b) = two()?;
185 N::Sub(a, b)
186 }
187 "mul" => {
188 let (a, b) = two()?;
189 N::Mul(a, b)
190 }
191 "udiv" => {
192 let (a, b) = two()?;
193 N::Udiv(a, b)
194 }
195 "urem" => {
196 let (a, b) = two()?;
197 N::Urem(a, b)
198 }
199 "and" => {
200 let (a, b) = two()?;
201 N::And(a, b)
202 }
203 "or" => {
204 let (a, b) = two()?;
205 N::Or(a, b)
206 }
207 "xor" => {
208 let (a, b) = two()?;
209 N::Xor(a, b)
210 }
211 "shl" => {
212 let (a, b) = two()?;
213 N::Shl(a, b)
214 }
215 "lshr" => {
216 let (a, b) = two()?;
217 N::Lshr(a, b)
218 }
219 "ashr" => {
220 let (a, b) = two()?;
221 N::Ashr(a, b)
222 }
223 "rotr" => {
224 let (a, b) = two()?;
225 N::Rotr(a, b)
226 }
227 "extract" => {
228 let (hi, lo, a) = three()?;
229 N::Extract(hi, lo, a)
230 }
231 "concat" => {
232 let (a, b) = two()?;
233 N::Concat(a, b)
234 }
235 "zero_ext" => {
236 let (a, by) = two()?;
237 N::ZeroExt(a, by)
238 }
239 "sign_ext" => {
240 let (a, by) = two()?;
241 N::SignExt(a, by)
242 }
243 "ite" => {
244 let (c, t, e) = three()?;
245 N::Ite(c, t, e)
246 }
247 "eq" => {
248 let (a, b) = two()?;
249 N::Eq(a, b)
250 }
251 "ne" => {
252 let (a, b) = two()?;
253 N::Ne(a, b)
254 }
255 "ult" => {
256 let (a, b) = two()?;
257 N::Ult(a, b)
258 }
259 "ule" => {
260 let (a, b) = two()?;
261 N::Ule(a, b)
262 }
263 "ugt" => {
264 let (a, b) = two()?;
265 N::Ugt(a, b)
266 }
267 "uge" => {
268 let (a, b) = two()?;
269 N::Uge(a, b)
270 }
271 "slt" => {
272 let (a, b) = two()?;
273 N::Slt(a, b)
274 }
275 "sle" => {
276 let (a, b) = two()?;
277 N::Sle(a, b)
278 }
279 "sgt" => {
280 let (a, b) = two()?;
281 N::Sgt(a, b)
282 }
283 "sge" => {
284 let (a, b) = two()?;
285 N::Sge(a, b)
286 }
287 "not" => N::Not(one()?),
288 "bool_and" => {
289 let (a, b) = two()?;
290 N::BoolAnd(a, b)
291 }
292 "bool_or" => {
293 let (a, b) = two()?;
294 N::BoolOr(a, b)
295 }
296 "bvnot" => N::BvNot(one()?),
297 "neg" => N::Neg(one()?),
298 "rotl" => {
299 let (a, b) = two()?;
300 N::Rotl(a, b)
301 }
302 "sdiv" => {
303 let (a, b) = two()?;
304 N::Sdiv(a, b)
305 }
306 "srem" => {
307 let (a, b) = two()?;
308 N::Srem(a, b)
309 }
310 _ => return None,
311 })
312}
313
314/// The constant table as a `0`/`1` string, `bits[0]` first.
315pub fn bits_string(bits: &[bool]) -> String {
316 let mut s = String::with_capacity(bits.len());
317 for &b in bits {
318 s.push(if b { '1' } else { '0' });
319 }
320 s
321}
322
323/// Parse a `0`/`1` string back into a constant table; `None` on any other
324/// character.
325pub fn bits_from_string(s: &str) -> Option<Vec<bool>> {
326 let mut out = Vec::with_capacity(s.len());
327 for c in s.chars() {
328 match c {
329 '0' => out.push(false),
330 '1' => out.push(true),
331 _ => return None,
332 }
333 }
334 Some(out)
335}
336
337fn push_usizes(s: &mut String, xs: &[usize]) {
338 for x in xs {
339 s.push(' ');
340 s.push_str(&wire_usize(*x).to_string());
341 }
342}
343
344/// The portable spelling of an index in a bundle and in the canonical
345/// texts its hashes cover (TR-075): [`NO_IMAGE`] is `u64::MAX` on every
346/// target, every other index its value. On a 64-bit host this is the
347/// identity (`usize::MAX == u64::MAX`), so bundles and hashes are
348/// byte-identical to what 64-bit ordeal always wrote; on a 32-bit target
349/// (the wasm32-wasip2 `ordeal-recheck`) the sentinel keeps its spelling
350/// instead of becoming `4294967295`.
351pub fn wire_usize(x: usize) -> u64 {
352 if x == NO_IMAGE { u64::MAX } else { x as u64 }
353}
354
355/// The inverse of [`wire_usize`]: `u64::MAX` is [`NO_IMAGE`]; any other
356/// value must fit this target's `usize` (`None` otherwise — a reader
357/// reports it as malformed).
358pub fn unwire_usize(x: u64) -> Option<usize> {
359 if x == u64::MAX {
360 Some(NO_IMAGE)
361 } else {
362 // A plain index that happens to equal this target's `usize::MAX`
363 // (only possible on a 32-bit target: 4294967295) is NOT the
364 // sentinel. Reading it as one would make a 32-bit reader see a
365 // "no image" entry or a mux-fold request ([`MUX_FOLD_HINT`]) that
366 // a 64-bit reader does not, so it is refused as malformed.
367 usize::try_from(x).ok().filter(|&v| v != usize::MAX)
368 }
369}
370
371impl QueryDag {
372 /// Does the DAG use one of the derived-op node kinds of #192 phase 5?
373 #[must_use]
374 pub fn has_derived(&self) -> bool {
375 self.nodes.iter().any(node_is_derived)
376 }
377
378 /// Do the compaction hints ask for the mux fold ([`MUX_FOLD_HINT`],
379 /// issue #314)? Then the CNF is the one a reader derives WITH the
380 /// fold, and only a reader from v0.38.0 on can re-derive it.
381 #[must_use]
382 pub fn has_mux_fold(&self) -> bool {
383 self.hints.contains(&MUX_FOLD_HINT)
384 }
385
386 /// The `recheck.min_version` a bundle carrying this DAG names: `floor`
387 /// (the bundle format's own first reader), raised to `0.38.0` when a
388 /// hint asks for the mux fold — the first release whose trusted crate
389 /// can re-derive that CNF.
390 #[must_use]
391 pub fn min_reader_version(&self, floor: &'static str) -> &'static str {
392 if self.has_mux_fold() { "0.38.0" } else { floor }
393 }
394
395 /// The encoding tag this DAG is emitted under: the lowest one that can
396 /// express it — [`QUERY_ENCODING`] (`ordeal-dag/v1`, readable by
397 /// v0.27.0) unless a derived-op node is present, then
398 /// [`QUERY_ENCODING_V2`]; and [`QUERY_ENCODING_V3`] whenever a hint
399 /// asks for the mux fold, with or without derived-op nodes. A query
400 /// the fold never fires on keeps the tag, the bytes and the hash it
401 /// had before v0.38.0.
402 #[must_use]
403 pub fn encoding(&self) -> &'static str {
404 if self.has_mux_fold() {
405 QUERY_ENCODING_V3
406 } else if self.has_derived() {
407 QUERY_ENCODING_V2
408 } else {
409 QUERY_ENCODING
410 }
411 }
412
413 /// The canonical text the content hash covers (stable, diff-friendly):
414 /// the encoding tag ([`QueryDag::encoding`]), `nodes <n>`, one `<op>
415 /// <args…>` line per node, then `bits <bitstring>`, `roots <r…>` and
416 /// `hints <h…>`.
417 pub fn canonical_text(&self) -> String {
418 self.canonical_text_tagged(self.encoding())
419 }
420
421 /// [`QueryDag::canonical_text`] under an explicit encoding tag — what a
422 /// reader hashes to verify a block that DECLARES its tag (a v1-tagged
423 /// block hashes with the v1 tag even on a reader that would emit v2).
424 pub fn canonical_text_tagged(&self, encoding: &str) -> String {
425 let mut s = String::new();
426 s.push_str(encoding);
427 s.push('\n');
428 s.push_str("nodes ");
429 s.push_str(&self.nodes.len().to_string());
430 s.push('\n');
431 for n in &self.nodes {
432 let (op, args) = node_op(n);
433 s.push_str(op);
434 push_usizes(&mut s, &args);
435 s.push('\n');
436 }
437 s.push_str("bits ");
438 s.push_str(&bits_string(&self.bits));
439 s.push('\n');
440 s.push_str("roots");
441 push_usizes(&mut s, &self.roots);
442 s.push('\n');
443 s.push_str("hints");
444 push_usizes(&mut s, &self.hints);
445 s.push('\n');
446 s
447 }
448
449 /// `sha256(canonical_text)` — the bundle's `query.sha256` (rivet:
450 /// `query-sha256`). Integrity only: the verdict rests on the recheck.
451 #[must_use]
452 pub fn sha256(&self) -> String {
453 sha256_hex(self.canonical_text().as_bytes())
454 }
455
456 /// [`QueryDag::sha256`] under an explicit encoding tag (see
457 /// [`QueryDag::canonical_text_tagged`]).
458 #[must_use]
459 pub fn sha256_tagged(&self, encoding: &str) -> String {
460 sha256_hex(self.canonical_text_tagged(encoding).as_bytes())
461 }
462}
463
464/// A certificate together with the query it certifies (issue #192 phase
465/// 4): the v1 pair (`certificate.cnf`, `certificate.lrat`) plus the lowered
466/// [`QueryDag`]. [`QueryCertificate::recheck`] is the stronger re-check:
467/// the trusted crate re-encodes the DAG itself and checks the proof
468/// against the CNF *it* produced, so an accepted re-check proves the DAG
469/// unsatisfiable — `kernel.spec.check_query_sound`.
470#[derive(Clone, Debug)]
471pub struct QueryCertificate {
472 /// The v1 pair: the CNF the solver produced from the DAG, and the LRAT
473 /// proof the checker validated against it. `certificate.recheck()` is
474 /// the v1 (CNF-level) re-check, still available.
475 pub certificate: Certificate,
476 /// The lowered query the CNF was encoded from.
477 pub query: QueryDag,
478}
479
480/// Why a [`QueryCertificate::recheck`] could not confirm the proof.
481#[derive(Debug)]
482pub enum QueryRecheckError {
483 /// The LRAT bytes were not valid UTF-8 (only possible for a hand-built
484 /// certificate).
485 NotText,
486 /// The trusted crate rejected: the DAG is malformed or too large, or
487 /// the proof does not refute the CNF re-encoded from it.
488 Rejected(ordeal_lrat::QueryCheckError),
489 /// The trusted re-encoding of the DAG is not the CNF the certificate
490 /// carries — the bundle is internally inconsistent (a v1 reader would
491 /// be checking a different formula than the query's).
492 CnfMismatch,
493}
494
495impl std::fmt::Display for QueryRecheckError {
496 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497 match self {
498 QueryRecheckError::NotText => write!(f, "LRAT certificate is not valid UTF-8"),
499 QueryRecheckError::Rejected(e) => write!(f, "trusted query re-check rejected: {e}"),
500 QueryRecheckError::CnfMismatch => write!(
501 f,
502 "the CNF re-encoded from the query differs from the carried CNF"
503 ),
504 }
505 }
506}
507
508impl std::error::Error for QueryRecheckError {}
509
510impl QueryCertificate {
511 /// Re-establish the verdict at the QUERY level, with zero trust in the
512 /// solver: `ordeal_lrat::check_query` checks the DAG well-formed
513 /// (`dag_wf`), re-runs the proven lowering over it, and checks the LRAT
514 /// proof against the CNF it produced. `Ok(())` ⟹ no assignment to the
515 /// DAG's variables makes every root true (`check_query_sound`). The
516 /// re-encoded CNF must also equal `certificate.cnf`, so the v1 pair a
517 /// bundle carries for older readers is the query's CNF and not another.
518 pub fn recheck(&self) -> Result<(), QueryRecheckError> {
519 let text = self
520 .certificate
521 .lrat_text()
522 .ok_or(QueryRecheckError::NotText)?;
523 let q = &self.query;
524 let cnf = ordeal_lrat::check_query(&q.nodes, &q.bits, &q.roots, &q.hints, text)
525 .map_err(QueryRecheckError::Rejected)?;
526 if cnf != self.certificate.cnf {
527 return Err(QueryRecheckError::CnfMismatch);
528 }
529 Ok(())
530 }
531}
532
533// ── #192 phase 6: the SAT direction at the query level ─────────────────
534
535/// The `inputs.encoding` value: `bits` is the DAG's primary-input
536/// assignment as a `0`/`1` string, input 0 first — the `Var` nodes' bits
537/// in node order, LSB first within each variable (exactly the `inp` list
538/// the DAG semantics `dagSim` reads and `check_query_model` evaluates).
539pub const INPUTS_ENCODING: &str = "ordeal-inputs/v1";
540
541/// The DAG's primary-input assignment a SAT verdict is re-checked with
542/// (issue #192 phase 6, TR-065): what the trusted
543/// `ordeal_lrat::check_query_model` consumes, plus the untrusted map from
544/// the model's named variables to the `Var` nodes that read those bits.
545#[derive(Clone, Default, PartialEq, Eq)]
546pub struct QueryInputs {
547 /// `bits[k]` is primary input `k` (see [`INPUTS_ENCODING`]).
548 pub bits: Vec<bool>,
549 /// Per model variable: (name, width, index of its `Var` node in the
550 /// DAG). Untrusted glue — the DAG builder's choice of node for a name
551 /// — carried so a reader can confirm the advertised model IS the
552 /// assignment the trusted check accepted
553 /// ([`QueryInputs::check_consistent`]).
554 pub vars: Vec<(String, u32, usize)>,
555}
556
557impl std::fmt::Debug for QueryInputs {
558 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559 f.debug_struct("QueryInputs")
560 .field("bits", &self.bits.len())
561 .field("vars", &self.vars.len())
562 .field("sha256", &self.sha256())
563 .finish()
564 }
565}
566
567/// The input offset of every `Var` node: `(node, offset, width)` in node
568/// order — the encoder numbers the inputs this way (`dagNin`).
569fn var_offsets(nodes: &[k::DagNode]) -> Vec<(usize, usize, usize)> {
570 let mut out = Vec::new();
571 let mut nin = 0usize;
572 for (i, n) in nodes.iter().enumerate() {
573 if let k::DagNode::Var(w) = *n {
574 out.push((i, nin, w));
575 nin = nin.saturating_add(w);
576 }
577 }
578 out
579}
580
581impl QueryInputs {
582 /// Build the assignment from a model: for every `Var` node of the
583 /// DAG, the bits (LSB first) of the model value of the variable the
584 /// builder mapped to it (`vars`, from `dag::Dag::vars`); a variable
585 /// without a binding reads as zero (and fails
586 /// [`QueryInputs::check_consistent`]).
587 #[must_use]
588 pub fn from_model(
589 query: &QueryDag,
590 vars: &[(String, u32, usize)],
591 model: &crate::certificate::Model,
592 ) -> QueryInputs {
593 let mut bits = Vec::new();
594 for (node, _offset, width) in var_offsets(&query.nodes) {
595 let value = vars
596 .iter()
597 .find(|(_, _, n)| *n == node)
598 .and_then(|(name, _, _)| model.assignments.iter().find(|(k, _)| k == name))
599 .map_or(0u128, |(_, v)| *v);
600 for j in 0..width {
601 // A `Var` wider than 128 never reaches here (`Sort` caps the
602 // width); the guard keeps the shift in range regardless.
603 bits.push(j < 128 && (value >> j) & 1 == 1);
604 }
605 }
606 QueryInputs {
607 bits,
608 vars: vars.to_vec(),
609 }
610 }
611
612 /// The canonical text the content hash covers: the encoding tag,
613 /// `bits <bitstring>`, then one `var <name> <width> <node>` line per
614 /// variable.
615 pub fn canonical_text(&self) -> String {
616 let mut s = String::new();
617 s.push_str(INPUTS_ENCODING);
618 s.push('\n');
619 s.push_str("bits ");
620 s.push_str(&bits_string(&self.bits));
621 s.push('\n');
622 for (name, width, node) in &self.vars {
623 s.push_str("var ");
624 s.push_str(name);
625 s.push(' ');
626 s.push_str(&width.to_string());
627 s.push(' ');
628 s.push_str(&node.to_string());
629 s.push('\n');
630 }
631 s
632 }
633
634 /// `sha256(canonical_text)` — the bundle's `inputs.sha256`. Integrity
635 /// only: the verdict rests on the recheck.
636 #[must_use]
637 pub fn sha256(&self) -> String {
638 sha256_hex(self.canonical_text().as_bytes())
639 }
640
641 /// The UNTRUSTED half of a SAT recheck: the advertised model is the
642 /// assignment. Every model binding names a `vars` entry whose node is
643 /// a `Var` node of that width, and the model value's bits equal the
644 /// input bits at that node's offset. (What this does NOT establish —
645 /// that the DAG asks the caller's question — is the DAG builder's
646 /// trust, as for the UNSAT direction.)
647 pub fn check_consistent(
648 &self,
649 query: &QueryDag,
650 model: &crate::certificate::Model,
651 ) -> Result<(), QueryModelRecheckError> {
652 for (name, value) in &model.assignments {
653 let Some((_, width, node)) = self.vars.iter().find(|(n, _, _)| n == name) else {
654 return Err(QueryModelRecheckError::UnmappedVariable(name.clone()));
655 };
656 let w = *width as usize;
657 if !matches!(query.nodes.get(*node), Some(k::DagNode::Var(vw)) if *vw == w) {
658 return Err(QueryModelRecheckError::UnmappedVariable(name.clone()));
659 }
660 // The bit comparison is the trusted crate's since #192 phase
661 // 7d: `var_offset` is proven to compute the node's input offset
662 // (`dagNin` of the prefix) and `check_input_value` to accept
663 // iff the value's bits ARE the inputs there, LSB first
664 // (`kernel.spec.check_input_value_sound`).
665 let Ok(offset) = ordeal_lrat::var_offset(&query.nodes, *node) else {
666 return Err(QueryModelRecheckError::UnmappedVariable(name.clone()));
667 };
668 if offset.saturating_add(w) > self.bits.len() {
669 return Err(QueryModelRecheckError::UnmappedVariable(name.clone()));
670 }
671 if !ordeal_lrat::check_input_value(&self.bits, offset, w, *value) {
672 return Err(QueryModelRecheckError::InputMismatch(name.clone()));
673 }
674 }
675 Ok(())
676 }
677}
678
679/// A SAT witness together with the query it satisfies (issue #192 phase
680/// 6): the v1 [`SatCertificate`] (model, CNF, assignment, bit map) plus
681/// the lowered [`QueryDag`] and the DAG's input assignment
682/// ([`QueryInputs`]). [`QuerySatCertificate::recheck`] is the stronger
683/// re-check: the trusted crate evaluates the DAG itself under the inputs
684/// (`ordeal_lrat::check_query_model`), so an accepted re-check proves the
685/// DAG satisfiable — `kernel.spec.check_query_model_sound`, in the same
686/// semantics `check_query_sound` negates. The SAT twin of
687/// [`QueryCertificate`].
688#[derive(Clone, Debug)]
689pub struct QuerySatCertificate {
690 /// The v1 witness: CNF-level, re-checked by `check_sat` /
691 /// `check_binding` (`witness.recheck()`), still available.
692 pub witness: SatCertificate,
693 /// The lowered query the witness is a model of.
694 pub query: QueryDag,
695 /// The DAG's input assignment and the model-to-node map.
696 pub inputs: QueryInputs,
697}
698
699/// Why a [`QuerySatCertificate::recheck`] could not confirm the model.
700#[derive(Debug)]
701pub enum QueryModelRecheckError {
702 /// The v1 (CNF-level) witness failed its own recheck.
703 Witness(crate::witness::SatRecheckError),
704 /// A model binding has no `vars` entry, its entry does not name a
705 /// `Var` node of its width, or that node's bits are not in the
706 /// assignment — the advertised model is not covered by the inputs.
707 UnmappedVariable(String),
708 /// A model binding's value disagrees with the input bits of its node.
709 InputMismatch(String),
710 /// The trusted crate rejected: the DAG is malformed or too large, the
711 /// assignment is too short, or a root evaluates to false under it.
712 Rejected(ordeal_lrat::ModelError),
713}
714
715impl std::fmt::Display for QueryModelRecheckError {
716 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
717 match self {
718 QueryModelRecheckError::Witness(e) => write!(f, "witness recheck failed: {e}"),
719 QueryModelRecheckError::UnmappedVariable(n) => {
720 write!(
721 f,
722 "model binding '{n}' is not mapped to a Var node of the query"
723 )
724 }
725 QueryModelRecheckError::InputMismatch(n) => {
726 write!(f, "model binding '{n}' disagrees with the query inputs")
727 }
728 QueryModelRecheckError::Rejected(e) => {
729 write!(f, "trusted model re-check rejected: {e:?}")
730 }
731 }
732 }
733}
734
735impl std::error::Error for QueryModelRecheckError {}
736
737impl QuerySatCertificate {
738 /// Re-establish the verdict at the QUERY level, with zero trust in the
739 /// solver: the v1 witness recheck first (defence in depth — the
740 /// CNF-level claim), the untrusted consistency check that the
741 /// advertised model is the assignment, then the trusted
742 /// `ordeal_lrat::check_query_model`: the DAG well-formed (`dag_wf`),
743 /// the assignment covering its inputs, and EVERY root true under it
744 /// (`check_query_model_sound`). The verdict rests on the last step.
745 pub fn recheck(&self) -> Result<(), QueryModelRecheckError> {
746 self.witness
747 .recheck()
748 .map_err(QueryModelRecheckError::Witness)?;
749 self.inputs
750 .check_consistent(&self.query, &self.witness.model)?;
751 let q = &self.query;
752 ordeal_lrat::check_query_model(&q.nodes, &q.bits, &q.roots, &self.inputs.bits)
753 .map_err(QueryModelRecheckError::Rejected)
754 }
755}
756
757// ── #192 phase 7: the term as asked, next to the DAG it was lowered to ──
758
759/// The `term.encoding` value: the caller's assertions flattened as they
760/// were asked (`dag::flatten` — no canonicalization, no hash-consing;
761/// variables shared by name, constants interned), in the
762/// [`QUERY_ENCODING_V2`] node spelling, with the variable names and the
763/// map to the lowered DAG's nodes.
764pub const TERM_ENCODING: &str = "ordeal-term/v1";
765
766/// The `term.encoding` of a sliver bundle (TR-072, `ordeal-cert/v4`): the
767/// LOWERED core — `sliver::lower`'s output — flattened with hash-consing
768/// (so that a shared lowered subterm is one node, which is what the read
769/// and call tables are keyed on) and with the lowered index of every read
770/// and the lowered arguments of every call appended as non-root nodes
771/// (so the trusted check and the model can always reach them). The
772/// question as asked is the `ext` block; this term is the checked
773/// intermediate, as the `query` block is.
774pub const TERM_ENCODING_V2: &str = "ordeal-term/v2";
775
776/// The `ext.encoding` value (TR-072): the extended query flattened as it
777/// was asked — `ordeal::sliver::flatten_ext` — plus the untrusted map
778/// and tables the trusted `check_sliver_lowering` verifies.
779pub const EXT_ENCODING: &str = "ordeal-ext/v1";
780
781/// The term a `v3` certificate is about (#192 phase 7): what the caller
782/// asserted, flattened, plus the untrusted index map from its nodes to the
783/// lowered [`QueryDag`]'s. The trusted `ordeal_lrat::check_term_dag`
784/// verifies, node by node along the map, that the DAG is a
785/// semantics-preserving rewrite of this term — the two rewrites
786/// canonicalization makes (a commutative swap, a comparison mirror), a
787/// constant fold (evaluated by the proven encoder and simulator) and
788/// hash-consing (the map itself) — so a consumer that compares this block
789/// with its own query certifies the QUESTION, not the solver's DAG.
790#[derive(Clone, Default, PartialEq, Eq)]
791pub struct QueryTerm {
792 /// The term's nodes, operands before operators, left to right.
793 pub nodes: Vec<k::DagNode>,
794 /// The term's constant table (LSB first).
795 pub bits: Vec<bool>,
796 /// The asserted nodes, one per assertion, in assertion order.
797 pub roots: Vec<usize>,
798 /// Per variable: (name, width, its `Var` node in `nodes`).
799 pub vars: Vec<(String, u32, usize)>,
800 /// `map[i]`: the lowered DAG's node term node `i` became, or
801 /// [`NO_IMAGE`] (`usize::MAX`) for a node that has none
802 /// (the inside of a folded constant). Untrusted advice: the trusted
803 /// check rejects a wrong entry.
804 pub map: Vec<usize>,
805 /// Whether this is a sliver bundle's lowered core ([`TERM_ENCODING_V2`]:
806 /// hash-consed, with the reads' indices and the calls' arguments
807 /// appended) rather than the assertions flattened 1:1
808 /// ([`TERM_ENCODING`]). The canonical text carries the tag.
809 pub shared: bool,
810}
811
812impl std::fmt::Debug for QueryTerm {
813 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
814 f.debug_struct("QueryTerm")
815 .field("nodes", &self.nodes.len())
816 .field("bits", &self.bits.len())
817 .field("roots", &self.roots)
818 .field("vars", &self.vars.len())
819 .field("shared", &self.shared)
820 .field("sha256", &self.sha256())
821 .finish()
822 }
823}
824
825impl QueryTerm {
826 /// The `term.encoding` this term carries.
827 pub fn encoding(&self) -> &'static str {
828 if self.shared {
829 TERM_ENCODING_V2
830 } else {
831 TERM_ENCODING
832 }
833 }
834
835 /// The trusted check: is `query` a semantics-preserving rewrite of
836 /// this term along the map (`ordeal_lrat::check_term_dag`,
837 /// `kernel.spec.check_term_dag_sound`)?
838 pub fn check(&self, query: &QueryDag) -> Result<(), ordeal_lrat::TermError> {
839 ordeal_lrat::check_term_dag(
840 &self.nodes,
841 &self.bits,
842 &self.roots,
843 &self.map,
844 &query.nodes,
845 &query.bits,
846 &query.roots,
847 )
848 }
849
850 /// The canonical text the content hash covers: the encoding tag,
851 /// `nodes <n>`, one `<op> <args…>` line per node, `bits <bitstring>`,
852 /// `roots <r…>`, one `var <name> <width> <node>` line per variable,
853 /// then `map <m…>`.
854 pub fn canonical_text(&self) -> String {
855 let mut s = String::new();
856 s.push_str(self.encoding());
857 s.push('\n');
858 s.push_str("nodes ");
859 s.push_str(&self.nodes.len().to_string());
860 s.push('\n');
861 for n in &self.nodes {
862 let (op, args) = node_op(n);
863 s.push_str(op);
864 push_usizes(&mut s, &args);
865 s.push('\n');
866 }
867 s.push_str("bits ");
868 s.push_str(&bits_string(&self.bits));
869 s.push('\n');
870 s.push_str("roots");
871 push_usizes(&mut s, &self.roots);
872 s.push('\n');
873 for (name, width, node) in &self.vars {
874 s.push_str("var ");
875 s.push_str(name);
876 s.push(' ');
877 s.push_str(&width.to_string());
878 s.push(' ');
879 s.push_str(&node.to_string());
880 s.push('\n');
881 }
882 s.push_str("map");
883 push_usizes(&mut s, &self.map);
884 s.push('\n');
885 s
886 }
887
888 /// `sha256(canonical_text)` — the bundle's `term.sha256`. Integrity
889 /// only: the verdict rests on the recheck.
890 #[must_use]
891 pub fn sha256(&self) -> String {
892 sha256_hex(self.canonical_text().as_bytes())
893 }
894}
895
896/// An UNSAT certificate together with the query it refutes AND the term
897/// that query was lowered from (#192 phase 7, `ordeal-cert/v3`).
898/// [`TermCertificate::recheck`] is the strongest re-check: the trusted
899/// crate relates the term to the DAG (`check_term_dag`) and refutes the
900/// DAG (`check_query`), so an accepted re-check proves the TERM
901/// unsatisfiable — `kernel.spec.check_term_unsat_sound`.
902#[derive(Clone, Debug)]
903pub struct TermCertificate {
904 /// The v2 certificate: the v1 pair plus the lowered query.
905 pub query: QueryCertificate,
906 /// The term and its map onto `query.query`.
907 pub term: QueryTerm,
908}
909
910/// Why a [`TermCertificate::recheck`] could not confirm the proof.
911#[derive(Debug)]
912pub enum TermRecheckError {
913 /// The trusted crate rejected the term-to-DAG correspondence: the DAG
914 /// is not a rewrite of the term along the map.
915 Term(ordeal_lrat::TermError),
916 /// The v2 (query-level) re-check failed.
917 Query(QueryRecheckError),
918}
919
920impl std::fmt::Display for TermRecheckError {
921 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
922 match self {
923 TermRecheckError::Term(e) => write!(f, "trusted term re-check rejected: {e:?}"),
924 TermRecheckError::Query(e) => write!(f, "{e}"),
925 }
926 }
927}
928
929impl std::error::Error for TermRecheckError {}
930
931impl TermCertificate {
932 /// Re-establish the verdict at the TERM level, with zero trust in the
933 /// solver: `ordeal_lrat::check_term_dag` over the term, the map and the
934 /// lowered DAG, then the v2 recheck (`ordeal_lrat::check_query`).
935 /// `Ok(())` ⟹ no assignment to the term's variables makes every
936 /// asserted root true (`check_term_unsat_sound`).
937 pub fn recheck(&self) -> Result<(), TermRecheckError> {
938 self.term
939 .check(&self.query.query)
940 .map_err(TermRecheckError::Term)?;
941 self.query.recheck().map_err(TermRecheckError::Query)
942 }
943}
944
945/// A SAT witness together with the query it satisfies AND the term that
946/// query was lowered from (#192 phase 7, `ordeal-cert/v3`).
947/// [`TermSatCertificate::recheck`] relates the term to the DAG
948/// (`check_term_dag`), evaluates the DAG under the inputs
949/// (`check_query_model`) and, new, ties every advertised model value to
950/// the inputs with the proven `var_offset` / `check_input_value` through
951/// the term's own variable map — so an accepted re-check proves the TERM
952/// satisfied by the advertised model (`check_term_model_sound`, and the
953/// only untrusted step left is the variable's name).
954#[derive(Clone, Debug)]
955pub struct TermSatCertificate {
956 /// The v2 SAT certificate: the v1 witness plus the query and inputs.
957 pub query: QuerySatCertificate,
958 /// The term and its map onto `query.query`.
959 pub term: QueryTerm,
960}
961
962/// Why a [`TermSatCertificate::recheck`] could not confirm the model.
963#[derive(Debug)]
964pub enum TermModelRecheckError {
965 /// The trusted crate rejected the term-to-DAG correspondence.
966 Term(ordeal_lrat::TermError),
967 /// The v2 (query-level) re-check failed.
968 Query(QueryModelRecheckError),
969 /// A model binding is not a variable of the term, its variable has no
970 /// image in the DAG, or the value is not the input bits at that
971 /// image's offset (`check_input_value` rejected).
972 Binding(String),
973}
974
975impl std::fmt::Display for TermModelRecheckError {
976 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
977 match self {
978 TermModelRecheckError::Term(e) => {
979 write!(f, "trusted term re-check rejected: {e:?}")
980 }
981 TermModelRecheckError::Query(e) => write!(f, "{e}"),
982 TermModelRecheckError::Binding(n) => {
983 write!(
984 f,
985 "model binding '{n}' is not the term variable's input bits"
986 )
987 }
988 }
989 }
990}
991
992impl std::error::Error for TermModelRecheckError {}
993
994impl TermSatCertificate {
995 /// The term-level SAT re-check: `check_term_dag`, the v2 recheck
996 /// (witness, consistency, `check_query_model`), then every model
997 /// binding through the TERM's variable map: its `Var` node's image
998 /// under the map, that image's input offset (`var_offset`, proven),
999 /// and the value's bits at that offset (`check_input_value`, proven).
1000 pub fn recheck(&self) -> Result<(), TermModelRecheckError> {
1001 self.term
1002 .check(&self.query.query)
1003 .map_err(TermModelRecheckError::Term)?;
1004 self.query.recheck().map_err(TermModelRecheckError::Query)?;
1005 let dag = &self.query.query;
1006 let inputs = &self.query.inputs.bits;
1007 for (name, value) in &self.query.witness.model.assignments {
1008 let bad = || TermModelRecheckError::Binding(name.clone());
1009 let Some((_, width, node)) = self.term.vars.iter().find(|(n, _, _)| n == name) else {
1010 return Err(bad());
1011 };
1012 let w = *width as usize;
1013 if !matches!(self.term.nodes.get(*node), Some(k::DagNode::Var(vw)) if *vw == w) {
1014 return Err(bad());
1015 }
1016 let image = *self.term.map.get(*node).ok_or_else(bad)?;
1017 if image == NO_IMAGE {
1018 return Err(bad());
1019 }
1020 let offset = ordeal_lrat::var_offset(&dag.nodes, image).map_err(|_| bad())?;
1021 if !ordeal_lrat::check_input_value(inputs, offset, w, *value) {
1022 return Err(bad());
1023 }
1024 }
1025 // TR-073: the binding BY NAME through the kernel's variable table
1026 // (`term.vars` is the table verbatim): every mapped table entry
1027 // reads the value advertised under its name
1028 // (`ordeal_lrat::check_tree_model`, `kernel.spec.tree_model_sound`).
1029 let (var_node, var_width, values) =
1030 table_values(&self.term.vars, &self.term.map, &self.query.witness.model)
1031 .map_err(TermModelRecheckError::Binding)?;
1032 if !ordeal_lrat::check_tree_model(
1033 &var_node,
1034 &var_width,
1035 &self.term.map,
1036 &dag.nodes,
1037 inputs,
1038 &values,
1039 ) {
1040 return Err(TermModelRecheckError::Binding("<table>".into()));
1041 }
1042 Ok(())
1043 }
1044}
1045
1046/// The kernel's model-binding arguments: `(var_node, var_width, values)`.
1047type ModelBinding = (Vec<usize>, Vec<usize>, Vec<u128>);
1048
1049/// The kernel's model-binding arguments from a variable table: the nodes,
1050/// the widths, and per entry the value the model advertises under its
1051/// name (`0` for an entry the DAG dropped — `map` says `NO_IMAGE` — which
1052/// the kernel skips; an entry with an image but no advertised value is an
1053/// error, named).
1054fn table_values(
1055 vars: &[(String, u32, usize)],
1056 map: &[usize],
1057 model: &crate::certificate::Model,
1058) -> Result<ModelBinding, String> {
1059 let mut var_node = Vec::with_capacity(vars.len());
1060 let mut var_width = Vec::with_capacity(vars.len());
1061 let mut values = Vec::with_capacity(vars.len());
1062 for (name, width, node) in vars {
1063 var_node.push(*node);
1064 var_width.push(*width as usize);
1065 let mapped = map.get(*node).is_some_and(|&m| m != NO_IMAGE);
1066 match model.assignments.iter().find(|(n, _)| n == name) {
1067 Some((_, v)) => values.push(*v),
1068 None if !mapped => values.push(0),
1069 None => return Err(name.clone()),
1070 }
1071 }
1072 Ok((var_node, var_width, values))
1073}
1074
1075// ── TR-072: the extended query, next to the core it was lowered to ──
1076
1077use crate::sliver::{ExtQuery, SliverModel};
1078use ordeal_lrat::{ExtNode, SliverCheckError};
1079
1080/// The `ext` block of an `ordeal-cert/v4` bundle (TR-072): the extended
1081/// query as asked ([`ExtQuery`]) plus the untrusted map from its nodes to
1082/// the lowered core's ([`QueryTerm`] with [`TERM_ENCODING_V2`]) and the
1083/// untrusted read and call tables — everything
1084/// `ordeal_lrat::check_sliver_lowering` verifies.
1085#[derive(Clone, Default, PartialEq, Eq)]
1086pub struct SliverBlock {
1087 /// The extended query as asked.
1088 pub ext: ExtQuery,
1089 /// Extended node → core node, [`NO_IMAGE`] for none.
1090 pub map: Vec<usize>,
1091 /// The read table, 3 per entry: `(read var node, array id, index node)`.
1092 pub reads: Vec<usize>,
1093 /// The call table, 4 per entry: `(result var node, function id,
1094 /// first argument in `cargs`, arity)`.
1095 pub calls: Vec<usize>,
1096 /// The calls' argument nodes.
1097 pub cargs: Vec<usize>,
1098}
1099
1100impl std::fmt::Debug for SliverBlock {
1101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1102 f.debug_struct("SliverBlock")
1103 .field("ext", &self.ext)
1104 .field("reads", &(self.reads.len() / 3))
1105 .field("calls", &(self.calls.len() / 4))
1106 .field("sha256", &self.sha256())
1107 .finish()
1108 }
1109}
1110
1111/// The spelling of an extended node in the `ext` block and its canonical
1112/// text: a closed node as [`node_op`], `["select", aid, idx, s, n]`,
1113/// `["call", fid, w, s, n]`.
1114pub fn ext_node_op(node: &ExtNode) -> (&'static str, Vec<usize>) {
1115 match node {
1116 ExtNode::Core(nd) => node_op(nd),
1117 ExtNode::Select(aid, idx, s, n) => ("select", vec![*aid, *idx, *s, *n]),
1118 ExtNode::Call(fid, w, s, n) => ("call", vec![*fid, *w, *s, *n]),
1119 }
1120}
1121
1122/// The inverse of [`ext_node_op`]; `None` for an unknown spelling.
1123pub fn ext_node_from_op(op: &str, args: &[usize]) -> Option<ExtNode> {
1124 match (op, args) {
1125 ("select", [aid, idx, s, n]) => Some(ExtNode::Select(*aid, *idx, *s, *n)),
1126 ("call", [fid, w, s, n]) => Some(ExtNode::Call(*fid, *w, *s, *n)),
1127 _ => node_from_op(op, args).map(ExtNode::Core),
1128 }
1129}
1130
1131impl SliverBlock {
1132 /// The trusted check: is `term` (the lowered core) the elimination of
1133 /// the extended query along the map and tables
1134 /// (`ordeal_lrat::check_sliver_lowering`,
1135 /// `kernel.spec.check_sliver_lowering_sound`)?
1136 pub fn check(&self, term: &QueryTerm) -> Result<(), SliverCheckError> {
1137 ordeal_lrat::check_sliver_lowering(
1138 &self.ext.nodes,
1139 &self.ext.bits,
1140 &self.ext.side,
1141 &self.ext.roots,
1142 &self.map,
1143 &self.reads,
1144 &self.calls,
1145 &self.cargs,
1146 &term.nodes,
1147 &term.bits,
1148 &term.roots,
1149 )
1150 }
1151
1152 /// The canonical text the content hash covers: the encoding tag,
1153 /// `nodes <n>`, one `<op> <args…>` line per node, `bits <bitstring>`,
1154 /// `side <s…>`, `roots <r…>`, one `var <name> <width> <node>` line per
1155 /// variable, one `array <name>` line per array id, one `func <name>
1156 /// <width>` line per function id, then `map <m…>`, `reads <r…>`,
1157 /// `calls <c…>`, `cargs <a…>`.
1158 pub fn canonical_text(&self) -> String {
1159 let mut s = String::new();
1160 s.push_str(EXT_ENCODING);
1161 s.push('\n');
1162 s.push_str("nodes ");
1163 s.push_str(&self.ext.nodes.len().to_string());
1164 s.push('\n');
1165 for n in &self.ext.nodes {
1166 let (op, args) = ext_node_op(n);
1167 s.push_str(op);
1168 push_usizes(&mut s, &args);
1169 s.push('\n');
1170 }
1171 s.push_str("bits ");
1172 s.push_str(&bits_string(&self.ext.bits));
1173 s.push('\n');
1174 s.push_str("side");
1175 push_usizes(&mut s, &self.ext.side);
1176 s.push('\n');
1177 s.push_str("roots");
1178 push_usizes(&mut s, &self.ext.roots);
1179 s.push('\n');
1180 for (name, width, node) in &self.ext.vars {
1181 s.push_str("var ");
1182 s.push_str(name);
1183 s.push(' ');
1184 s.push_str(&width.to_string());
1185 s.push(' ');
1186 s.push_str(&node.to_string());
1187 s.push('\n');
1188 }
1189 for name in &self.ext.arrays {
1190 s.push_str("array ");
1191 s.push_str(name);
1192 s.push('\n');
1193 }
1194 for (name, width) in &self.ext.funcs {
1195 s.push_str("func ");
1196 s.push_str(name);
1197 s.push(' ');
1198 s.push_str(&width.to_string());
1199 s.push('\n');
1200 }
1201 for (key, xs) in [
1202 ("map", &self.map),
1203 ("reads", &self.reads),
1204 ("calls", &self.calls),
1205 ("cargs", &self.cargs),
1206 ] {
1207 s.push_str(key);
1208 push_usizes(&mut s, xs);
1209 s.push('\n');
1210 }
1211 s
1212 }
1213
1214 /// `sha256(canonical_text)` — the bundle's `ext.sha256`. Integrity
1215 /// only: the verdict rests on the recheck.
1216 #[must_use]
1217 pub fn sha256(&self) -> String {
1218 sha256_hex(self.canonical_text().as_bytes())
1219 }
1220
1221 /// The extended model a core model denotes — the pullback the SAT
1222 /// capstone is stated with (`kernel.spec.check_sliver_model_sound`):
1223 /// the lowered core is evaluated under the model with the proven
1224 /// encoder and simulator, and then every base array holds, at each
1225 /// read's index value, the read variable's value; every function maps
1226 /// each call's argument values to the result variable's value; the
1227 /// query variables keep their bindings. Cells and tuples no read or
1228 /// call touched are free and read as `0`. `None` if a table entry is
1229 /// out of range (the trusted check would have rejected it).
1230 pub fn pullback_model(
1231 &self,
1232 term: &QueryTerm,
1233 model: &crate::certificate::Model,
1234 ) -> Option<SliverModel> {
1235 let dag = QueryDag {
1236 nodes: term.nodes.clone(),
1237 bits: term.bits.clone(),
1238 roots: term.roots.clone(),
1239 hints: Vec::new(),
1240 };
1241 let inputs = QueryInputs::from_model(&dag, &term.vars, model);
1242 let mut raw = k::aig_new();
1243 let (words, _) = k::encode(&mut raw, &term.nodes, &term.bits, &[]);
1244 let vals = k::simulate(&raw, &inputs.bits);
1245 let value = |node: usize| -> Option<u128> {
1246 let word = words.get(node)?;
1247 let mut v = 0u128;
1248 for (j, l) in word.iter().enumerate().take(128) {
1249 if k::eval_lit(&vals, *l) {
1250 v |= 1u128 << j;
1251 }
1252 }
1253 Some(v)
1254 };
1255 let mut out = SliverModel::default();
1256 for (name, _, _) in &self.ext.vars {
1257 if let Some((_, v)) = model.assignments.iter().find(|(n, _)| n == name) {
1258 out.env.insert(name.clone(), *v);
1259 }
1260 }
1261 for &[var, aid, idx] in self.reads.as_chunks::<3>().0 {
1262 let array = self.ext.arrays.get(aid)?;
1263 let i = value(idx)? as u32;
1264 let v = value(var)? as u8;
1265 out.arrays.entry(array.clone()).or_default().insert(i, v);
1266 }
1267 for &[var, fid, s, n] in self.calls.as_chunks::<4>().0 {
1268 let (func, _) = self.ext.funcs.get(fid)?;
1269 let args = self.cargs.get(s..s.checked_add(n)?)?;
1270 let argv = args.iter().map(|&a| value(a)).collect::<Option<Vec<_>>>()?;
1271 out.calls.insert((func.clone(), argv), value(var)?);
1272 }
1273 Some(out)
1274 }
1275}
1276
1277/// An UNSAT certificate about an EXTENDED query (TR-072, `ordeal-cert/v4`):
1278/// the v3 term certificate about the lowered core, plus the `ext` block
1279/// relating that core to the query as asked.
1280/// [`SliverCertificate::recheck`] is the strongest re-check: the trusted
1281/// crate relates the extended query to the core (`check_sliver_lowering`),
1282/// the core to the DAG (`check_term_dag`) and refutes the DAG
1283/// (`check_query`), so an accepted re-check proves the EXTENDED query
1284/// unsatisfiable under every array and UF interpretation —
1285/// `kernel.spec.check_sliver_unsat_sound`.
1286#[derive(Clone, Debug)]
1287pub struct SliverCertificate {
1288 /// The v3 certificate about the lowered core.
1289 pub term: TermCertificate,
1290 /// The extended query, its map and tables onto `term.term`.
1291 pub sliver: SliverBlock,
1292}
1293
1294/// Why a [`SliverCertificate::recheck`] could not confirm the proof.
1295#[derive(Debug)]
1296pub enum SliverRecheckError {
1297 /// The trusted crate rejected the extended-to-core correspondence.
1298 Sliver(SliverCheckError),
1299 /// The v3 (term-level) re-check failed.
1300 Term(TermRecheckError),
1301}
1302
1303impl std::fmt::Display for SliverRecheckError {
1304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1305 match self {
1306 SliverRecheckError::Sliver(e) => write!(f, "trusted sliver re-check rejected: {e:?}"),
1307 SliverRecheckError::Term(e) => write!(f, "{e}"),
1308 }
1309 }
1310}
1311
1312impl std::error::Error for SliverRecheckError {}
1313
1314impl SliverCertificate {
1315 /// Re-establish the verdict at the EXTENDED level, with zero trust in
1316 /// the solver: `check_sliver_lowering`, then the v3 recheck.
1317 pub fn recheck(&self) -> Result<(), SliverRecheckError> {
1318 self.sliver
1319 .check(&self.term.term)
1320 .map_err(SliverRecheckError::Sliver)?;
1321 self.term.recheck().map_err(SliverRecheckError::Term)
1322 }
1323}
1324
1325/// A SAT witness about an EXTENDED query (TR-072, `ordeal-cert/v4`): the
1326/// v3 SAT certificate about the lowered core, the `ext` block, and the
1327/// extended model the core model pulls back to
1328/// ([`SliverBlock::pullback_model`]). An accepted
1329/// [`SliverSatCertificate::recheck`] proves the EXTENDED query satisfied
1330/// by an interpretation built from the model —
1331/// `kernel.spec.check_sliver_model_sound`.
1332#[derive(Clone, Debug)]
1333pub struct SliverSatCertificate {
1334 /// The v3 SAT certificate about the lowered core.
1335 pub term: TermSatCertificate,
1336 /// The extended query, its map and tables onto `term.term`.
1337 pub sliver: SliverBlock,
1338 /// The extended model: the pullback of the core model.
1339 pub model: SliverModel,
1340}
1341
1342/// Why a [`SliverSatCertificate::recheck`] could not confirm the model.
1343#[derive(Debug)]
1344pub enum SliverModelRecheckError {
1345 /// The trusted crate rejected the extended-to-core correspondence.
1346 Sliver(SliverCheckError),
1347 /// The v3 (term-level) re-check failed.
1348 Term(TermModelRecheckError),
1349 /// The advertised extended model is not the pullback of the core
1350 /// model through the tables.
1351 Model,
1352}
1353
1354impl std::fmt::Display for SliverModelRecheckError {
1355 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1356 match self {
1357 SliverModelRecheckError::Sliver(e) => {
1358 write!(f, "trusted sliver re-check rejected: {e:?}")
1359 }
1360 SliverModelRecheckError::Term(e) => write!(f, "{e}"),
1361 SliverModelRecheckError::Model => {
1362 write!(
1363 f,
1364 "the extended model is not the pullback of the core model"
1365 )
1366 }
1367 }
1368 }
1369}
1370
1371impl std::error::Error for SliverModelRecheckError {}
1372
1373impl SliverSatCertificate {
1374 /// `check_sliver_lowering`, the v3 SAT recheck, then that the
1375 /// advertised extended model is the pullback of the core model.
1376 pub fn recheck(&self) -> Result<(), SliverModelRecheckError> {
1377 self.sliver
1378 .check(&self.term.term)
1379 .map_err(SliverModelRecheckError::Sliver)?;
1380 self.term.recheck().map_err(SliverModelRecheckError::Term)?;
1381 let expected = self
1382 .sliver
1383 .pullback_model(&self.term.term, &self.term.query.witness.model)
1384 .ok_or(SliverModelRecheckError::Model)?;
1385 if expected.env != self.model.env
1386 || expected.arrays != self.model.arrays
1387 || expected.calls != self.model.calls
1388 {
1389 return Err(SliverModelRecheckError::Model);
1390 }
1391 // TR-073: the extended model's variables BY NAME through the
1392 // kernel's variable table of the extended query, the extended map
1393 // and the term map (`check_tree_model_ext`,
1394 // `kernel.spec.ext_tree_model_sound`).
1395 let ext = &self.sliver.ext;
1396 let mut var_node = Vec::with_capacity(ext.vars.len());
1397 let mut var_width = Vec::with_capacity(ext.vars.len());
1398 let mut values = Vec::with_capacity(ext.vars.len());
1399 for (name, width, node) in &ext.vars {
1400 var_node.push(*node);
1401 var_width.push(*width as usize);
1402 let mapped = self
1403 .sliver
1404 .map
1405 .get(*node)
1406 .and_then(|&m| (m != NO_IMAGE).then(|| self.term.term.map.get(m)))
1407 .flatten()
1408 .is_some_and(|&m| m != NO_IMAGE);
1409 match self.model.env.get(name) {
1410 Some(v) => values.push(*v),
1411 None if !mapped => values.push(0),
1412 None => return Err(SliverModelRecheckError::Model),
1413 }
1414 }
1415 if !ordeal_lrat::check_tree_model_ext(
1416 &var_node,
1417 &var_width,
1418 &self.sliver.map,
1419 &self.term.term.nodes,
1420 &self.term.term.map,
1421 &self.term.query.query.nodes,
1422 &self.term.query.inputs.bits,
1423 &values,
1424 ) {
1425 return Err(SliverModelRecheckError::Model);
1426 }
1427 Ok(())
1428 }
1429}