Skip to main content

world_id_proof/
proof.rs

1//! Internal proof generation for the World ID Protocol.
2//!
3//! Provides functionality for generating ZKPs (zero-knowledge proofs), including
4//! Uniqueness Proofs (internally also called Nullifier Proofs `π2`) and Session Proofs. It
5//! also contains internal proof computation such as Query Proofs `π1`.
6//!
7//! The proof generation workflow for Uniqueness Proofs consists of:
8//! 1. Loading circuit proving material (zkeys and witness graphs)
9//! 2. Signing OPRF queries and generating a Query Proof `π1`
10//! 3. Interacting with OPRF services to obtain challenge responses
11//! 4. Verifying `DLog` equality proofs from OPRF nodes
12//! 5. Generating the final Uniqueness Proof `π2`
13
14use ark_bn254::Bn254;
15use groth16_material::Groth16Error;
16use rand::{CryptoRng, Rng};
17use std::{io::Read, path::Path};
18use world_id_primitives::{
19    Credential, FieldElement, RequestItem, TREE_DEPTH, circuit_inputs::NullifierProofCircuitInput,
20};
21
22pub use groth16_material::circom::{
23    CircomGroth16Material, CircomGroth16MaterialBuilder, ZkeyError,
24};
25
26use crate::nullifier::OprfNullifier;
27
28pub(crate) const OPRF_PROOF_DS: &[u8] = b"World ID Proof";
29
30/// The SHA-256 fingerprint of the `OPRFQuery` `ZKey`.
31pub const QUERY_ZKEY_FINGERPRINT: &str =
32    "292483d5631c28f15613b26bee6cf62a8cc9bbd74a97f375aea89e4dfbf7a10f";
33/// The SHA-256 fingerprint of the `OPRFNullifier` `ZKey`.
34pub const NULLIFIER_ZKEY_FINGERPRINT: &str =
35    "14bd468c7fc6e91e48fa776995c267493845d93648a4c1ee24c2567b18b1795a";
36
37/// The SHA-256 fingerprint of the `OPRFQuery` witness graph.
38pub const QUERY_GRAPH_FINGERPRINT: &str =
39    "6b0cb90304c510f9142a555fe2b7cf31b9f68f6f37286f4471fd5d03e91da311";
40/// The SHA-256 fingerprint of the `OPRFNullifier` witness graph.
41pub const NULLIFIER_GRAPH_FINGERPRINT: &str =
42    "c1d951716e3b74b72e4ea0429986849cadc43cccc630a7ee44a56a6199a66b9a";
43
44#[cfg(all(feature = "embed-zkeys", not(docsrs)))]
45const CIRCUIT_ARCHIVE: &[u8] = {
46    #[cfg(feature = "zstd-compress-zkeys")]
47    {
48        include_bytes!(concat!(env!("OUT_DIR"), "/circuit_files.tar.zst"))
49    }
50    #[cfg(not(feature = "zstd-compress-zkeys"))]
51    {
52        include_bytes!(concat!(env!("OUT_DIR"), "/circuit_files.tar"))
53    }
54};
55
56#[cfg(all(feature = "embed-zkeys", docsrs))]
57const CIRCUIT_ARCHIVE: &[u8] = &[];
58
59#[cfg(feature = "embed-zkeys")]
60#[derive(Clone, Debug)]
61pub struct EmbeddedCircuitFiles {
62    /// Embedded query witness graph bytes.
63    pub query_graph: Vec<u8>,
64    /// Embedded nullifier witness graph bytes.
65    pub nullifier_graph: Vec<u8>,
66    /// Embedded query zkey bytes (decompressed if `compress-zkeys` is enabled).
67    pub query_zkey: Vec<u8>,
68    /// Embedded nullifier zkey bytes (decompressed if `compress-zkeys` is enabled).
69    pub nullifier_zkey: Vec<u8>,
70}
71
72#[cfg(feature = "embed-zkeys")]
73static CIRCUIT_FILES: std::sync::OnceLock<Result<EmbeddedCircuitFiles, String>> =
74    std::sync::OnceLock::new();
75
76/// Error type for OPRF operations and proof generation.
77#[derive(Debug, thiserror::Error)]
78pub enum ProofError {
79    /// Error originating from `oprf_client`.
80    #[error(transparent)]
81    OprfError(#[from] taceo_oprf::client::Error),
82    /// Errors originating from Groth16 proof generation or verification.
83    #[error(transparent)]
84    ZkError(#[from] Groth16Error),
85    /// Catch-all for other internal errors.
86    #[error(transparent)]
87    InternalError(#[from] eyre::Report),
88}
89
90// ============================================================================
91// Circuit Material Loaders
92// ============================================================================
93
94/// Loads the [`CircomGroth16Material`] for the uniqueness proof (internally also nullifier proof)
95/// from the embedded keys in the binary without caching.
96///
97/// # Returns
98/// The nullifier material.
99///
100/// # Errors
101/// Will return an error if the zkey file cannot be loaded.
102#[cfg(feature = "embed-zkeys")]
103pub fn load_embedded_nullifier_material() -> eyre::Result<CircomGroth16Material> {
104    let files = load_embedded_circuit_files()?;
105    load_nullifier_material_from_reader(
106        files.nullifier_zkey.as_slice(),
107        files.nullifier_graph.as_slice(),
108    )
109}
110
111/// Loads the [`CircomGroth16Material`] for the uniqueness proof (internally also query proof)
112/// from the optional zkey file or from embedded keys in the binary.
113///
114/// # Returns
115/// The query material
116///
117/// # Errors
118/// Will return an error if the zkey file cannot be loaded.
119#[cfg(feature = "embed-zkeys")]
120pub fn load_embedded_query_material() -> eyre::Result<CircomGroth16Material> {
121    let files = load_embedded_circuit_files()?;
122    load_query_material_from_reader(files.query_zkey.as_slice(), files.query_graph.as_slice())
123}
124
125/// Loads the [`CircomGroth16Material`] for the nullifier proof from the provided reader.
126///
127/// # Errors
128/// Will return an error if the material cannot be loaded or verified.
129pub fn load_nullifier_material_from_reader(
130    zkey: impl Read,
131    graph: impl Read,
132) -> eyre::Result<CircomGroth16Material> {
133    Ok(build_nullifier_builder().build_from_reader(zkey, graph)?)
134}
135
136/// Loads the [`CircomGroth16Material`] for the query proof from the provided reader.
137///
138/// # Errors
139/// Will return an error if the material cannot be loaded or verified.
140pub fn load_query_material_from_reader(
141    zkey: impl Read,
142    graph: impl Read,
143) -> eyre::Result<CircomGroth16Material> {
144    Ok(build_query_builder().build_from_reader(zkey, graph)?)
145}
146
147/// Loads the [`CircomGroth16Material`] for the nullifier proof from the provided paths.
148///
149/// # Panics
150/// Will panic if the material cannot be loaded or verified.
151pub fn load_nullifier_material_from_paths(
152    zkey: impl AsRef<Path>,
153    graph: impl AsRef<Path>,
154) -> CircomGroth16Material {
155    build_nullifier_builder()
156        .build_from_paths(zkey, graph)
157        .expect("works when loading embedded groth16-material")
158}
159
160/// Loads the [`CircomGroth16Material`] for the query proof from the provided paths.
161///
162/// # Errors
163/// Will return an error if the material cannot be loaded or verified.
164pub fn load_query_material_from_paths(
165    zkey: impl AsRef<Path>,
166    graph: impl AsRef<Path>,
167) -> eyre::Result<CircomGroth16Material> {
168    Ok(build_query_builder().build_from_paths(zkey, graph)?)
169}
170
171#[cfg(feature = "embed-zkeys")]
172pub fn load_embedded_circuit_files() -> eyre::Result<EmbeddedCircuitFiles> {
173    let files = get_circuit_files()?;
174    Ok(files.clone())
175}
176
177#[cfg(feature = "embed-zkeys")]
178fn get_circuit_files() -> eyre::Result<&'static EmbeddedCircuitFiles> {
179    let files = CIRCUIT_FILES.get_or_init(|| init_circuit_files().map_err(|e| e.to_string()));
180    match files {
181        Ok(files) => Ok(files),
182        Err(err) => Err(eyre::eyre!(err.clone())),
183    }
184}
185
186#[cfg(feature = "embed-zkeys")]
187fn init_circuit_files() -> eyre::Result<EmbeddedCircuitFiles> {
188    use std::io::Read as _;
189
190    use eyre::ContextCompat;
191
192    // Step 1: Decode archive bytes (optional zstd decompression)
193    let tar_bytes: Vec<u8> = {
194        #[cfg(feature = "zstd-compress-zkeys")]
195        {
196            zstd::stream::decode_all(CIRCUIT_ARCHIVE)?
197        }
198        #[cfg(not(feature = "zstd-compress-zkeys"))]
199        {
200            CIRCUIT_ARCHIVE.to_vec()
201        }
202    };
203
204    // Step 2: Untar — extract 4 entries by filename
205    let mut query_graph = None;
206    let mut nullifier_graph = None;
207    let mut query_zkey = None;
208    let mut nullifier_zkey = None;
209
210    let mut archive = tar::Archive::new(tar_bytes.as_slice());
211    for entry in archive.entries()? {
212        let mut entry = entry?;
213        let path = entry.path()?.to_path_buf();
214        let name = path
215            .file_name()
216            .and_then(|n| n.to_str())
217            .unwrap_or_default();
218
219        let mut buf = Vec::with_capacity(entry.size() as usize);
220        entry.read_to_end(&mut buf)?;
221
222        match name {
223            "OPRFQueryGraph.bin" => query_graph = Some(buf),
224            "OPRFNullifierGraph.bin" => nullifier_graph = Some(buf),
225            n if n.starts_with("OPRFQuery.arks.zkey") => query_zkey = Some(buf),
226            n if n.starts_with("OPRFNullifier.arks.zkey") => nullifier_zkey = Some(buf),
227            _ => {}
228        }
229    }
230
231    let query_graph = query_graph.context("OPRFQueryGraph.bin not found in archive")?;
232    let nullifier_graph = nullifier_graph.context("OPRFNullifierGraph.bin not found in archive")?;
233    #[allow(unused_mut)]
234    let mut query_zkey = query_zkey.context("OPRFQuery zkey not found in archive")?;
235    #[allow(unused_mut)]
236    let mut nullifier_zkey = nullifier_zkey.context("OPRFNullifier zkey not found in archive")?;
237
238    // Step 3: ARK decompress zkeys if compress-zkeys is active
239    #[cfg(feature = "compress-zkeys")]
240    {
241        query_zkey = ark_decompress_zkey(&query_zkey)?;
242        nullifier_zkey = ark_decompress_zkey(&nullifier_zkey)?;
243    }
244
245    Ok(EmbeddedCircuitFiles {
246        query_graph,
247        nullifier_graph,
248        query_zkey,
249        nullifier_zkey,
250    })
251}
252
253/// ARK-decompresses a zkey.
254#[cfg(feature = "compress-zkeys")]
255pub fn ark_decompress_zkey(compressed: &[u8]) -> eyre::Result<Vec<u8>> {
256    let zkey = <circom_types::groth16::ArkZkey<Bn254> as ark_serialize::CanonicalDeserialize>::deserialize_with_mode(
257        compressed,
258        ark_serialize::Compress::Yes,
259        ark_serialize::Validate::Yes,
260    )?;
261
262    let mut uncompressed = Vec::new();
263    ark_serialize::CanonicalSerialize::serialize_with_mode(
264        &zkey,
265        &mut uncompressed,
266        ark_serialize::Compress::No,
267    )?;
268    Ok(uncompressed)
269}
270
271fn build_nullifier_builder() -> CircomGroth16MaterialBuilder {
272    CircomGroth16MaterialBuilder::new()
273        .fingerprint_zkey(NULLIFIER_ZKEY_FINGERPRINT.into())
274        .fingerprint_graph(NULLIFIER_GRAPH_FINGERPRINT.into())
275        .bbf_num_2_bits_helper()
276        .bbf_inv()
277        .bbf_legendre()
278        .bbf_sqrt_input()
279        .bbf_sqrt_unchecked()
280}
281
282fn build_query_builder() -> CircomGroth16MaterialBuilder {
283    CircomGroth16MaterialBuilder::new()
284        .fingerprint_zkey(QUERY_ZKEY_FINGERPRINT.into())
285        .fingerprint_graph(QUERY_GRAPH_FINGERPRINT.into())
286        .bbf_num_2_bits_helper()
287        .bbf_inv()
288        .bbf_legendre()
289        .bbf_sqrt_input()
290        .bbf_sqrt_unchecked()
291}
292
293// ============================================================================
294// Uniqueness Proof (internally also called nullifier proof) Generation
295// ============================================================================
296
297/// FIXME. Description.
298/// Generates the Groth16 nullifier proof ....
299///
300/// Internally can be a Session Proof or Uniqueness Proof
301///
302/// # Errors
303///
304/// Returns [`ProofError`] if proof generation or verification fails.
305#[allow(clippy::too_many_arguments)]
306pub fn generate_nullifier_proof<R: Rng + CryptoRng>(
307    nullifier_material: &CircomGroth16Material,
308    rng: &mut R,
309    credential: &Credential,
310    credential_sub_blinding_factor: FieldElement,
311    oprf_nullifier: OprfNullifier,
312    request_item: &RequestItem,
313    session_id: Option<FieldElement>,
314    session_id_r_seed: FieldElement,
315    expires_at_min: u64,
316) -> Result<
317    (
318        ark_groth16::Proof<Bn254>,
319        Vec<ark_babyjubjub::Fq>,
320        ark_babyjubjub::Fq,
321    ),
322    ProofError,
323> {
324    let cred_signature = credential
325        .signature
326        .clone()
327        .ok_or_else(|| ProofError::InternalError(eyre::eyre!("Credential not signed")))?;
328
329    let nullifier_input = NullifierProofCircuitInput::<TREE_DEPTH> {
330        query_input: oprf_nullifier.query_proof_input,
331        issuer_schema_id: credential.issuer_schema_id.into(),
332        cred_pk: credential.issuer.pk,
333        cred_hashes: [*credential.claims_hash()?, *credential.associated_data_hash],
334        cred_genesis_issued_at: credential.genesis_issued_at.into(),
335        cred_genesis_issued_at_min: request_item.genesis_issued_at_min.unwrap_or(0).into(),
336        cred_expires_at: credential.expires_at.into(),
337        cred_id: credential.id.into(),
338        cred_sub_blinding_factor: *credential_sub_blinding_factor,
339        cred_s: cred_signature.s,
340        cred_r: cred_signature.r,
341        id_commitment_r: *session_id_r_seed,
342        id_commitment: *session_id.unwrap_or(FieldElement::ZERO),
343        dlog_e: oprf_nullifier.verifiable_oprf_output.dlog_proof.e,
344        dlog_s: oprf_nullifier.verifiable_oprf_output.dlog_proof.s,
345        oprf_pk: oprf_nullifier
346            .verifiable_oprf_output
347            .oprf_public_key
348            .inner(),
349        oprf_response_blinded: oprf_nullifier.verifiable_oprf_output.blinded_response,
350        oprf_response: oprf_nullifier.verifiable_oprf_output.unblinded_response,
351        signal_hash: *request_item.signal_hash(),
352        // The `current_timestamp` constraint in the circuit is used to specify the minimum expiration time for the credential.
353        // The circuit verifies that `current_timestamp < cred_expires_at`.
354        current_timestamp: expires_at_min.into(),
355    };
356
357    let (proof, public) = nullifier_material.generate_proof(&nullifier_input, rng)?;
358    nullifier_material.verify_proof(&proof, &public)?;
359
360    let nullifier = public[0];
361
362    // Verify that the computed nullifier matches the OPRF output.
363    if nullifier != oprf_nullifier.verifiable_oprf_output.output {
364        return Err(ProofError::InternalError(eyre::eyre!(
365            "Computed nullifier does not match OPRF output"
366        )));
367    }
368
369    Ok((proof, public, nullifier))
370}
371
372#[cfg(all(test, feature = "embed-zkeys"))]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn loads_embedded_circuit_files() {
378        let files = load_embedded_circuit_files().unwrap();
379        assert!(!files.query_graph.is_empty());
380        assert!(!files.nullifier_graph.is_empty());
381        assert!(!files.query_zkey.is_empty());
382        assert!(!files.nullifier_zkey.is_empty());
383    }
384
385    #[test]
386    fn builds_materials_from_embedded_readers() {
387        let files = load_embedded_circuit_files().unwrap();
388        load_query_material_from_reader(files.query_zkey.as_slice(), files.query_graph.as_slice())
389            .unwrap();
390        load_nullifier_material_from_reader(
391            files.nullifier_zkey.as_slice(),
392            files.nullifier_graph.as_slice(),
393        )
394        .unwrap();
395    }
396
397    #[test]
398    fn convenience_embedded_material_loaders_work() {
399        load_embedded_query_material().unwrap();
400        load_embedded_nullifier_material().unwrap();
401    }
402
403    #[cfg(feature = "compress-zkeys")]
404    #[test]
405    fn ark_decompress_zkey_roundtrip() {
406        use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Compress, Validate};
407        use circom_types::{ark_bn254::Bn254, groth16::ArkZkey};
408
409        let files = load_embedded_circuit_files().unwrap();
410        let zkey = ArkZkey::<Bn254>::deserialize_with_mode(
411            files.query_zkey.as_slice(),
412            Compress::No,
413            Validate::Yes,
414        )
415        .unwrap();
416        let mut compressed = Vec::new();
417        zkey.serialize_with_mode(&mut compressed, Compress::Yes)
418            .unwrap();
419
420        let decompressed = ark_decompress_zkey(&compressed).unwrap();
421        assert_eq!(decompressed, files.query_zkey);
422    }
423}