#![allow(
clippy::needless_range_loop,
clippy::manual_memcpy,
clippy::manual_range_patterns,
clippy::unnecessary_cast
)]
use serde::{Deserialize, Serialize};
use winter_utils::{ByteReader, Deserializable, DeserializationError, Serializable};
use winterfell::{
crypto::{hashers::Blake3_256, DefaultRandomCoin, MerkleTree},
math::{fields::f128::BaseElement, FieldElement, StarkField, ToElements},
matrix::ColMatrix,
Air, AirContext, Assertion, AuxRandElements, BatchingMethod, CompositionPoly,
CompositionPolyTrace, ConstraintCompositionCoefficients, DefaultConstraintCommitment,
DefaultConstraintEvaluator, DefaultTraceLde, EvaluationFrame, FieldExtension, PartitionOptions,
Proof, ProofOptions, Prover, ProverError, StarkDomain, TraceInfo, TracePolyTable, TraceTable,
TransitionConstraintDegree,
};
pub const S: u64 = 1_000_000;
pub const TRACE_LEN: usize = 64;
pub const NUM_RC: usize = 16;
const 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;
pub const COMMIT_LIMBS: usize = 4;
pub const HEX_LIMBS: usize = 4;
pub const HEX_COMMITMENT_DIGITS: usize = 64;
const 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;
const RC_STRIDE: u64 = 0x0000_1000_0000_01B3;
#[inline]
const fn rc_k(k: usize) -> u64 {
RC_SEED.wrapping_add((k as u64).wrapping_mul(RC_STRIDE))
}
#[inline]
const fn h_lane(j: usize) -> usize {
HASH_BASE + j
}
#[inline]
const fn preimage_col(j: usize) -> usize {
match j {
0 | 1 | 2 | 3 | 4 | 5 => C_X[j],
6 => C_BS,
7 => C_PM,
8 => C_CO,
_ => usize::MAX,
}
}
#[inline]
const fn rc_bit(k: usize) -> usize {
RC_BASE + 2 * k
}
#[inline]
const fn rc_acc(k: usize) -> usize {
RC_BASE + 2 * k + 1
}
const INVERTED: [bool; 6] = [false, true, false, false, true, false];
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PolicyParams {
pub weights: [u64; 6],
pub s: u64,
pub theta1_scaled: u64,
pub kappa: u64,
pub bmax_scaled: u64,
pub policy_commitment: String,
pub action_commitment: String,
pub witness_commitment: [String; COMMIT_LIMBS],
}
impl PolicyParams {
pub fn default_policy() -> Self {
let wc = compute_witness_commitment(&Witness::compliant());
PolicyParams {
weights: [250_000, 200_000, 200_000, 200_000, 100_000, 50_000],
s: S,
theta1_scaled: 250_000, kappa: 1,
bmax_scaled: 1_000_000, policy_commitment: "a1b2c3d4e5f60718293a4b5c6d7e8f90fedcba98765432100123456789abcdef".into(),
action_commitment: "0f1e2d3c4b5a69788796a5b4c3d2e1f0112233445566778899aabbccddeeff00".into(),
witness_commitment: core::array::from_fn(|m| wc[m].as_int().to_string()),
}
}
fn t1_rraw(&self) -> u128 {
self.theta1_scaled as u128 * self.s as u128
}
pub fn validate(&self) -> Result<(), String> {
hex256_limbs(&self.policy_commitment).map_err(|e| format!("policy_commitment: {e}"))?;
hex256_limbs(&self.action_commitment).map_err(|e| format!("action_commitment: {e}"))?;
Ok(())
}
pub fn try_to_public(&self) -> Result<PublicInputs, String> {
let pc = hex256_limbs(&self.policy_commitment).map_err(|e| format!("policy_commitment: {e}"))?;
let ac = hex256_limbs(&self.action_commitment).map_err(|e| format!("action_commitment: {e}"))?;
let wc: [BaseElement; COMMIT_LIMBS] =
core::array::from_fn(|m| BaseElement::new(self.witness_commitment[m].parse::<u128>().unwrap_or(0)));
Ok(PublicInputs {
weights: self.weights.map(|w| BaseElement::new(w as u128)),
s: BaseElement::new(self.s as u128),
t1_rraw: BaseElement::new(self.t1_rraw()),
kappa: BaseElement::new(self.kappa as u128),
bmax_scaled: BaseElement::new(self.bmax_scaled as u128),
policy_commitment: pc.map(|l| BaseElement::new(l as u128)),
action_commitment: ac.map(|l| BaseElement::new(l as u128)),
witness_commitment: wc,
})
}
pub fn to_public(&self) -> PublicInputs {
self.try_to_public().expect("malformed policy/action commitment (need 64 hex digits)")
}
}
pub fn hex256_limbs(h: &str) -> Result<[u64; HEX_LIMBS], String> {
if h.len() != HEX_COMMITMENT_DIGITS || !h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
return Err(format!("must be exactly {HEX_COMMITMENT_DIGITS} lowercase hex digits"));
}
let mut out = [0u64; HEX_LIMBS];
for (i, o) in out.iter_mut().enumerate() {
*o = u64::from_str_radix(&h[16 * i..16 * i + 16], 16).map_err(|e| e.to_string())?;
}
Ok(out)
}
#[derive(Clone, Debug)]
pub struct PublicInputs {
pub weights: [BaseElement; 6],
pub s: BaseElement,
pub t1_rraw: BaseElement,
pub kappa: BaseElement,
pub bmax_scaled: BaseElement,
pub policy_commitment: [BaseElement; HEX_LIMBS],
pub action_commitment: [BaseElement; HEX_LIMBS],
pub witness_commitment: [BaseElement; COMMIT_LIMBS],
}
impl ToElements<BaseElement> for PublicInputs {
fn to_elements(&self) -> Vec<BaseElement> {
let mut v = Vec::with_capacity(10 + 2 * HEX_LIMBS + COMMIT_LIMBS);
v.extend_from_slice(&self.weights);
v.push(self.s);
v.push(self.t1_rraw);
v.push(self.kappa);
v.push(self.bmax_scaled);
v.extend_from_slice(&self.policy_commitment);
v.extend_from_slice(&self.action_commitment);
v.extend_from_slice(&self.witness_commitment);
v
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Witness {
pub inputs: [u64; 6],
pub budget_scaled: u64,
pub predicate_match: bool,
pub caveats_ok: bool,
}
impl Witness {
pub fn compliant() -> Self {
Witness {
inputs: [100_000, 900_000, 50_000, 0, 950_000, 100_000],
budget_scaled: 1_000_000, predicate_match: true,
caveats_ok: true,
}
}
pub fn non_compliant_risk() -> Self {
Witness {
inputs: [900_000, 100_000, 900_000, 900_000, 100_000, 900_000],
budget_scaled: 0,
predicate_match: true,
caveats_ok: true,
}
}
pub fn non_compliant_predicate() -> Self {
let mut w = Witness::compliant();
w.predicate_match = false;
w
}
}
pub fn risk_raw(inputs: &[u64; 6], weights: &[u64; 6]) -> u128 {
let mut acc: u128 = 0;
for i in 0..6 {
let x = inputs[i] as u128;
let term = if INVERTED[i] { S as u128 - x } else { x };
acc += weights[i] as u128 * term;
}
acc
}
fn hash_state_trace(preimage: &[BaseElement; 9]) -> [[BaseElement; NUM_LANES]; TRACE_LEN] {
let mut st = [[BaseElement::ZERO; NUM_LANES]; TRACE_LEN];
for j in 0..9 {
st[0][j] = preimage[j];
}
st[0][9] = BaseElement::new(CAP_IV as u128);
let rc: [BaseElement; NUM_LANES] = core::array::from_fn(|k| BaseElement::new(rc_k(k) as u128));
for r in 0..TRACE_LEN - 1 {
let pow = BaseElement::new(1u128 << r);
let mut a = [BaseElement::ZERO; NUM_LANES];
let mut sum = BaseElement::ZERO;
for k in 0..NUM_LANES {
let t = st[r][k] + pow + rc[k];
let c = t * t * t;
a[k] = c;
sum += c;
}
for j in 0..NUM_LANES {
st[r + 1][j] = sum + a[j];
}
}
st
}
fn witness_preimage(w: &Witness) -> [BaseElement; 9] {
[
BaseElement::new(w.inputs[0] as u128),
BaseElement::new(w.inputs[1] as u128),
BaseElement::new(w.inputs[2] as u128),
BaseElement::new(w.inputs[3] as u128),
BaseElement::new(w.inputs[4] as u128),
BaseElement::new(w.inputs[5] as u128),
BaseElement::new(w.budget_scaled as u128),
if w.predicate_match { BaseElement::ONE } else { BaseElement::ZERO },
if w.caveats_ok { BaseElement::ONE } else { BaseElement::ZERO },
]
}
pub fn compute_witness_commitment(w: &Witness) -> [BaseElement; COMMIT_LIMBS] {
let st = hash_state_trace(&witness_preimage(w));
core::array::from_fn(|m| st[TRACE_LEN - 1][m])
}
pub struct ReleaseAir {
context: AirContext<BaseElement>,
weights: [BaseElement; 6],
s: BaseElement,
t1_rraw: BaseElement,
kappa: BaseElement,
bmax_scaled: BaseElement,
witness_commitment: [BaseElement; COMMIT_LIMBS],
}
impl ReleaseAir {
fn rc_target<E: FieldElement<BaseField = BaseElement>>(&self, k: usize, cur: &[E]) -> E {
let s = E::from(self.s);
match k {
0 => cur[C_X[0]],
1 => s - cur[C_X[0]],
2 => cur[C_X[1]],
3 => s - cur[C_X[1]],
4 => cur[C_X[2]],
5 => s - cur[C_X[2]],
6 => cur[C_X[3]],
7 => s - cur[C_X[3]],
8 => cur[C_X[4]],
9 => s - cur[C_X[4]],
10 => cur[C_X[5]],
11 => s - cur[C_X[5]],
12 => cur[C_BS],
13 => E::from(self.bmax_scaled) - cur[C_BS],
14 => E::from(self.t1_rraw) - cur[C_RRAW],
15 => s * cur[C_BS] - E::from(self.kappa) * cur[C_RRAW],
_ => unreachable!(),
}
}
}
impl Air for ReleaseAir {
type BaseField = BaseElement;
type PublicInputs = PublicInputs;
fn new(trace_info: TraceInfo, pub_inputs: PublicInputs, options: ProofOptions) -> Self {
assert_eq!(WIDTH, trace_info.width());
let mut degrees = Vec::new();
for _ in 0..13 {
degrees.push(TransitionConstraintDegree::new(1));
}
degrees.push(TransitionConstraintDegree::new(1));
degrees.push(TransitionConstraintDegree::new(1));
for _ in 0..4 {
degrees.push(TransitionConstraintDegree::new(2));
}
degrees.push(TransitionConstraintDegree::new(4));
for _ in 0..NUM_RC {
degrees.push(TransitionConstraintDegree::new(2));
degrees.push(TransitionConstraintDegree::new(2));
degrees.push(TransitionConstraintDegree::with_cycles(1, vec![TRACE_LEN]));
}
for _ in 0..NUM_LANES {
degrees.push(TransitionConstraintDegree::new(3));
}
for _ in 0..NUM_LANES {
degrees.push(TransitionConstraintDegree::with_cycles(1, vec![TRACE_LEN]));
}
let num_assertions = 2 + NUM_RC + COMMIT_LIMBS;
ReleaseAir {
context: AirContext::new(trace_info, degrees, num_assertions, options),
weights: pub_inputs.weights,
s: pub_inputs.s,
t1_rraw: pub_inputs.t1_rraw,
kappa: pub_inputs.kappa,
bmax_scaled: pub_inputs.bmax_scaled,
witness_commitment: pub_inputs.witness_commitment,
}
}
fn get_periodic_column_values(&self) -> Vec<Vec<BaseElement>> {
let mut s0 = vec![BaseElement::ZERO; TRACE_LEN];
s0[0] = BaseElement::ONE;
vec![s0]
}
fn evaluate_transition<E: FieldElement<BaseField = BaseElement>>(
&self,
frame: &EvaluationFrame<E>,
periodic: &[E],
result: &mut [E],
) {
let cur = frame.current();
let next = frame.next();
let one = E::ONE;
let s0 = periodic[0];
let mut i = 0usize;
for c in 0..13 {
result[i] = next[c] - cur[c];
i += 1;
}
result[i] = next[C_POW] - (cur[C_POW] + cur[C_POW]);
i += 1;
let s = E::from(self.s);
let mut rraw = E::ZERO;
for j in 0..6 {
let w = E::from(self.weights[j]);
let term = if INVERTED[j] { s - cur[C_X[j]] } else { cur[C_X[j]] };
rraw += w * term;
}
result[i] = cur[C_RRAW] - rraw;
i += 1;
for &c in &[C_PM, C_CO, C_TGATE, C_BGATE] {
result[i] = cur[c] * (cur[c] - one);
i += 1;
}
result[i] = cur[C_ALLOW] - cur[C_PM] * cur[C_CO] * cur[C_TGATE] * cur[C_BGATE];
i += 1;
for k in 0..NUM_RC {
let bit = cur[rc_bit(k)];
let acc = cur[rc_acc(k)];
let acc_next = next[rc_acc(k)];
let pow = cur[C_POW];
result[i] = bit * (bit - one);
i += 1;
result[i] = acc_next - (acc - bit * pow);
i += 1;
result[i] = s0 * (acc - self.rc_target(k, cur));
i += 1;
}
let pow = cur[C_POW];
let mut a = [E::ZERO; NUM_LANES];
let mut sum = E::ZERO;
for k in 0..NUM_LANES {
let t = cur[h_lane(k)] + pow + E::from(BaseElement::new(rc_k(k) as u128));
let c = t * t * t;
a[k] = c;
sum += c;
}
for j in 0..NUM_LANES {
result[i] = next[h_lane(j)] - (sum + a[j]);
i += 1;
}
for j in 0..9 {
result[i] = s0 * (cur[h_lane(j)] - cur[preimage_col(j)]);
i += 1;
}
result[i] = s0 * (cur[h_lane(9)] - E::from(BaseElement::new(CAP_IV as u128)));
i += 1;
debug_assert_eq!(i, result.len());
}
fn get_assertions(&self) -> Vec<Assertion<BaseElement>> {
let last = TRACE_LEN - 1;
let mut a = Vec::with_capacity(2 + NUM_RC + COMMIT_LIMBS);
a.push(Assertion::single(C_POW, 0, BaseElement::ONE)); a.push(Assertion::single(C_ALLOW, 0, BaseElement::ONE)); for k in 0..NUM_RC {
a.push(Assertion::single(rc_acc(k), last, BaseElement::ZERO));
}
for m in 0..COMMIT_LIMBS {
a.push(Assertion::single(h_lane(m), last, self.witness_commitment[m]));
}
a
}
fn context(&self) -> &AirContext<BaseElement> {
&self.context
}
}
fn rc_target_base(k: usize, x: &[BaseElement; 6], bs: BaseElement, rraw: BaseElement, p: &PublicInputs) -> BaseElement {
let s = p.s;
match k {
0 => x[0],
1 => s - x[0],
2 => x[1],
3 => s - x[1],
4 => x[2],
5 => s - x[2],
6 => x[3],
7 => s - x[3],
8 => x[4],
9 => s - x[4],
10 => x[5],
11 => s - x[5],
12 => bs,
13 => p.bmax_scaled - bs,
14 => p.t1_rraw - rraw,
15 => s * bs - p.kappa * rraw,
_ => unreachable!(),
}
}
pub fn build_trace(w: &Witness, policy: &PolicyParams) -> TraceTable<BaseElement> {
let p = policy.to_public();
let x: [BaseElement; 6] = w.inputs.map(|v| BaseElement::new(v as u128));
let bs = BaseElement::new(w.budget_scaled as u128);
let rraw = BaseElement::new(risk_raw(&w.inputs, &policy.weights));
let pm = if w.predicate_match { BaseElement::ONE } else { BaseElement::ZERO };
let co = if w.caveats_ok { BaseElement::ONE } else { BaseElement::ZERO };
let tgate = BaseElement::ONE; let bgate = BaseElement::ONE;
let allow = pm * co * tgate * bgate;
let mut cols: Vec<Vec<BaseElement>> = vec![vec![BaseElement::ZERO; TRACE_LEN]; WIDTH];
let consts = [x[0], x[1], x[2], x[3], x[4], x[5], bs, rraw, pm, co, tgate, bgate, allow];
for (c, &val) in consts.iter().enumerate() {
for row in 0..TRACE_LEN {
cols[c][row] = val;
}
}
for row in 0..TRACE_LEN {
cols[C_POW][row] = BaseElement::new(1u128 << row);
}
for k in 0..NUM_RC {
let target = rc_target_base(k, &x, bs, rraw, &p);
let v = target.as_int(); let bcol = rc_bit(k);
let acol = rc_acc(k);
let mut acc = target;
for row in 0..TRACE_LEN {
cols[acol][row] = acc;
let bit = if row < TRACE_LEN - 1 { ((v >> row) & 1) as u128 } else { 0 };
cols[bcol][row] = BaseElement::new(bit);
if row < TRACE_LEN - 1 {
acc -= BaseElement::new(bit) * cols[C_POW][row];
}
}
}
let st = hash_state_trace(&witness_preimage(w));
for row in 0..TRACE_LEN {
for j in 0..NUM_LANES {
cols[h_lane(j)][row] = st[row][j];
}
}
TraceTable::init(cols)
}
pub fn proof_options() -> ProofOptions {
ProofOptions::new(
37,
8,
0,
FieldExtension::None,
8,
31,
BatchingMethod::Linear,
BatchingMethod::Linear,
)
}
pub const MIN_SECURITY_BITS: u32 = 100;
struct ReleaseProver {
options: ProofOptions,
policy: PolicyParams,
}
impl ReleaseProver {
fn new(options: ProofOptions, policy: PolicyParams) -> Self {
Self { options, policy }
}
}
impl Prover for ReleaseProver {
type BaseField = BaseElement;
type Air = ReleaseAir;
type Trace = TraceTable<BaseElement>;
type HashFn = Blake3_256<BaseElement>;
type VC = MerkleTree<Self::HashFn>;
type RandomCoin = DefaultRandomCoin<Self::HashFn>;
type TraceLde<E: FieldElement<BaseField = Self::BaseField>> =
DefaultTraceLde<E, Self::HashFn, Self::VC>;
type ConstraintCommitment<E: FieldElement<BaseField = Self::BaseField>> =
DefaultConstraintCommitment<E, Self::HashFn, Self::VC>;
type ConstraintEvaluator<'a, E: FieldElement<BaseField = Self::BaseField>> =
DefaultConstraintEvaluator<'a, Self::Air, E>;
fn get_pub_inputs(&self, _trace: &Self::Trace) -> PublicInputs {
self.policy.to_public()
}
fn options(&self) -> &ProofOptions {
&self.options
}
fn new_trace_lde<E: FieldElement<BaseField = Self::BaseField>>(
&self,
trace_info: &TraceInfo,
main_trace: &ColMatrix<Self::BaseField>,
domain: &StarkDomain<Self::BaseField>,
partition_option: PartitionOptions,
) -> (Self::TraceLde<E>, TracePolyTable<E>) {
DefaultTraceLde::new(trace_info, main_trace, domain, partition_option)
}
fn build_constraint_commitment<E: FieldElement<BaseField = Self::BaseField>>(
&self,
composition_poly_trace: CompositionPolyTrace<E>,
num_constraint_composition_columns: usize,
domain: &StarkDomain<Self::BaseField>,
partition_options: PartitionOptions,
) -> (Self::ConstraintCommitment<E>, CompositionPoly<E>) {
DefaultConstraintCommitment::new(
composition_poly_trace,
num_constraint_composition_columns,
domain,
partition_options,
)
}
fn new_evaluator<'a, E: FieldElement<BaseField = Self::BaseField>>(
&self,
air: &'a Self::Air,
aux_rand_elements: Option<AuxRandElements<E>>,
composition_coefficients: ConstraintCompositionCoefficients<E>,
) -> Self::ConstraintEvaluator<'a, E> {
DefaultConstraintEvaluator::new(air, aux_rand_elements, composition_coefficients)
}
}
pub fn prove_release(witness: &Witness, policy: &PolicyParams) -> Result<Proof, ProverError> {
if policy.validate().is_err() {
return Err(ProverError::UnsatisfiedTransitionConstraintError(0));
}
let trace = build_trace(witness, policy);
let prover = ReleaseProver::new(proof_options(), policy.clone());
prover.prove(trace)
}
struct BoundedReader<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> BoundedReader<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
fn remaining(&self) -> usize {
self.data.len() - self.pos
}
}
impl ByteReader for BoundedReader<'_> {
fn read_u8(&mut self) -> Result<u8, DeserializationError> {
let b = *self.data.get(self.pos).ok_or(DeserializationError::UnexpectedEOF)?;
self.pos += 1;
Ok(b)
}
fn peek_u8(&self) -> Result<u8, DeserializationError> {
self.data.get(self.pos).copied().ok_or(DeserializationError::UnexpectedEOF)
}
fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> {
self.check_eor(len)?;
let out = &self.data[self.pos..self.pos + len];
self.pos += len;
Ok(out)
}
fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> {
let s = self.read_slice(N)?;
let mut out = [0u8; N];
out.copy_from_slice(s);
Ok(out)
}
fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> {
if num_bytes > self.remaining() {
return Err(DeserializationError::UnexpectedEOF);
}
Ok(())
}
fn has_more_bytes(&self) -> bool {
self.pos < self.data.len()
}
fn read_many<D>(&mut self, num_elements: usize) -> Result<Vec<D>, DeserializationError>
where
Self: Sized,
D: Deserializable,
{
self.check_eor(num_elements)?;
let mut result = Vec::with_capacity(num_elements);
for _ in 0..num_elements {
result.push(D::read_from(self)?);
}
Ok(result)
}
}
const DIGEST_BYTES: usize = 32;
fn check_batch_opening(blob: &[u8]) -> Result<(), DeserializationError> {
let mut r = BoundedReader::new(blob);
let _depth = r.read_u8()?;
let node_vectors = r.read_usize()?;
if node_vectors > r.remaining() {
return Err(DeserializationError::InvalidValue("batch opening: node-vector count exceeds the input".into()));
}
for _ in 0..node_vectors {
let digests = r.read_usize()?;
let bytes = digests
.checked_mul(DIGEST_BYTES)
.filter(|b| *b <= r.remaining())
.ok_or_else(|| DeserializationError::InvalidValue("batch opening: digest count exceeds the input".into()))?;
r.read_slice(bytes)?;
}
Ok(())
}
fn check_nested_openings(proof: &Proof) -> Result<(), DeserializationError> {
for q in proof.trace_queries.iter().chain(core::iter::once(&proof.constraint_queries)) {
let bytes = q.to_bytes();
let mut r = BoundedReader::new(&bytes);
let values = r.read_usize()?;
r.read_slice(values)?;
let paths = r.read_usize()?;
check_batch_opening(r.read_slice(paths)?)?;
}
let bytes = proof.fri_proof.to_bytes();
let mut r = BoundedReader::new(&bytes);
let layers = r.read_u8()?;
for _ in 0..layers {
let values = r.read_u32()? as usize;
r.read_slice(values)?;
let paths = r.read_u32()? as usize;
check_batch_opening(r.read_slice(paths)?)?;
}
Ok(())
}
pub fn proof_from_bytes(bytes: &[u8]) -> Result<Proof, winterfell::VerifierError> {
let decoded = std::panic::catch_unwind(|| {
let mut reader = BoundedReader::new(bytes);
let proof = Proof::read_from(&mut reader)?;
if reader.has_more_bytes() {
return Err(DeserializationError::InvalidValue("trailing bytes after proof".into()));
}
check_nested_openings(&proof)?;
Ok(proof)
});
match decoded {
Ok(Ok(p)) => Ok(p),
Ok(Err(e)) => Err(winterfell::VerifierError::ProofDeserializationError(format!("{e}"))),
Err(_) => Err(winterfell::VerifierError::ProofDeserializationError(
"malformed proof bytes".into(),
)),
}
}
pub fn verify_release_bytes(
bytes: &[u8],
policy: &PolicyParams,
) -> Result<(), winterfell::VerifierError> {
verify_release(proof_from_bytes(bytes)?, policy)
}
pub fn verify_release(
proof: Proof,
policy: &PolicyParams,
) -> Result<(), winterfell::VerifierError> {
check_nested_openings(&proof)
.map_err(|e| winterfell::VerifierError::ProofDeserializationError(format!("{e}")))?;
let info = proof.trace_info();
if info.width() != WIDTH
|| info.length() != TRACE_LEN
|| info.aux_segment_width() != 0
|| info.num_aux_segments() != 0
|| !info.meta().is_empty()
{
return Err(winterfell::VerifierError::ProofDeserializationError(
"proof trace shape does not match the release-gate AIR".into(),
));
}
if proof.options() != &proof_options() {
return Err(winterfell::VerifierError::UnacceptableProofOptions);
}
let pub_inputs = policy.try_to_public().map_err(winterfell::VerifierError::ProofDeserializationError)?;
let min = winterfell::AcceptableOptions::MinConjecturedSecurity(MIN_SECURITY_BITS);
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
winterfell::verify::<
ReleaseAir,
Blake3_256<BaseElement>,
DefaultRandomCoin<Blake3_256<BaseElement>>,
MerkleTree<Blake3_256<BaseElement>>,
>(proof, pub_inputs, &min)
}))
.unwrap_or_else(|_| {
Err(winterfell::VerifierError::ProofDeserializationError(
"malformed proof rejected by the verifier".into(),
))
})
}
#[cfg(test)]
mod opening_layout_tests {
use super::{check_batch_opening, DIGEST_BYTES};
use winter_utils::{ByteWriter, DeserializationError};
fn blob(count: usize, vectors: &[(usize, usize)]) -> Vec<u8> {
let mut b: Vec<u8> = vec![3];
b.write_usize(count);
for &(claimed, present) in vectors {
b.write_usize(claimed);
b.extend(std::iter::repeat(0xab).take(present * DIGEST_BYTES));
}
b
}
#[test]
fn well_formed_opening_is_accepted() {
assert!(check_batch_opening(&blob(2, &[(1, 1), (2, 2)])).is_ok());
}
#[test]
fn node_vector_count_equal_to_the_remaining_bytes_is_accepted() {
assert!(check_batch_opening(&blob(3, &[(0, 0), (0, 0), (0, 0)])).is_ok());
}
#[test]
fn node_vector_count_over_the_input_is_refused_with_its_reason() {
let Err(DeserializationError::InvalidValue(m)) = check_batch_opening(&blob(5, &[(0, 0)])) else {
panic!("expected InvalidValue")
};
assert!(m.contains("node-vector count exceeds the input"), "{m}");
}
#[test]
fn digest_overclaim_late_in_the_blob_is_an_error_not_a_panic() {
let r = std::panic::catch_unwind(|| check_batch_opening(&blob(2, &[(1, 1), (1, 0)])));
let Ok(Err(DeserializationError::InvalidValue(m))) = r else { panic!("expected a clean InvalidValue, got {r:?}") };
assert!(m.contains("digest count exceeds the input"), "{m}");
}
}