Skip to main content

qualia_core_db/crypto/
deontic_circuit.rs

1// ── Deontic Access Circuit (arkworks) ──────────────────────────────────────
2/// Groth16 circuit for zero-knowledge proof verification.
3
4#[cfg(feature = "zk-culling")]
5use ark_bls12_381::{Bls12_381, Fr};
6#[cfg(feature = "zk-culling")]
7use ark_groth16::{Groth16, Proof, ProvingKey, VerifyingKey};
8#[cfg(feature = "zk-culling")]
9use ark_relations::gr1cs::{
10    ConstraintSynthesizer, ConstraintSystemRef, LinearCombination, SynthesisError, Variable,
11};
12#[cfg(feature = "zk-culling")]
13use ark_serialize::CanonicalDeserialize;
14#[cfg(feature = "zk-culling")]
15use ark_snark::SNARK;
16
17#[cfg(feature = "zk-culling")]
18#[derive(Clone)]
19pub struct DeonticAccessCircuit {
20    pub user_did_commitment: Option<Fr>,
21    pub role_id: Option<Fr>,
22    pub action_permission: Option<Fr>,
23    pub policy_root: Option<Fr>,
24    pub temporal_constraint: Option<Fr>,
25}
26
27#[cfg(feature = "zk-culling")]
28impl ConstraintSynthesizer<Fr> for DeonticAccessCircuit {
29    fn generate_constraints(self, cs: ConstraintSystemRef<Fr>) -> Result<(), SynthesisError> {
30        let did_var = cs.new_witness_variable(|| {
31            self.user_did_commitment
32                .ok_or(SynthesisError::AssignmentMissing)
33        })?;
34        let role_var =
35            cs.new_witness_variable(|| self.role_id.ok_or(SynthesisError::AssignmentMissing))?;
36        let action_var = cs.new_witness_variable(|| {
37            self.action_permission
38                .ok_or(SynthesisError::AssignmentMissing)
39        })?;
40        let root_var =
41            cs.new_input_variable(|| self.policy_root.ok_or(SynthesisError::AssignmentMissing))?;
42        let time_var = cs.new_input_variable(|| {
43            self.temporal_constraint
44                .ok_or(SynthesisError::AssignmentMissing)
45        })?;
46
47        // Access constraint: the prover's secret (did, role, action) must sum to the
48        // public `policy_root` — i.e. they hold a credential authorised under the
49        // committed policy. (Simplified additive commitment; Merkle-set membership is
50        // a future hardening, not faked here.)
51        cs.enforce_r1cs_constraint(
52            || LinearCombination::from(did_var) + role_var + action_var,
53            || LinearCombination::from(Variable::One),
54            || LinearCombination::from(root_var),
55        )?;
56        // `temporal_constraint` is bound as a public input (the verifier checks the
57        // proof was generated for this exact timestamp), but range enforcement
58        // (notBefore <= t <= notAfter) is a documented PendingImplementation. We do
59        // NOT fake it with a tautological `t * 1 = t` constraint that enforces nothing.
60        let _ = time_var;
61        Ok(())
62    }
63}
64
65#[cfg(feature = "zk-culling")]
66pub struct ZkAccessVerifier {
67    verifying_key: Option<VerifyingKey<Bls12_381>>,
68}
69
70#[cfg(feature = "zk-culling")]
71impl ZkAccessVerifier {
72    /// Create a verifier with no key loaded — verification fails closed
73    /// until a verifying key is attached.
74    pub fn new() -> Self {
75        Self {
76            verifying_key: None,
77        }
78    }
79
80    /// Verify a Groth16 proof (uncompressed bytes) against `public_inputs`.
81    /// Fails closed with `SignatureVerificationFailed` when no verifying
82    /// key is loaded.
83    pub fn verify_access(
84        &self,
85        proof: &[u8],
86        public_inputs: &[Fr],
87    ) -> Result<bool, crate::fiduciary_crypto::MlDsaError> {
88        if let Some(ref vk) = self.verifying_key {
89            let parsed_proof =
90                Proof::<Bls12_381>::deserialize_uncompressed(&mut &*proof).map_err(|e| {
91                    crate::fiduciary_crypto::MlDsaError::SignatureVerificationFailed(e.to_string())
92                })?;
93            Groth16::<Bls12_381>::verify(vk, public_inputs, &parsed_proof).map_err(|e| {
94                crate::fiduciary_crypto::MlDsaError::SignatureVerificationFailed(e.to_string())
95            })
96        } else {
97            Err(
98                crate::fiduciary_crypto::MlDsaError::SignatureVerificationFailed(
99                    "Verifying key not loaded".to_string(),
100                ),
101            )
102        }
103    }
104}
105
106#[cfg(feature = "zk-culling")]
107impl Default for ZkAccessVerifier {
108    fn default() -> Self {
109        Self::new()
110    }
111}
112
113/// Run the Groth16 circuit-specific trusted setup for
114/// `DeonticAccessCircuit` over BLS12-381, returning the (proving key,
115/// verifying key) pair.
116#[cfg(feature = "zk-culling")]
117pub fn generate_deontic_crs() -> Result<(ProvingKey<Bls12_381>, VerifyingKey<Bls12_381>), String> {
118    let circuit = DeonticAccessCircuit {
119        user_did_commitment: None,
120        role_id: None,
121        action_permission: None,
122        policy_root: None,
123        temporal_constraint: None,
124    };
125    let mut rng = crate::zk_proofs::zk_secure_rng();
126    Groth16::<Bls12_381>::circuit_specific_setup(circuit, &mut rng)
127        .map_err(|e| format!("Failed to generate parameters: {e}"))
128}
129
130#[cfg(test)]
131#[cfg(feature = "zk-culling")]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn test_circuit_setup() {
137        assert!(generate_deontic_crs().is_ok());
138    }
139
140    #[test]
141    fn test_deontic_proof_roundtrip_and_soundness() {
142        use ark_ff::UniformRand;
143        let mut rng = crate::zk_proofs::zk_secure_rng();
144        let (pk, vk) = generate_deontic_crs().unwrap();
145
146        // A satisfying credential: did + role + action == policy_root.
147        let did = Fr::rand(&mut rng);
148        let role = Fr::rand(&mut rng);
149        let action = Fr::rand(&mut rng);
150        let policy_root = did + role + action;
151        let temporal = Fr::from(1_700_000_000u64);
152
153        let circuit = DeonticAccessCircuit {
154            user_did_commitment: Some(did),
155            role_id: Some(role),
156            action_permission: Some(action),
157            policy_root: Some(policy_root),
158            temporal_constraint: Some(temporal),
159        };
160        let proof = Groth16::<Bls12_381>::prove(&pk, circuit, &mut rng).unwrap();
161
162        // Valid: the public inputs match the proven relation.
163        assert!(
164            Groth16::<Bls12_381>::verify(&vk, &[policy_root, temporal], &proof).unwrap(),
165            "a satisfying deontic access proof must verify"
166        );
167
168        // Soundness: a falsified policy_root must be rejected.
169        assert!(
170            !Groth16::<Bls12_381>::verify(&vk, &[policy_root + Fr::from(1u64), temporal], &proof)
171                .unwrap(),
172            "the proof must NOT verify against a falsified policy_root"
173        );
174    }
175}