arnaucube
arnaucube/circomlibPublic Self-hosted repository
circomlib/circuits/comparators.circom
circuits/comparators.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
20include "bitify.circom";
21include "binsum.circom";
22
23template IsZero() {
24    signal input in;
25    signal output out;
26
27    signal inv;
28
29    inv <-- in!=0 ? 1/in : 0;
30
31    out <== -in*inv +1;
32    in*out === 0;
33}
34
35
36template IsEqual() {
37    signal input in[2];
38    signal output out;
39
40    component isz = IsZero();
41
42    in[1] - in[0] ==> isz.in;
43
44    isz.out ==> out;
45}
46
47template ForceEqualIfEnabled() {
48    signal input enabled;
49    signal input in[2];
50
51    component isz = IsZero();
52
53    in[1] - in[0] ==> isz.in;
54
55    (1 - isz.out)*enabled === 0;
56}
57
58
59// N is the number of bits the input  have.
60// The MSF is the sign bit.
61template LessThan(n) {
62    signal input in[2];
63    signal output out;
64
65    component num2Bits0;
66    component num2Bits1;
67
68    component adder;
69
70    adder = BinSum(n, 2);
71
72    num2Bits0 = Num2Bits(n);
73    num2Bits1 = Num2BitsNeg(n);
74
75    in[0] ==> num2Bits0.in;
76    in[1] ==> num2Bits1.in;
77
78    var i;
79    for (i=0;i<n;i++) {
80        num2Bits0.out[i] ==> adder.in[0][i];
81        num2Bits1.out[i] ==> adder.in[1][i];
82    }
83
84    adder.out[n-1] ==> out;
85}