arnaucube
arnaucube/grapevine-sonobePublic Self-hosted repository
grapevine-sonobe/circom/node_modules/circomlib/circuits/binsub.circom
circom/node_modules/circomlib/circuits/binsub.circomRaw
 1 /*
 2    Copyright 2018 0KIMS association.
 3
 4    This file is part of circom (Zero Knowledge Circuit Compiler).
 5
 6    circom is a free software: you can redistribute it and/or modify it
 7    under the terms of the GNU General Public License as published by
 8    the Free Software Foundation, either version 3 of the License, or
 9    (at your option) any later version.
10
11    circom is distributed in the hope that it will be useful, but WITHOUT
12    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14    License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with circom. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20/*
21This component creates a binary substraction.
22
23
24Main Constraint:
25   (in[0][0]     * 2^0  +  in[0][1]     * 2^1  + ..... + in[0][n-1]    * 2^(n-1))  +
26 +  2^n
27 - (in[1][0]     * 2^0  +  in[1][1]     * 2^1  + ..... + in[1][n-1]    * 2^(n-1))
28 ===
29   out[0] * 2^0  + out[1] * 2^1 +   + out[n-1] *2^(n-1) + aux
30
31
32    out[0]     * (out[0] - 1) === 0
33    out[1]     * (out[0] - 1) === 0
34    .
35    .
36    .
37    out[n-1]   * (out[n-1] - 1) === 0
38    aux * (aux-1) == 0
39
40*/
41pragma circom 2.0.0;
42
43template BinSub(n) {
44    signal input in[2][n];
45    signal output out[n];
46
47    signal aux;
48
49    var lin = 2**n;
50    var lout = 0;
51
52    var i;
53
54    for (i=0; i<n; i++) {
55        lin = lin + in[0][i]*(2**i);
56        lin = lin - in[1][i]*(2**i);
57    }
58
59    for (i=0; i<n; i++) {
60        out[i] <-- (lin >> i) & 1;
61
62        // Ensure out is binary
63        out[i] * (out[i] - 1) === 0;
64
65        lout = lout + out[i]*(2**i);
66    }
67
68    aux <-- (lin >> n) & 1;
69    aux*(aux-1) === 0;
70    lout = lout + aux*(2**n);
71
72    // Ensure the sum;
73    lin === lout;
74}