use serde::{Deserialize, Serialize};
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;
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: "a1b2c3d4e5f60718293a4b5c6d7e8f90".into(),
action_commitment: "0f1e2d3c4b5a69788796a5b4c3d2e1f0".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
}
fn commitment_elems(&self) -> (BaseElement, BaseElement) {
(hex_to_felt(&self.policy_commitment), hex_to_felt(&self.action_commitment))
}
pub fn to_public(&self) -> PublicInputs {
let (pc, ac) = self.commitment_elems();
let wc: [BaseElement; COMMIT_LIMBS] =
core::array::from_fn(|m| BaseElement::new(self.witness_commitment[m].parse::<u128>().unwrap_or(0)));
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,
action_commitment: ac,
witness_commitment: wc,
}
}
}
fn hex_to_felt(h: &str) -> BaseElement {
let mut acc: u128 = 0;
for c in h.chars().filter(|c| c.is_ascii_hexdigit()).take(32) {
acc = acc.wrapping_mul(16).wrapping_add(c.to_digit(16).unwrap() as u128);
}
BaseElement::new(acc)
}
#[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,
pub action_commitment: BaseElement,
pub witness_commitment: [BaseElement; COMMIT_LIMBS],
}
impl ToElements<BaseElement> for PublicInputs {
fn to_elements(&self) -> Vec<BaseElement> {
let mut v = Vec::with_capacity(12 + 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.push(self.policy_commitment);
v.push(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(
32,
8,
0,
FieldExtension::None,
8,
31,
BatchingMethod::Linear,
BatchingMethod::Linear,
)
}
pub const MIN_SECURITY_BITS: u32 = 95;
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> {
let trace = build_trace(witness, policy);
let prover = ReleaseProver::new(proof_options(), policy.clone());
prover.prove(trace)
}
pub fn verify_release(
proof: Proof,
policy: &PolicyParams,
) -> Result<(), winterfell::VerifierError> {
let pub_inputs = policy.to_public();
let min = winterfell::AcceptableOptions::MinConjecturedSecurity(MIN_SECURITY_BITS);
winterfell::verify::<
ReleaseAir,
Blake3_256<BaseElement>,
DefaultRandomCoin<Blake3_256<BaseElement>>,
MerkleTree<Blake3_256<BaseElement>>,
>(proof, pub_inputs, &min)
}