1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use snarkvm_curves::traits::PairingEngine;
use snarkvm_fields::Field;
use snarkvm_r1cs::{ConstraintSystem, Index, LinearCombination, OptionalVec, SynthesisError, Variable};

#[derive(Default)]
pub struct Namespace {
    pub constraint_indices: Vec<usize>,
    pub public_var_indices: Vec<usize>,
    pub private_var_indices: Vec<usize>,
}

pub struct ConstraintSet<E: PairingEngine> {
    pub at: Vec<(E::Fr, Index)>,
    pub bt: Vec<(E::Fr, Index)>,
    pub ct: Vec<(E::Fr, Index)>,
}

impl<E: PairingEngine> Default for ConstraintSet<E> {
    fn default() -> Self {
        ConstraintSet {
            at: Default::default(),
            bt: Default::default(),
            ct: Default::default(),
        }
    }
}

pub struct CircuitSynthesizer<E: PairingEngine> {
    // Constraints
    pub constraints: OptionalVec<ConstraintSet<E>>,

    // Assignments of variables
    pub public_variables: OptionalVec<E::Fr>,
    pub private_variables: OptionalVec<E::Fr>,

    // Technical namespaces used to remove of out-of-scope objects.
    pub namespaces: Vec<Namespace>,
}

impl<E: PairingEngine> Default for CircuitSynthesizer<E> {
    fn default() -> Self {
        Self {
            constraints: Default::default(),
            public_variables: Default::default(),
            private_variables: Default::default(),
            namespaces: Default::default(),
        }
    }
}

impl<E: PairingEngine> ConstraintSystem<E::Fr> for CircuitSynthesizer<E> {
    type Root = Self;

    #[inline]
    fn alloc<F, A, AR>(&mut self, _: A, f: F) -> Result<Variable, SynthesisError>
    where
        F: FnOnce() -> Result<E::Fr, SynthesisError>,
        A: FnOnce() -> AR,
        AR: AsRef<str>,
    {
        let index = self.private_variables.insert(f()?);
        if let Some(ref mut ns) = self.namespaces.last_mut() {
            ns.private_var_indices.push(index);
        }
        Ok(Variable::new_unchecked(Index::Private(index)))
    }

    #[inline]
    fn alloc_input<F, A, AR>(&mut self, _: A, f: F) -> Result<Variable, SynthesisError>
    where
        F: FnOnce() -> Result<E::Fr, SynthesisError>,
        A: FnOnce() -> AR,
        AR: AsRef<str>,
    {
        let index = self.public_variables.insert(f()?);
        if let Some(ref mut ns) = self.namespaces.last_mut() {
            ns.public_var_indices.push(index);
        }
        Ok(Variable::new_unchecked(Index::Public(index)))
    }

    #[inline]
    fn enforce<A, AR, LA, LB, LC>(&mut self, _: A, a: LA, b: LB, c: LC)
    where
        A: FnOnce() -> AR,
        AR: AsRef<str>,
        LA: FnOnce(LinearCombination<E::Fr>) -> LinearCombination<E::Fr>,
        LB: FnOnce(LinearCombination<E::Fr>) -> LinearCombination<E::Fr>,
        LC: FnOnce(LinearCombination<E::Fr>) -> LinearCombination<E::Fr>,
    {
        let index = self.constraints.insert(Default::default());

        push_constraints(a(LinearCombination::zero()), &mut self.constraints[index].at);
        push_constraints(b(LinearCombination::zero()), &mut self.constraints[index].bt);
        push_constraints(c(LinearCombination::zero()), &mut self.constraints[index].ct);

        if let Some(ref mut ns) = self.namespaces.last_mut() {
            ns.constraint_indices.push(index);
        }
    }

    fn push_namespace<NR, N>(&mut self, _: N)
    where
        NR: AsRef<str>,
        N: FnOnce() -> NR,
    {
        self.namespaces.push(Namespace::default());
    }

    fn pop_namespace(&mut self) {
        // Todo @ljedrz: Fix constraint system optimizations.
        // if let Some(ns) = self.namespaces.pop() {
        //     for idx in ns.constraint_indices {
        //         self.constraints.remove(idx);
        //     }
        //
        //     for idx in ns.private_var_indices {
        //         self.private_variables.remove(idx);
        //     }
        //
        //     for idx in ns.public_var_indices {
        //         self.public_variables.remove(idx);
        //     }
        // }
    }

    fn get_root(&mut self) -> &mut Self::Root {
        self
    }

    fn num_constraints(&self) -> usize {
        self.constraints.len()
    }

    fn num_public_variables(&self) -> usize {
        self.public_variables.len()
    }

    fn num_private_variables(&self) -> usize {
        self.private_variables.len()
    }
}

fn push_constraints<F: Field>(l: LinearCombination<F>, constraint: &mut Vec<(F, Index)>) {
    for (var, coeff) in l.as_ref() {
        match var.get_unchecked() {
            Index::Public(i) => constraint.push((*coeff, Index::Public(i))),
            Index::Private(i) => constraint.push((*coeff, Index::Private(i))),
        }
    }
}