Skip to main content

ns

Macro ns 

Source
macro_rules! ns {
    ($cs:expr, $name:expr) => { ... };
}
Expand description

Creates namespaces for different parts of a circuit when generating constraints. Here, a namespace is equivalent to having a unique span for each part of the circuit. For more information on spans, see the tracing crate.

Takes in a reference to a Constraint System and a string slice representing the name of the namespace. The name is used to identify the namespace.

§Simple Example of using namespaces

use ark_ff::Field;
use ark_r1cs_std::prelude::*;
use ark_relations::gr1cs::{ConstraintSystemRef, SynthesisError};

// Define the circuit structure
pub struct SimpleAdditionCircuit<F: Field> {
    pub a: F,  // Public input 1
    pub b: F,  // Public input 2
    pub c: F,  // Witness (private input)
}

impl<F: Field> SimpleAdditionCircuit<F> {
    pub fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
        // Create a namespace for public inputs
        let cs = ns!(cs, "public_inputs");
        let a_var = FpVar::new_input(cs.clone(), || Ok(self.a))?;
        let b_var = FpVar::new_input(cs.clone(), || Ok(self.b))?;

        // Create another namespace for the witness
        let cs = ns!(cs, "witness");
        let c_var = FpVar::new_witness(cs.clone(), || Ok(self.c))?;

        // Create another namespace for the addition constraint
        let cs = ns!(cs, "addition_constraint");
        let sum = &a_var + &b_var;

        // Enforce that a + b = c
        sum.enforce_equal(&c_var)?;

        Ok(())
    }
}