Skip to main content

stark_pca/
lib.rs

1//! # stark-pca — a transparent STARK of the PCA release gate
2//!
3//! A genuine, verifiable zk-STARK (Winterfell, hash-based, **no trusted setup**,
4//! **post-quantum**) proving the *core release gate* of Proof-Carrying Authority.
5//!
6//! ## What the AIR proves
7//!
8//! Given PUBLIC inputs — the risk weights `(α,β,γ,δ,ε,ζ)`, the tier-1 threshold `θ₁`,
9//! the cost scale `κ`, the budget ceiling `bMax`, the fixed-point scale `S = 1e6`, and
10//! two opaque commitments `(policy_commitment, action_commitment)` — and PRIVATE
11//! witnesses — the six risk-magnitude inputs `(d, rev, bl, taint, conf, age)`, the trust
12//! budget `B`, a predicate-match bit `pm`, and a caveats-satisfied bit `co` — the prover
13//! demonstrates knowledge of a witness such that
14//!
15//! ```text
16//!   r_raw = α·d + β·(1−rev) + γ·bl + δ·taint + ε·(1−conf) + ζ·age           (fixed-point, scale S²)
17//!   allow = (tier==1) ∧ (B ≥ κ·r) ∧ pm ∧ co   and   allow == 1
18//! ```
19//!
20//! where `r = r_raw / S²` is computed by the **same fixed-point risk functional as
21//! the `@atlasauth/pca` reference risk model** (weights clamped `≥0`, inputs in `[0,1]` at scale `S`,
22//! reversibility and confidence entering as `1−x`), `tier==1 ⟺ r ≤ θ₁`
23//! (`requiredThreshold`'s t=1 band), and `B ≥ κ·r` is the budget-admission cost gate
24//! (`admit` / `cost`).
25//!
26//! `allow` is **derived** in-trace as the product of the four conjuncts and **asserted
27//! `== 1`**: a deny witness (`r > θ₁`, `B < κ·r`, `pm == 0`, or `co == 0`) makes the
28//! system unsatisfiable, so you cannot forge an `allow` proof. The two inequalities are
29//! enforced by in-AIR **bit-decomposition range gadgets** (`θ₁·S² − r_raw ≥ 0` and
30//! `B·S − κ·r_raw ≥ 0`), which are real algebraic STARK constraints — not a trusted bit.
31//!
32//! ## Witness ↔ commitment binding (the in-AIR hash)
33//!
34//! The private witness is now **bound in-AIR** to a public commitment. A genuine in-AIR
35//! algebraic hash (`NUM_LANES=10`-wide cube-S-box SPN: `a_k = (Hₖ + 2^row + RCₖ)³`,
36//! diffusion `H'ⱼ = Σₖ aₖ + aⱼ`, one round per trace row) absorbs the **nine quantized
37//! witness quantities** `(d, rev, bl, taint, conf, age, B, pm, co)` on row 0 (lanes 0..8) +
38//! a capacity IV (lane 9), runs `TRACE_LEN−1` rounds, and the first `COMMIT_LIMBS=4` state
39//! lanes at the final row are **asserted equal to a public input** `witness_commitment`
40//! (the resource server's algebraic commitment to the quantized action). The same
41//! witness columns drive both the risk gate and the hash, so a proof exists only for a
42//! witness whose quantized form hashes to the committed value — you cannot prove the gate
43//! for a witness that does not match the committed action. See `compute_witness_commitment`.
44//!
45//! See `README.md` for the precise honest gaps versus the Groth16 Policy-VM circuit
46//! (the `@atlasauth/pca` Groth16 circuit). The binding above is over the **quantized preimage** via the
47//! AIR's native algebraic hash — it is **not** a recomputation of the SHA-256-of-canonical-
48//! JSON `action_commitment` in-AIR (still infeasible in this field); the two are linked
49//! off-circuit by the resource server deriving both from one action. Remaining gaps:
50//! predicates/caveats are reduced to booleans, the threshold ladder beyond t=1 and the
51//! attenuation chain are not encoded.
52
53// Trace-construction code mirrors the AIR column-by-column; index loops are the clearer form.
54#![allow(
55    clippy::needless_range_loop,
56    clippy::manual_memcpy,
57    clippy::manual_range_patterns,
58    clippy::unnecessary_cast
59)]
60
61use serde::{Deserialize, Serialize};
62use winter_utils::{ByteReader, Deserializable, DeserializationError, Serializable};
63use winterfell::{
64    crypto::{hashers::Blake3_256, DefaultRandomCoin, MerkleTree},
65    math::{fields::f128::BaseElement, FieldElement, StarkField, ToElements},
66    matrix::ColMatrix,
67    Air, AirContext, Assertion, AuxRandElements, BatchingMethod, CompositionPoly,
68    CompositionPolyTrace, ConstraintCompositionCoefficients, DefaultConstraintCommitment,
69    DefaultConstraintEvaluator, DefaultTraceLde, EvaluationFrame, FieldExtension, PartitionOptions,
70    Proof, ProofOptions, Prover, ProverError, StarkDomain, TraceInfo, TracePolyTable, TraceTable,
71    TransitionConstraintDegree,
72};
73
74/// Fixed-point scale (parts-per-million). Matches the reference risk model and Groth16 circuit (`S = 1e6`).
75pub const S: u64 = 1_000_000;
76/// Execution-trace length (power of two; ≥ 63 so the range gadgets cover bits 0..=62).
77pub const TRACE_LEN: usize = 64;
78/// Number of in-AIR range checks (bit-decomposition gadgets).
79pub const NUM_RC: usize = 16;
80
81// ---- trace column layout --------------------------------------------------------------
82
83const C_X: [usize; 6] = [0, 1, 2, 3, 4, 5]; // d, rev, bl, taint, conf, age (scaled 0..=S)
84const C_BS: usize = 6; // budget, scaled by S
85const C_RRAW: usize = 7; // Σ wᵢ·termᵢ  (scale S²)
86const C_PM: usize = 8; // predicate-match bit
87const C_CO: usize = 9; // caveats-ok bit
88const C_TGATE: usize = 10; // tier==1 bit
89const C_BGATE: usize = 11; // B≥κ·r bit
90const C_ALLOW: usize = 12; // allow == pm·co·tgate·bgate
91const C_POW: usize = 13; // 2^step
92const RC_BASE: usize = 14; // range-check columns start here (2 per check: bit, acc)
93
94// ---- in-AIR algebraic-hash (witness ↔ commitment binding) layout ---------------------
95
96/// Hash-state lanes: lanes 0..8 absorb the 9 quantized witness quantities, lane 9 = capacity.
97pub const NUM_LANES: usize = 10;
98/// Number of squeezed output limbs forming the public `witness_commitment`.
99pub const COMMIT_LIMBS: usize = 4;
100/// Number of 64-bit limbs each opaque 256-bit hex commitment is split into (big-endian: limb 0
101/// = hex digits 0..16 ... limb 3 = hex digits 48..64). 64-bit limbs are always `< p` in `f128`,
102/// so the split is injective: all 256 bits are bound, with no modular reduction.
103pub const HEX_LIMBS: usize = 4;
104/// Required length of an opaque commitment: 64 hex digits (a SHA-256 digest).
105pub const HEX_COMMITMENT_DIGITS: usize = 64;
106/// Hash-state columns start here (one column per lane).
107const HASH_BASE: usize = RC_BASE + 2 * NUM_RC; // 46
108/// Total trace width.
109pub const WIDTH: usize = HASH_BASE + NUM_LANES; // 56
110
111/// Capacity-lane IV and per-lane round constants (nothing-up-my-sleeve; all fit in u64, so
112/// they are byte-identical to the Plonky3/Goldilocks crate's constants).
113const CAP_IV: u64 = 0x5043_4162_6967_3031; // "PCAbig01"
114const RC_SEED: u64 = 0x00A1_B2C3_D4E5_F607;
115const RC_STRIDE: u64 = 0x0000_1000_0000_01B3;
116
117#[inline]
118const fn rc_k(k: usize) -> u64 {
119    RC_SEED.wrapping_add((k as u64).wrapping_mul(RC_STRIDE))
120}
121#[inline]
122const fn h_lane(j: usize) -> usize {
123    HASH_BASE + j
124}
125/// The trace column holding the preimage element absorbed into hash lane `j` (j < 9):
126/// lanes 0..5 → the six risk inputs, lane 6 → budget, lane 7 → pm, lane 8 → co.
127#[inline]
128const fn preimage_col(j: usize) -> usize {
129    match j {
130        0 | 1 | 2 | 3 | 4 | 5 => C_X[j],
131        6 => C_BS,
132        7 => C_PM,
133        8 => C_CO,
134        _ => usize::MAX,
135    }
136}
137
138#[inline]
139const fn rc_bit(k: usize) -> usize {
140    RC_BASE + 2 * k
141}
142#[inline]
143const fn rc_acc(k: usize) -> usize {
144    RC_BASE + 2 * k + 1
145}
146
147/// `rev` (index 1) and `conf` (index 4) enter the functional as `(1 − x)`.
148const INVERTED: [bool; 6] = [false, true, false, false, true, false];
149
150// ---- public inputs & policy -----------------------------------------------------------
151
152/// Public policy parameters (the verifier's view). All risk quantities are integers at
153/// scale `S`; `kappa` is a non-negative integer cost scale (see README gap note).
154#[derive(Clone, Debug, Serialize, Deserialize)]
155pub struct PolicyParams {
156    /// Risk weights (α,β,γ,δ,ε,ζ) at scale S (e.g. 0.25 → 250000).
157    pub weights: [u64; 6],
158    /// Fixed-point scale (must equal `S`).
159    pub s: u64,
160    /// Tier-1 threshold θ₁ at scale S (e.g. 0.25 → 250000).
161    pub theta1_scaled: u64,
162    /// Cost scale κ (non-negative integer).
163    pub kappa: u64,
164    /// Budget ceiling bMax at scale S (e.g. 1.0 → 1000000).
165    pub bmax_scaled: u64,
166    /// Opaque policy commitment: exactly 64 lowercase hex digits (256 bits; uppercase is refused, R6-ALIAS-06). All 256
167    /// bits are bound into the proof transcript (as `HEX_LIMBS` 64-bit field elements); NOT
168    /// constrained in-AIR.
169    pub policy_commitment: String,
170    /// Opaque action commitment: exactly 64 hex digits (SHA-256 of canonical JSON). All 256
171    /// bits are bound into the proof transcript, NOT recomputed in-AIR (see the crate docs / README on the quantized binding).
172    pub action_commitment: String,
173    /// The resource server's algebraic commitment to the quantized action — the
174    /// `COMMIT_LIMBS` field-element limbs (decimal) of [`compute_witness_commitment`]. These
175    /// ARE constrained in-AIR: the witness's quantized form is proven to hash to them.
176    pub witness_commitment: [String; COMMIT_LIMBS],
177}
178
179impl PolicyParams {
180    /// The default risk policy of the reference model, scaled by S. Its
181    /// `witness_commitment` is the algebraic commitment to the paired [`Witness::compliant`]
182    /// quantized action (the default fixture), as a resource server would compute and publish.
183    pub fn default_policy() -> Self {
184        let wc = compute_witness_commitment(&Witness::compliant());
185        PolicyParams {
186            weights: [250_000, 200_000, 200_000, 200_000, 100_000, 50_000],
187            s: S,
188            theta1_scaled: 250_000, // θ₁ = 0.25
189            kappa: 1,
190            bmax_scaled: 1_000_000, // bMax = 1.0
191            policy_commitment: "a1b2c3d4e5f60718293a4b5c6d7e8f90fedcba98765432100123456789abcdef".into(),
192            action_commitment: "0f1e2d3c4b5a69788796a5b4c3d2e1f0112233445566778899aabbccddeeff00".into(),
193            witness_commitment: core::array::from_fn(|m| wc[m].as_int().to_string()),
194        }
195    }
196
197    /// θ₁·S² : the tier-1 bound in `r_raw` (scale S²) units. `r ≤ θ₁ ⟺ r_raw ≤ θ₁·S²`.
198    fn t1_rraw(&self) -> u128 {
199        self.theta1_scaled as u128 * self.s as u128
200    }
201
202    /// Check that both opaque commitments are exactly 64 hex digits. Anything else (short,
203    /// long, non-hex, `0x`-prefixed) is refused rather than silently truncated.
204    pub fn validate(&self) -> Result<(), String> {
205        hex256_limbs(&self.policy_commitment).map_err(|e| format!("policy_commitment: {e}"))?;
206        hex256_limbs(&self.action_commitment).map_err(|e| format!("action_commitment: {e}"))?;
207        Ok(())
208    }
209
210    /// The public inputs embedded in / checked against the proof, or `Err` if a commitment is
211    /// malformed (see [`PolicyParams::validate`]).
212    pub fn try_to_public(&self) -> Result<PublicInputs, String> {
213        let pc = hex256_limbs(&self.policy_commitment).map_err(|e| format!("policy_commitment: {e}"))?;
214        let ac = hex256_limbs(&self.action_commitment).map_err(|e| format!("action_commitment: {e}"))?;
215        let wc: [BaseElement; COMMIT_LIMBS] =
216            core::array::from_fn(|m| BaseElement::new(self.witness_commitment[m].parse::<u128>().unwrap_or(0)));
217        Ok(PublicInputs {
218            weights: self.weights.map(|w| BaseElement::new(w as u128)),
219            s: BaseElement::new(self.s as u128),
220            t1_rraw: BaseElement::new(self.t1_rraw()),
221            kappa: BaseElement::new(self.kappa as u128),
222            bmax_scaled: BaseElement::new(self.bmax_scaled as u128),
223            policy_commitment: pc.map(|l| BaseElement::new(l as u128)),
224            action_commitment: ac.map(|l| BaseElement::new(l as u128)),
225            witness_commitment: wc,
226        })
227    }
228
229    /// Infallible form of [`PolicyParams::try_to_public`].
230    ///
231    /// # Panics
232    /// If a commitment is not exactly 64 hex digits; call [`PolicyParams::validate`] first on
233    /// untrusted policies. `prove_release` / `verify_release` do so and never panic.
234    pub fn to_public(&self) -> PublicInputs {
235        self.try_to_public().expect("malformed policy/action commitment (need 64 hex digits)")
236    }
237}
238
239/// Parse exactly 64 lowercase hex digits into four big-endian 64-bit limbs (all 256 bits, injective).
240pub fn hex256_limbs(h: &str) -> Result<[u64; HEX_LIMBS], String> {
241    // R6-ALIAS-06: lowercase only, so a commitment has one accepted spelling (is_ascii_hexdigit also admits A-F).
242    if h.len() != HEX_COMMITMENT_DIGITS || !h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
243        return Err(format!("must be exactly {HEX_COMMITMENT_DIGITS} lowercase hex digits"));
244    }
245    let mut out = [0u64; HEX_LIMBS];
246    for (i, o) in out.iter_mut().enumerate() {
247        *o = u64::from_str_radix(&h[16 * i..16 * i + 16], 16).map_err(|e| e.to_string())?;
248    }
249    Ok(out)
250}
251
252/// Public inputs as field elements. Order here defines the Fiat–Shamir transcript binding.
253#[derive(Clone, Debug)]
254pub struct PublicInputs {
255    pub weights: [BaseElement; 6],
256    pub s: BaseElement,
257    pub t1_rraw: BaseElement,
258    pub kappa: BaseElement,
259    pub bmax_scaled: BaseElement,
260    /// 256-bit policy commitment as four 64-bit limbs (big-endian).
261    pub policy_commitment: [BaseElement; HEX_LIMBS],
262    /// 256-bit action commitment as four 64-bit limbs (big-endian).
263    pub action_commitment: [BaseElement; HEX_LIMBS],
264    pub witness_commitment: [BaseElement; COMMIT_LIMBS],
265}
266
267impl ToElements<BaseElement> for PublicInputs {
268    fn to_elements(&self) -> Vec<BaseElement> {
269        let mut v = Vec::with_capacity(10 + 2 * HEX_LIMBS + COMMIT_LIMBS);
270        v.extend_from_slice(&self.weights);
271        v.push(self.s);
272        v.push(self.t1_rraw);
273        v.push(self.kappa);
274        v.push(self.bmax_scaled);
275        v.extend_from_slice(&self.policy_commitment);
276        v.extend_from_slice(&self.action_commitment);
277        v.extend_from_slice(&self.witness_commitment);
278        v
279    }
280}
281
282/// Private witness.
283#[derive(Clone, Debug, Serialize, Deserialize)]
284pub struct Witness {
285    /// (d, rev, bl, taint, conf, age) at scale S, each in `[0, S]`.
286    pub inputs: [u64; 6],
287    /// Trust budget B at scale S.
288    pub budget_scaled: u64,
289    /// predicate-match bit.
290    pub predicate_match: bool,
291    /// caveats-satisfied bit.
292    pub caveats_ok: bool,
293}
294
295impl Witness {
296    /// A compliant, low-risk witness that satisfies the gate under the default policy.
297    pub fn compliant() -> Self {
298        Witness {
299            // d=0.10 rev=0.90 bl=0.05 taint=0.00 conf=0.95 age=0.10  → r = 0.065 ≤ θ₁=0.25
300            inputs: [100_000, 900_000, 50_000, 0, 950_000, 100_000],
301            budget_scaled: 1_000_000, // B = 1.0 ≥ κ·r = 0.065
302            predicate_match: true,
303            caveats_ok: true,
304        }
305    }
306
307    /// Non-compliant: high risk AND no budget (r > θ₁ and B < κ·r).
308    pub fn non_compliant_risk() -> Self {
309        Witness {
310            // all risk-maximal → r = 0.90 > θ₁
311            inputs: [900_000, 100_000, 900_000, 900_000, 100_000, 900_000],
312            budget_scaled: 0,
313            predicate_match: true,
314            caveats_ok: true,
315        }
316    }
317
318    /// Non-compliant: compliant risk/budget but predicate does not match (pm = 0).
319    pub fn non_compliant_predicate() -> Self {
320        let mut w = Witness::compliant();
321        w.predicate_match = false;
322        w
323    }
324}
325
326// ---- fixed-point risk functional (scale S²), shared by trace-gen and tests -----------
327
328/// `r_raw = Σ wᵢ·termᵢ` where `termᵢ = xᵢ` or `(S − xᵢ)` for inverted inputs. Scale S².
329/// This is the integer image of `riskScore` in the reference model; dividing by S² recovers `r∈[0,1]`.
330pub fn risk_raw(inputs: &[u64; 6], weights: &[u64; 6]) -> u128 {
331    let mut acc: u128 = 0;
332    for i in 0..6 {
333        let x = inputs[i] as u128;
334        let term = if INVERTED[i] { S as u128 - x } else { x };
335        acc += weights[i] as u128 * term;
336    }
337    acc
338}
339
340// ---- in-AIR algebraic hash (witness ↔ commitment binding) ----------------------------
341
342/// Run the full hash-state trace. Row 0 is the initial state (lanes 0..8 = the 9 quantized
343/// preimage elements, lane 9 = capacity IV); each subsequent row applies one SPN round with
344/// a cube S-box (`a_k = (H_k + 2^row + RC_k)³`) and an invertible `(I+J)` diffusion layer
345/// (`H'_j = Σ_k a_k + a_j`). This is exactly the recurrence enforced in-AIR by
346/// [`ReleaseAir::evaluate_transition`], so prover trace and verifier constraints agree.
347fn hash_state_trace(preimage: &[BaseElement; 9]) -> [[BaseElement; NUM_LANES]; TRACE_LEN] {
348    let mut st = [[BaseElement::ZERO; NUM_LANES]; TRACE_LEN];
349    for j in 0..9 {
350        st[0][j] = preimage[j];
351    }
352    st[0][9] = BaseElement::new(CAP_IV as u128);
353    let rc: [BaseElement; NUM_LANES] = core::array::from_fn(|k| BaseElement::new(rc_k(k) as u128));
354    for r in 0..TRACE_LEN - 1 {
355        let pow = BaseElement::new(1u128 << r);
356        let mut a = [BaseElement::ZERO; NUM_LANES];
357        let mut sum = BaseElement::ZERO;
358        for k in 0..NUM_LANES {
359            let t = st[r][k] + pow + rc[k];
360            let c = t * t * t;
361            a[k] = c;
362            sum += c;
363        }
364        for j in 0..NUM_LANES {
365            st[r + 1][j] = sum + a[j];
366        }
367    }
368    st
369}
370
371/// The nine quantized witness quantities, in absorption order (= lanes 0..8).
372fn witness_preimage(w: &Witness) -> [BaseElement; 9] {
373    [
374        BaseElement::new(w.inputs[0] as u128),
375        BaseElement::new(w.inputs[1] as u128),
376        BaseElement::new(w.inputs[2] as u128),
377        BaseElement::new(w.inputs[3] as u128),
378        BaseElement::new(w.inputs[4] as u128),
379        BaseElement::new(w.inputs[5] as u128),
380        BaseElement::new(w.budget_scaled as u128),
381        if w.predicate_match { BaseElement::ONE } else { BaseElement::ZERO },
382        if w.caveats_ok { BaseElement::ONE } else { BaseElement::ZERO },
383    ]
384}
385
386/// The algebraic commitment to the quantized witness preimage: the first `COMMIT_LIMBS`
387/// hash-state lanes at the final trace row. The resource server computes the *same* value
388/// over the quantized action and publishes it as `PolicyParams::witness_commitment`.
389pub fn compute_witness_commitment(w: &Witness) -> [BaseElement; COMMIT_LIMBS] {
390    let st = hash_state_trace(&witness_preimage(w));
391    core::array::from_fn(|m| st[TRACE_LEN - 1][m])
392}
393
394// ---- the AIR --------------------------------------------------------------------------
395
396pub struct ReleaseAir {
397    context: AirContext<BaseElement>,
398    weights: [BaseElement; 6],
399    s: BaseElement,
400    t1_rraw: BaseElement,
401    kappa: BaseElement,
402    bmax_scaled: BaseElement,
403    witness_commitment: [BaseElement; COMMIT_LIMBS],
404}
405
406impl ReleaseAir {
407    /// Target value decomposed by range-check `k` (the quantity asserted `≥ 0`), as a
408    /// field expression over the *current* trace row. Must match [`rc_target_base`].
409    fn rc_target<E: FieldElement<BaseField = BaseElement>>(&self, k: usize, cur: &[E]) -> E {
410        let s = E::from(self.s);
411        match k {
412            // input lower/upper bounds: xᵢ ≥ 0 and S − xᵢ ≥ 0  ⟹  xᵢ ∈ [0, S]
413            0 => cur[C_X[0]],
414            1 => s - cur[C_X[0]],
415            2 => cur[C_X[1]],
416            3 => s - cur[C_X[1]],
417            4 => cur[C_X[2]],
418            5 => s - cur[C_X[2]],
419            6 => cur[C_X[3]],
420            7 => s - cur[C_X[3]],
421            8 => cur[C_X[4]],
422            9 => s - cur[C_X[4]],
423            10 => cur[C_X[5]],
424            11 => s - cur[C_X[5]],
425            // budget bounds: B_S ≥ 0 and bMax·S − B_S ≥ 0  ⟹  B_S ∈ [0, bMax·S]
426            12 => cur[C_BS],
427            13 => E::from(self.bmax_scaled) - cur[C_BS],
428            // tier==1 gate: θ₁·S² − r_raw ≥ 0  ⟺  r ≤ θ₁
429            14 => E::from(self.t1_rraw) - cur[C_RRAW],
430            // budget gate: B_S·S − κ·r_raw ≥ 0  ⟺  B ≥ κ·r
431            15 => s * cur[C_BS] - E::from(self.kappa) * cur[C_RRAW],
432            _ => unreachable!(),
433        }
434    }
435}
436
437impl Air for ReleaseAir {
438    type BaseField = BaseElement;
439    type PublicInputs = PublicInputs;
440
441    fn new(trace_info: TraceInfo, pub_inputs: PublicInputs, options: ProofOptions) -> Self {
442        assert_eq!(WIDTH, trace_info.width());
443
444        let mut degrees = Vec::new();
445        // (A) constant propagation for columns 0..=12
446        for _ in 0..13 {
447            degrees.push(TransitionConstraintDegree::new(1));
448        }
449        // (B) pow recurrence
450        degrees.push(TransitionConstraintDegree::new(1));
451        // (C) r_raw definition
452        degrees.push(TransitionConstraintDegree::new(1));
453        // (D) four boolean gates (pm, co, tgate, bgate)
454        for _ in 0..4 {
455            degrees.push(TransitionConstraintDegree::new(2));
456        }
457        // (E) allow = pm·co·tgate·bgate
458        degrees.push(TransitionConstraintDegree::new(4));
459        // (F) per range check: boolean(2), residual recurrence(2), init pin(1 × periodic cycle)
460        for _ in 0..NUM_RC {
461            degrees.push(TransitionConstraintDegree::new(2));
462            degrees.push(TransitionConstraintDegree::new(2));
463            degrees.push(TransitionConstraintDegree::with_cycles(1, vec![TRACE_LEN]));
464        }
465        // (G) hash SPN round recurrence (cube S-box → degree 3), one per lane
466        for _ in 0..NUM_LANES {
467            degrees.push(TransitionConstraintDegree::new(3));
468        }
469        // (H) hash init pins (first row only): degree-1 gated by the step-0 periodic selector
470        for _ in 0..NUM_LANES {
471            degrees.push(TransitionConstraintDegree::with_cycles(1, vec![TRACE_LEN]));
472        }
473
474        // assertions: pow[0]=1, allow[0]=1, acc_k[last]=0 per range check, and the
475        // COMMIT_LIMBS squeezed hash lanes at the last row == public witness_commitment.
476        let num_assertions = 2 + NUM_RC + COMMIT_LIMBS;
477
478        ReleaseAir {
479            context: AirContext::new(trace_info, degrees, num_assertions, options),
480            weights: pub_inputs.weights,
481            s: pub_inputs.s,
482            t1_rraw: pub_inputs.t1_rraw,
483            kappa: pub_inputs.kappa,
484            bmax_scaled: pub_inputs.bmax_scaled,
485            witness_commitment: pub_inputs.witness_commitment,
486        }
487    }
488
489    fn get_periodic_column_values(&self) -> Vec<Vec<BaseElement>> {
490        // s0: a selector that is 1 only at step 0 (period = trace length).
491        let mut s0 = vec![BaseElement::ZERO; TRACE_LEN];
492        s0[0] = BaseElement::ONE;
493        vec![s0]
494    }
495
496    fn evaluate_transition<E: FieldElement<BaseField = BaseElement>>(
497        &self,
498        frame: &EvaluationFrame<E>,
499        periodic: &[E],
500        result: &mut [E],
501    ) {
502        let cur = frame.current();
503        let next = frame.next();
504        let one = E::ONE;
505        let s0 = periodic[0];
506        let mut i = 0usize;
507
508        // (A) constant propagation for columns 0..=12
509        for c in 0..13 {
510            result[i] = next[c] - cur[c];
511            i += 1;
512        }
513        // (B) pow' = 2·pow
514        result[i] = next[C_POW] - (cur[C_POW] + cur[C_POW]);
515        i += 1;
516        // (C) r_raw = Σ wᵢ·termᵢ  (rev, conf inverted as S − x)
517        let s = E::from(self.s);
518        let mut rraw = E::ZERO;
519        for j in 0..6 {
520            let w = E::from(self.weights[j]);
521            let term = if INVERTED[j] { s - cur[C_X[j]] } else { cur[C_X[j]] };
522            rraw += w * term;
523        }
524        result[i] = cur[C_RRAW] - rraw;
525        i += 1;
526        // (D) boolean gates
527        for &c in &[C_PM, C_CO, C_TGATE, C_BGATE] {
528            result[i] = cur[c] * (cur[c] - one);
529            i += 1;
530        }
531        // (E) allow = pm·co·tgate·bgate
532        result[i] = cur[C_ALLOW] - cur[C_PM] * cur[C_CO] * cur[C_TGATE] * cur[C_BGATE];
533        i += 1;
534        // (F) range checks
535        for k in 0..NUM_RC {
536            let bit = cur[rc_bit(k)];
537            let acc = cur[rc_acc(k)];
538            let acc_next = next[rc_acc(k)];
539            let pow = cur[C_POW];
540            // boolean bit
541            result[i] = bit * (bit - one);
542            i += 1;
543            // residual recurrence: acc' = acc − bit·pow   (so acc counts DOWN to 0)
544            result[i] = acc_next - (acc - bit * pow);
545            i += 1;
546            // init pin (only at step 0): acc[0] == target_k
547            result[i] = s0 * (acc - self.rc_target(k, cur));
548            i += 1;
549        }
550
551        // (G) algebraic-hash SPN round: a_k = (H_k + pow + RC_k)³ ; H'_j = Σ_k a_k + a_j.
552        // The per-row constant is `pow` (= 2^row, column C_POW), so every round differs; the
553        // per-lane RC_k break lane symmetry. This recurrence binds the preimage (row 0) to
554        // the squeezed commitment (last row), asserted equal to the public input below.
555        let pow = cur[C_POW];
556        let mut a = [E::ZERO; NUM_LANES];
557        let mut sum = E::ZERO;
558        for k in 0..NUM_LANES {
559            let t = cur[h_lane(k)] + pow + E::from(BaseElement::new(rc_k(k) as u128));
560            let c = t * t * t;
561            a[k] = c;
562            sum += c;
563        }
564        for j in 0..NUM_LANES {
565            result[i] = next[h_lane(j)] - (sum + a[j]);
566            i += 1;
567        }
568        // (H) hash init pins (step 0 only): lanes 0..8 == the quantized preimage columns,
569        // lane 9 == the capacity IV.
570        for j in 0..9 {
571            result[i] = s0 * (cur[h_lane(j)] - cur[preimage_col(j)]);
572            i += 1;
573        }
574        result[i] = s0 * (cur[h_lane(9)] - E::from(BaseElement::new(CAP_IV as u128)));
575        i += 1;
576        debug_assert_eq!(i, result.len());
577    }
578
579    fn get_assertions(&self) -> Vec<Assertion<BaseElement>> {
580        let last = TRACE_LEN - 1;
581        let mut a = Vec::with_capacity(2 + NUM_RC + COMMIT_LIMBS);
582        a.push(Assertion::single(C_POW, 0, BaseElement::ONE)); // pow[0] = 2^0 = 1
583        a.push(Assertion::single(C_ALLOW, 0, BaseElement::ONE)); // allow = 1 (the gate)
584        for k in 0..NUM_RC {
585            // residual decompositions all reach exactly 0 → each target is a valid
586            // non-negative <2^63 bit sum (a deny witness cannot satisfy this).
587            a.push(Assertion::single(rc_acc(k), last, BaseElement::ZERO));
588        }
589        // squeeze: the first COMMIT_LIMBS hash lanes at the last row must equal the public
590        // witness_commitment — this is the in-AIR witness ↔ action binding.
591        for m in 0..COMMIT_LIMBS {
592            a.push(Assertion::single(h_lane(m), last, self.witness_commitment[m]));
593        }
594        a
595    }
596
597    fn context(&self) -> &AirContext<BaseElement> {
598        &self.context
599    }
600}
601
602/// Concrete (non-generic) target value for range-check `k`, used by trace generation.
603/// MUST match [`ReleaseAir::rc_target`].
604fn rc_target_base(k: usize, x: &[BaseElement; 6], bs: BaseElement, rraw: BaseElement, p: &PublicInputs) -> BaseElement {
605    let s = p.s;
606    match k {
607        0 => x[0],
608        1 => s - x[0],
609        2 => x[1],
610        3 => s - x[1],
611        4 => x[2],
612        5 => s - x[2],
613        6 => x[3],
614        7 => s - x[3],
615        8 => x[4],
616        9 => s - x[4],
617        10 => x[5],
618        11 => s - x[5],
619        12 => bs,
620        13 => p.bmax_scaled - bs,
621        14 => p.t1_rraw - rraw,
622        15 => s * bs - p.kappa * rraw,
623        _ => unreachable!(),
624    }
625}
626
627// ---- trace construction ---------------------------------------------------------------
628
629/// Build the execution trace for `(witness, policy)`.
630pub fn build_trace(w: &Witness, policy: &PolicyParams) -> TraceTable<BaseElement> {
631    let p = policy.to_public();
632    let x: [BaseElement; 6] = w.inputs.map(|v| BaseElement::new(v as u128));
633    let bs = BaseElement::new(w.budget_scaled as u128);
634    let rraw = BaseElement::new(risk_raw(&w.inputs, &policy.weights));
635    let pm = if w.predicate_match { BaseElement::ONE } else { BaseElement::ZERO };
636    let co = if w.caveats_ok { BaseElement::ONE } else { BaseElement::ZERO };
637    let tgate = BaseElement::ONE; // asserted gate bit (proven consistent by range checks 14/15)
638    let bgate = BaseElement::ONE;
639    let allow = pm * co * tgate * bgate;
640
641    let mut cols: Vec<Vec<BaseElement>> = vec![vec![BaseElement::ZERO; TRACE_LEN]; WIDTH];
642
643    // constant columns (repeated on every row)
644    let consts = [x[0], x[1], x[2], x[3], x[4], x[5], bs, rraw, pm, co, tgate, bgate, allow];
645    for (c, &val) in consts.iter().enumerate() {
646        for row in 0..TRACE_LEN {
647            cols[c][row] = val;
648        }
649    }
650    // pow column: 2^row
651    for row in 0..TRACE_LEN {
652        cols[C_POW][row] = BaseElement::new(1u128 << row);
653    }
654    // range-check columns
655    for k in 0..NUM_RC {
656        let target = rc_target_base(k, &x, bs, rraw, &p);
657        let v = target.as_int(); // u128 field representation
658        let bcol = rc_bit(k);
659        let acol = rc_acc(k);
660        let mut acc = target;
661        for row in 0..TRACE_LEN {
662            cols[acol][row] = acc;
663            // bits 0..=62 participate in the residual (last transition is 62→63).
664            let bit = if row < TRACE_LEN - 1 { ((v >> row) & 1) as u128 } else { 0 };
665            cols[bcol][row] = BaseElement::new(bit);
666            if row < TRACE_LEN - 1 {
667                acc -= BaseElement::new(bit) * cols[C_POW][row];
668            }
669        }
670        // For a valid (<2^63) target, acc[last] == 0. For an out-of-range / negative
671        // (field-wrapped, ≥2^63) target it is non-zero → the acc[last]=0 assertion fails.
672    }
673
674    // in-AIR algebraic-hash columns: the full SPN state trace over the quantized preimage.
675    let st = hash_state_trace(&witness_preimage(w));
676    for row in 0..TRACE_LEN {
677        for j in 0..NUM_LANES {
678            cols[h_lane(j)][row] = st[row][j];
679        }
680    }
681
682    TraceTable::init(cols)
683}
684
685// ---- prover ---------------------------------------------------------------------------
686
687/// Winterfell proof options: 37 queries, blowup 8, no field extension → 111-bit query security,
688/// 110 bits conjectured (min(min(128, 111) - 1, 128)).
689pub fn proof_options() -> ProofOptions {
690    ProofOptions::new(
691        37,
692        8,
693        0,
694        FieldExtension::None,
695        8,
696        31,
697        BatchingMethod::Linear,
698        BatchingMethod::Linear,
699    )
700}
701
702/// Minimum security level the verifier will accept.
703pub const MIN_SECURITY_BITS: u32 = 100;
704
705struct ReleaseProver {
706    options: ProofOptions,
707    policy: PolicyParams,
708}
709
710impl ReleaseProver {
711    fn new(options: ProofOptions, policy: PolicyParams) -> Self {
712        Self { options, policy }
713    }
714}
715
716impl Prover for ReleaseProver {
717    type BaseField = BaseElement;
718    type Air = ReleaseAir;
719    type Trace = TraceTable<BaseElement>;
720    type HashFn = Blake3_256<BaseElement>;
721    type VC = MerkleTree<Self::HashFn>;
722    type RandomCoin = DefaultRandomCoin<Self::HashFn>;
723    type TraceLde<E: FieldElement<BaseField = Self::BaseField>> =
724        DefaultTraceLde<E, Self::HashFn, Self::VC>;
725    type ConstraintCommitment<E: FieldElement<BaseField = Self::BaseField>> =
726        DefaultConstraintCommitment<E, Self::HashFn, Self::VC>;
727    type ConstraintEvaluator<'a, E: FieldElement<BaseField = Self::BaseField>> =
728        DefaultConstraintEvaluator<'a, Self::Air, E>;
729
730    fn get_pub_inputs(&self, _trace: &Self::Trace) -> PublicInputs {
731        self.policy.to_public()
732    }
733
734    fn options(&self) -> &ProofOptions {
735        &self.options
736    }
737
738    fn new_trace_lde<E: FieldElement<BaseField = Self::BaseField>>(
739        &self,
740        trace_info: &TraceInfo,
741        main_trace: &ColMatrix<Self::BaseField>,
742        domain: &StarkDomain<Self::BaseField>,
743        partition_option: PartitionOptions,
744    ) -> (Self::TraceLde<E>, TracePolyTable<E>) {
745        DefaultTraceLde::new(trace_info, main_trace, domain, partition_option)
746    }
747
748    fn build_constraint_commitment<E: FieldElement<BaseField = Self::BaseField>>(
749        &self,
750        composition_poly_trace: CompositionPolyTrace<E>,
751        num_constraint_composition_columns: usize,
752        domain: &StarkDomain<Self::BaseField>,
753        partition_options: PartitionOptions,
754    ) -> (Self::ConstraintCommitment<E>, CompositionPoly<E>) {
755        DefaultConstraintCommitment::new(
756            composition_poly_trace,
757            num_constraint_composition_columns,
758            domain,
759            partition_options,
760        )
761    }
762
763    fn new_evaluator<'a, E: FieldElement<BaseField = Self::BaseField>>(
764        &self,
765        air: &'a Self::Air,
766        aux_rand_elements: Option<AuxRandElements<E>>,
767        composition_coefficients: ConstraintCompositionCoefficients<E>,
768    ) -> Self::ConstraintEvaluator<'a, E> {
769        DefaultConstraintEvaluator::new(air, aux_rand_elements, composition_coefficients)
770    }
771}
772
773// ---- public prove / verify API --------------------------------------------------------
774
775/// Generate a STARK proof that `witness` satisfies the release gate under `policy`.
776pub fn prove_release(witness: &Witness, policy: &PolicyParams) -> Result<Proof, ProverError> {
777    // Malformed commitments cannot be proven against (ProverError has no better variant).
778    if policy.validate().is_err() {
779        return Err(ProverError::UnsatisfiedTransitionConstraintError(0));
780    }
781    let trace = build_trace(witness, policy);
782    let prover = ReleaseProver::new(proof_options(), policy.clone());
783    prover.prove(trace)
784}
785
786/// A slice reader that refuses attacker-controlled over-allocation.
787///
788/// Winterfell decodes `Vec<T>` by reading a length prefix and then calling
789/// `ByteReader::read_many(len)`, whose default implementation does
790/// `Vec::with_capacity(len)` BEFORE reading any element. A hostile length prefix therefore makes
791/// the process abort with an allocation failure (not a catchable panic). Every serialized element
792/// occupies at least one byte, so `len` can never legitimately exceed the bytes that remain; we
793/// check exactly that, with a comparison that cannot overflow (the stock `SliceReader::check_eor`
794/// computes `pos + num_bytes`, which wraps in release builds for a length near `usize::MAX`).
795struct BoundedReader<'a> {
796    data: &'a [u8],
797    pos: usize,
798}
799
800impl<'a> BoundedReader<'a> {
801    fn new(data: &'a [u8]) -> Self {
802        Self { data, pos: 0 }
803    }
804    fn remaining(&self) -> usize {
805        self.data.len() - self.pos
806    }
807}
808
809impl ByteReader for BoundedReader<'_> {
810    fn read_u8(&mut self) -> Result<u8, DeserializationError> {
811        let b = *self.data.get(self.pos).ok_or(DeserializationError::UnexpectedEOF)?;
812        self.pos += 1;
813        Ok(b)
814    }
815    fn peek_u8(&self) -> Result<u8, DeserializationError> {
816        self.data.get(self.pos).copied().ok_or(DeserializationError::UnexpectedEOF)
817    }
818    fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> {
819        self.check_eor(len)?;
820        let out = &self.data[self.pos..self.pos + len];
821        self.pos += len;
822        Ok(out)
823    }
824    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> {
825        let s = self.read_slice(N)?;
826        let mut out = [0u8; N];
827        out.copy_from_slice(s);
828        Ok(out)
829    }
830    fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> {
831        if num_bytes > self.remaining() {
832            return Err(DeserializationError::UnexpectedEOF);
833        }
834        Ok(())
835    }
836    fn has_more_bytes(&self) -> bool {
837        self.pos < self.data.len()
838    }
839    fn read_many<D>(&mut self, num_elements: usize) -> Result<Vec<D>, DeserializationError>
840    where
841        Self: Sized,
842        D: Deserializable,
843    {
844        self.check_eor(num_elements)?;
845        let mut result = Vec::with_capacity(num_elements);
846        for _ in 0..num_elements {
847            result.push(D::read_from(self)?);
848        }
849        Ok(result)
850    }
851}
852
853/// Serialized size of one Blake3-256 digest inside a batch Merkle opening.
854const DIGEST_BYTES: usize = 32;
855
856/// Pre-validate the layout of an opaque batch Merkle opening (`depth: u8`, then a vint count of node
857/// vectors, each a vint count followed by that many 32-byte digests) so that the verifier's later,
858/// unbounded parse of it cannot be made to allocate more than the bytes actually present.
859///
860/// Why this exists: `Proof` keeps every opening as an opaque byte blob and decodes it only inside
861/// `winterfell::verify`, through `BatchMerkleProof::read_from`, which calls
862/// `Vec::with_capacity(count)` on an attacker-controlled count. A 43 KB proof with one count rewritten
863/// to 2^52 made `verify_release_bytes` abort the process ("memory allocation of ... bytes failed").
864fn check_batch_opening(blob: &[u8]) -> Result<(), DeserializationError> {
865    let mut r = BoundedReader::new(blob);
866    let _depth = r.read_u8()?;
867    let node_vectors = r.read_usize()?;
868    // each node vector needs at least its own one-byte length prefix
869    if node_vectors > r.remaining() {
870        return Err(DeserializationError::InvalidValue("batch opening: node-vector count exceeds the input".into()));
871    }
872    for _ in 0..node_vectors {
873        let digests = r.read_usize()?;
874        let bytes = digests
875            .checked_mul(DIGEST_BYTES)
876            .filter(|b| *b <= r.remaining())
877            .ok_or_else(|| DeserializationError::InvalidValue("batch opening: digest count exceeds the input".into()))?;
878        r.read_slice(bytes)?;
879    }
880    Ok(())
881}
882
883/// Walk every opaque opening in an already-decoded proof (trace and constraint queries, every FRI
884/// layer) and run [`check_batch_opening`] on it. The proof is re-serialized to reach the private
885/// blobs; the re-serialization is of structures that were just decoded, so its lengths are trusted.
886fn check_nested_openings(proof: &Proof) -> Result<(), DeserializationError> {
887    for q in proof.trace_queries.iter().chain(core::iter::once(&proof.constraint_queries)) {
888        let bytes = q.to_bytes();
889        let mut r = BoundedReader::new(&bytes);
890        let values = r.read_usize()?;
891        r.read_slice(values)?;
892        let paths = r.read_usize()?;
893        check_batch_opening(r.read_slice(paths)?)?;
894    }
895    let bytes = proof.fri_proof.to_bytes();
896    let mut r = BoundedReader::new(&bytes);
897    let layers = r.read_u8()?;
898    for _ in 0..layers {
899        let values = r.read_u32()? as usize;
900        r.read_slice(values)?;
901        let paths = r.read_u32()? as usize;
902        check_batch_opening(r.read_slice(paths)?)?;
903    }
904    Ok(())
905}
906
907/// Decode a serialized proof from UNTRUSTED bytes, failing closed.
908///
909/// Plain `winterfell::Proof::from_bytes` is not safe on hostile input: some corrupted headers trip
910/// internal assertions (panic) and a corrupted length prefix can request an enormous allocation
911/// (process abort). This decoder bounds every length prefix by the remaining input, converts any
912/// residual panic into an error, and rejects trailing bytes. Use it (or
913/// [`verify_release_bytes`]) for any proof bytes that arrive from the wire.
914pub fn proof_from_bytes(bytes: &[u8]) -> Result<Proof, winterfell::VerifierError> {
915    let decoded = std::panic::catch_unwind(|| {
916        let mut reader = BoundedReader::new(bytes);
917        let proof = Proof::read_from(&mut reader)?;
918        if reader.has_more_bytes() {
919            return Err(DeserializationError::InvalidValue("trailing bytes after proof".into()));
920        }
921        check_nested_openings(&proof)?;
922        Ok(proof)
923    });
924    match decoded {
925        Ok(Ok(p)) => Ok(p),
926        Ok(Err(e)) => Err(winterfell::VerifierError::ProofDeserializationError(format!("{e}"))),
927        Err(_) => Err(winterfell::VerifierError::ProofDeserializationError(
928            "malformed proof bytes".into(),
929        )),
930    }
931}
932
933/// Decode (fail-closed) and verify a serialized proof in one step.
934pub fn verify_release_bytes(
935    bytes: &[u8],
936    policy: &PolicyParams,
937) -> Result<(), winterfell::VerifierError> {
938    verify_release(proof_from_bytes(bytes)?, policy)
939}
940
941/// Verify a release-gate STARK proof against the public `policy`. `Ok(())` ⟺ the gate
942/// holds (allow == 1) for *some* witness, under exactly these public inputs.
943pub fn verify_release(
944    proof: Proof,
945    policy: &PolicyParams,
946) -> Result<(), winterfell::VerifierError> {
947    // A `Proof` can reach us without going through `proof_from_bytes`: re-validate the opaque openings.
948    check_nested_openings(&proof)
949        .map_err(|e| winterfell::VerifierError::ProofDeserializationError(format!("{e}")))?;
950    // Fail closed on a malformed proof BEFORE handing it to Winterfell: `Air::new` receives the
951    // trace shape straight from the (untrusted) proof and cannot return an error, so a proof
952    // claiming another width or length would otherwise abort the verifier with a panic.
953    let info = proof.trace_info();
954    if info.width() != WIDTH
955        || info.length() != TRACE_LEN
956        || info.aux_segment_width() != 0
957        || info.num_aux_segments() != 0
958        || !info.meta().is_empty()
959    {
960        return Err(winterfell::VerifierError::ProofDeserializationError(
961            "proof trace shape does not match the release-gate AIR".into(),
962        ));
963    }
964    // Pin the exact proof options (query count, blowup, FRI parameters, partitioning, ...). The
965    // security floor below only bounds the strength; without an exact match, option bytes that
966    // do not change the statement (e.g. the row-hash partition rate) would be malleable.
967    if proof.options() != &proof_options() {
968        return Err(winterfell::VerifierError::UnacceptableProofOptions);
969    }
970    let pub_inputs = policy.try_to_public().map_err(winterfell::VerifierError::ProofDeserializationError)?;
971    let min = winterfell::AcceptableOptions::MinConjecturedSecurity(MIN_SECURITY_BITS);
972    // Defence in depth: any residual panic on adversarial bytes is reported as a rejection.
973    std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
974        winterfell::verify::<
975            ReleaseAir,
976            Blake3_256<BaseElement>,
977            DefaultRandomCoin<Blake3_256<BaseElement>>,
978            MerkleTree<Blake3_256<BaseElement>>,
979        >(proof, pub_inputs, &min)
980    }))
981    .unwrap_or_else(|_| {
982        Err(winterfell::VerifierError::ProofDeserializationError(
983            "malformed proof rejected by the verifier".into(),
984        ))
985    })
986}
987
988#[cfg(test)]
989mod opening_layout_tests {
990    use super::{check_batch_opening, DIGEST_BYTES};
991    use winter_utils::{ByteWriter, DeserializationError};
992
993    /// depth byte, node-vector count, then per vector (digest count, that many 32-byte digests; `extra` raw bytes appended).
994    fn blob(count: usize, vectors: &[(usize, usize)]) -> Vec<u8> {
995        let mut b: Vec<u8> = vec![3];
996        b.write_usize(count);
997        for &(claimed, present) in vectors {
998            b.write_usize(claimed);
999            b.extend(std::iter::repeat(0xab).take(present * DIGEST_BYTES));
1000        }
1001        b
1002    }
1003
1004    #[test]
1005    fn well_formed_opening_is_accepted() {
1006        assert!(check_batch_opening(&blob(2, &[(1, 1), (2, 2)])).is_ok());
1007    }
1008
1009    #[test]
1010    fn node_vector_count_equal_to_the_remaining_bytes_is_accepted() {
1011        // three empty node vectors: exactly one length byte each, so count == remaining is the tight bound
1012        assert!(check_batch_opening(&blob(3, &[(0, 0), (0, 0), (0, 0)])).is_ok());
1013    }
1014
1015    #[test]
1016    fn node_vector_count_over_the_input_is_refused_with_its_reason() {
1017        let Err(DeserializationError::InvalidValue(m)) = check_batch_opening(&blob(5, &[(0, 0)])) else {
1018            panic!("expected InvalidValue")
1019        };
1020        assert!(m.contains("node-vector count exceeds the input"), "{m}");
1021    }
1022
1023    #[test]
1024    fn digest_overclaim_late_in_the_blob_is_an_error_not_a_panic() {
1025        // the second vector claims one digest with none left: the bound must use the bytes REMAINING
1026        // (len - pos), not anything larger, or the slice read runs off the end.
1027        let r = std::panic::catch_unwind(|| check_batch_opening(&blob(2, &[(1, 1), (1, 0)])));
1028        let Ok(Err(DeserializationError::InvalidValue(m))) = r else { panic!("expected a clean InvalidValue, got {r:?}") };
1029        assert!(m.contains("digest count exceeds the input"), "{m}");
1030    }
1031}