snarkvm_algorithms/r1cs/
constraint_counter.rs

1// Copyright 2024-2025 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::r1cs::{ConstraintSystem, Index, LinearCombination, Variable, errors::SynthesisError};
17use snarkvm_fields::Field;
18
19/// Constraint counter for testing purposes.
20#[derive(Default)]
21pub struct ConstraintCounter {
22    pub num_public_variables: usize,
23    pub num_private_variables: usize,
24    pub num_constraints: usize,
25}
26
27impl<ConstraintF: Field> ConstraintSystem<ConstraintF> for ConstraintCounter {
28    type Root = Self;
29
30    fn alloc<F, A, AR>(&mut self, _: A, _: F) -> Result<Variable, SynthesisError>
31    where
32        F: FnOnce() -> Result<ConstraintF, SynthesisError>,
33        A: FnOnce() -> AR,
34        AR: AsRef<str>,
35    {
36        let var = Variable::new_unchecked(Index::Private(self.num_private_variables));
37        self.num_private_variables += 1;
38        Ok(var)
39    }
40
41    fn alloc_input<F, A, AR>(&mut self, _: A, _: F) -> Result<Variable, SynthesisError>
42    where
43        F: FnOnce() -> Result<ConstraintF, SynthesisError>,
44        A: FnOnce() -> AR,
45        AR: AsRef<str>,
46    {
47        let var = Variable::new_unchecked(Index::Public(self.num_public_variables));
48        self.num_public_variables += 1;
49
50        Ok(var)
51    }
52
53    fn enforce<A, AR, LA, LB, LC>(&mut self, _: A, _: LA, _: LB, _: LC)
54    where
55        A: FnOnce() -> AR,
56        AR: AsRef<str>,
57        LA: FnOnce(LinearCombination<ConstraintF>) -> LinearCombination<ConstraintF>,
58        LB: FnOnce(LinearCombination<ConstraintF>) -> LinearCombination<ConstraintF>,
59        LC: FnOnce(LinearCombination<ConstraintF>) -> LinearCombination<ConstraintF>,
60    {
61        self.num_constraints += 1;
62    }
63
64    fn push_namespace<NR, N>(&mut self, _: N)
65    where
66        NR: AsRef<str>,
67        N: FnOnce() -> NR,
68    {
69    }
70
71    fn pop_namespace(&mut self) {}
72
73    fn get_root(&mut self) -> &mut Self::Root {
74        self
75    }
76
77    fn num_constraints(&self) -> usize {
78        self.num_constraints
79    }
80
81    fn num_public_variables(&self) -> usize {
82        self.num_public_variables
83    }
84
85    fn num_private_variables(&self) -> usize {
86        self.num_private_variables
87    }
88
89    fn is_in_setup_mode(&self) -> bool {
90        true
91    }
92}