You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.2 KiB

  1. /*
  2. Copyright 2018 0KIMS association.
  3. This file is part of circom (Zero Knowledge Circuit Compiler).
  4. circom is a free software: you can redistribute it and/or modify it
  5. under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. circom is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  10. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
  11. License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with circom. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. pragma circom 2.0.0;
  16. include "comparators.circom";
  17. include "aliascheck.circom";
  18. template Num2Bits(n) {
  19. signal input in;
  20. signal output out[n];
  21. var lc1=0;
  22. var e2=1;
  23. for (var i = 0; i<n; i++) {
  24. out[i] <-- (in >> i) & 1;
  25. out[i] * (out[i] -1 ) === 0;
  26. lc1 += out[i] * e2;
  27. e2 = e2+e2;
  28. }
  29. lc1 === in;
  30. }
  31. template Num2Bits_strict() {
  32. signal input in;
  33. signal output out[254];
  34. component aliasCheck = AliasCheck();
  35. component n2b = Num2Bits(254);
  36. in ==> n2b.in;
  37. for (var i=0; i<254; i++) {
  38. n2b.out[i] ==> out[i];
  39. n2b.out[i] ==> aliasCheck.in[i];
  40. }
  41. }
  42. template Bits2Num(n) {
  43. signal input in[n];
  44. signal output out;
  45. var lc1=0;
  46. var e2 = 1;
  47. for (var i = 0; i<n; i++) {
  48. lc1 += in[i] * e2;
  49. e2 = e2 + e2;
  50. }
  51. lc1 ==> out;
  52. }
  53. template Bits2Num_strict() {
  54. signal input in[254];
  55. signal output out;
  56. component aliasCheck = AliasCheck();
  57. component b2n = Bits2Num(254);
  58. for (var i=0; i<254; i++) {
  59. in[i] ==> b2n.in[i];
  60. in[i] ==> aliasCheck.in[i];
  61. }
  62. b2n.out ==> out;
  63. }
  64. template Num2BitsNeg(n) {
  65. signal input in;
  66. signal output out[n];
  67. var lc1=0;
  68. component isZero;
  69. isZero = IsZero();
  70. var neg = n == 0 ? 0 : 2**n - in;
  71. for (var i = 0; i<n; i++) {
  72. out[i] <-- (neg >> i) & 1;
  73. out[i] * (out[i] -1 ) === 0;
  74. lc1 += out[i] * 2**i;
  75. }
  76. in ==> isZero.in;
  77. lc1 + isZero.out * 2**n === 2**n - in;
  78. }