1#![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
74pub const S: u64 = 1_000_000;
76pub const TRACE_LEN: usize = 64;
78pub const NUM_RC: usize = 16;
80
81const C_X: [usize; 6] = [0, 1, 2, 3, 4, 5]; const C_BS: usize = 6; const C_RRAW: usize = 7; const C_PM: usize = 8; const C_CO: usize = 9; const C_TGATE: usize = 10; const C_BGATE: usize = 11; const C_ALLOW: usize = 12; const C_POW: usize = 13; const RC_BASE: usize = 14; pub const NUM_LANES: usize = 10;
98pub const COMMIT_LIMBS: usize = 4;
100pub const HEX_LIMBS: usize = 4;
104pub const HEX_COMMITMENT_DIGITS: usize = 64;
106const HASH_BASE: usize = RC_BASE + 2 * NUM_RC; pub const WIDTH: usize = HASH_BASE + NUM_LANES; const CAP_IV: u64 = 0x5043_4162_6967_3031; const 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#[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
147const INVERTED: [bool; 6] = [false, true, false, false, true, false];
149
150#[derive(Clone, Debug, Serialize, Deserialize)]
155pub struct PolicyParams {
156 pub weights: [u64; 6],
158 pub s: u64,
160 pub theta1_scaled: u64,
162 pub kappa: u64,
164 pub bmax_scaled: u64,
166 pub policy_commitment: String,
170 pub action_commitment: String,
173 pub witness_commitment: [String; COMMIT_LIMBS],
177}
178
179impl PolicyParams {
180 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, kappa: 1,
190 bmax_scaled: 1_000_000, 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 fn t1_rraw(&self) -> u128 {
199 self.theta1_scaled as u128 * self.s as u128
200 }
201
202 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 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 pub fn to_public(&self) -> PublicInputs {
235 self.try_to_public().expect("malformed policy/action commitment (need 64 hex digits)")
236 }
237}
238
239pub fn hex256_limbs(h: &str) -> Result<[u64; HEX_LIMBS], String> {
241 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#[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 pub policy_commitment: [BaseElement; HEX_LIMBS],
262 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#[derive(Clone, Debug, Serialize, Deserialize)]
284pub struct Witness {
285 pub inputs: [u64; 6],
287 pub budget_scaled: u64,
289 pub predicate_match: bool,
291 pub caveats_ok: bool,
293}
294
295impl Witness {
296 pub fn compliant() -> Self {
298 Witness {
299 inputs: [100_000, 900_000, 50_000, 0, 950_000, 100_000],
301 budget_scaled: 1_000_000, predicate_match: true,
303 caveats_ok: true,
304 }
305 }
306
307 pub fn non_compliant_risk() -> Self {
309 Witness {
310 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 pub fn non_compliant_predicate() -> Self {
320 let mut w = Witness::compliant();
321 w.predicate_match = false;
322 w
323 }
324}
325
326pub 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
340fn 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
371fn 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
386pub 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
394pub 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 fn rc_target<E: FieldElement<BaseField = BaseElement>>(&self, k: usize, cur: &[E]) -> E {
410 let s = E::from(self.s);
411 match k {
412 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 12 => cur[C_BS],
427 13 => E::from(self.bmax_scaled) - cur[C_BS],
428 14 => E::from(self.t1_rraw) - cur[C_RRAW],
430 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 for _ in 0..13 {
447 degrees.push(TransitionConstraintDegree::new(1));
448 }
449 degrees.push(TransitionConstraintDegree::new(1));
451 degrees.push(TransitionConstraintDegree::new(1));
453 for _ in 0..4 {
455 degrees.push(TransitionConstraintDegree::new(2));
456 }
457 degrees.push(TransitionConstraintDegree::new(4));
459 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 for _ in 0..NUM_LANES {
467 degrees.push(TransitionConstraintDegree::new(3));
468 }
469 for _ in 0..NUM_LANES {
471 degrees.push(TransitionConstraintDegree::with_cycles(1, vec![TRACE_LEN]));
472 }
473
474 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 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 for c in 0..13 {
510 result[i] = next[c] - cur[c];
511 i += 1;
512 }
513 result[i] = next[C_POW] - (cur[C_POW] + cur[C_POW]);
515 i += 1;
516 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 for &c in &[C_PM, C_CO, C_TGATE, C_BGATE] {
528 result[i] = cur[c] * (cur[c] - one);
529 i += 1;
530 }
531 result[i] = cur[C_ALLOW] - cur[C_PM] * cur[C_CO] * cur[C_TGATE] * cur[C_BGATE];
533 i += 1;
534 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 result[i] = bit * (bit - one);
542 i += 1;
543 result[i] = acc_next - (acc - bit * pow);
545 i += 1;
546 result[i] = s0 * (acc - self.rc_target(k, cur));
548 i += 1;
549 }
550
551 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 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)); a.push(Assertion::single(C_ALLOW, 0, BaseElement::ONE)); for k in 0..NUM_RC {
585 a.push(Assertion::single(rc_acc(k), last, BaseElement::ZERO));
588 }
589 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
602fn 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
627pub 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; 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 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 for row in 0..TRACE_LEN {
652 cols[C_POW][row] = BaseElement::new(1u128 << row);
653 }
654 for k in 0..NUM_RC {
656 let target = rc_target_base(k, &x, bs, rraw, &p);
657 let v = target.as_int(); 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 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 }
673
674 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
685pub 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
702pub 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
773pub fn prove_release(witness: &Witness, policy: &PolicyParams) -> Result<Proof, ProverError> {
777 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
786struct 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
853const DIGEST_BYTES: usize = 32;
855
856fn 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 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
883fn 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
907pub 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
933pub fn verify_release_bytes(
935 bytes: &[u8],
936 policy: &PolicyParams,
937) -> Result<(), winterfell::VerifierError> {
938 verify_release(proof_from_bytes(bytes)?, policy)
939}
940
941pub fn verify_release(
944 proof: Proof,
945 policy: &PolicyParams,
946) -> Result<(), winterfell::VerifierError> {
947 check_nested_openings(&proof)
949 .map_err(|e| winterfell::VerifierError::ProofDeserializationError(format!("{e}")))?;
950 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 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 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 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 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 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}