arnaucube
arnaucube/grapevine-sonobePublic Self-hosted repository
grapevine-sonobe/circom/node_modules/circomlib/circuits/bitify.circom
circom/node_modules/circomlib/circuits/bitify.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*/
 19pragma circom 2.0.0;
 20
 21include "comparators.circom";
 22include "aliascheck.circom";
 23
 24
 25template Num2Bits(n) {
 26    signal input in;
 27    signal output out[n];
 28    var lc1=0;
 29
 30    var e2=1;
 31    for (var i = 0; i<n; i++) {
 32        out[i] <-- (in >> i) & 1;
 33        out[i] * (out[i] -1 ) === 0;
 34        lc1 += out[i] * e2;
 35        e2 = e2+e2;
 36    }
 37
 38    lc1 === in;
 39}
 40
 41template Num2Bits_strict() {
 42    signal input in;
 43    signal output out[254];
 44
 45    component aliasCheck = AliasCheck();
 46    component n2b = Num2Bits(254);
 47    in ==> n2b.in;
 48
 49    for (var i=0; i<254; i++) {
 50        n2b.out[i] ==> out[i];
 51        n2b.out[i] ==> aliasCheck.in[i];
 52    }
 53}
 54
 55template Bits2Num(n) {
 56    signal input in[n];
 57    signal output out;
 58    var lc1=0;
 59
 60    var e2 = 1;
 61    for (var i = 0; i<n; i++) {
 62        lc1 += in[i] * e2;
 63        e2 = e2 + e2;
 64    }
 65
 66    lc1 ==> out;
 67}
 68
 69template Bits2Num_strict() {
 70    signal input in[254];
 71    signal output out;
 72
 73    component aliasCheck = AliasCheck();
 74    component b2n = Bits2Num(254);
 75
 76    for (var i=0; i<254; i++) {
 77        in[i] ==> b2n.in[i];
 78        in[i] ==> aliasCheck.in[i];
 79    }
 80
 81    b2n.out ==> out;
 82}
 83
 84template Num2BitsNeg(n) {
 85    signal input in;
 86    signal output out[n];
 87    var lc1=0;
 88
 89    component isZero;
 90
 91    isZero = IsZero();
 92
 93    var neg = n == 0 ? 0 : 2**n - in;
 94
 95    for (var i = 0; i<n; i++) {
 96        out[i] <-- (neg >> i) & 1;
 97        out[i] * (out[i] -1 ) === 0;
 98        lc1 += out[i] * 2**i;
 99    }
100
101    in ==> isZero.in;
102
103
104
105    lc1 + isZero.out * 2**n === 2**n - in;
106}