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.

93 lines
2.1 KiB

6 years ago
6 years ago
6 years ago
  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. /*
  16. Binary Sum
  17. ==========
  18. This component creates a binary sum componet of ops operands and n bits each operand.
  19. e is Number of carries: Depends on the number of operands in the input.
  20. Main Constraint:
  21. in[0][0] * 2^0 + in[0][1] * 2^1 + ..... + in[0][n-1] * 2^(n-1) +
  22. + in[1][0] * 2^0 + in[1][1] * 2^1 + ..... + in[1][n-1] * 2^(n-1) +
  23. + ..
  24. + in[ops-1][0] * 2^0 + in[ops-1][1] * 2^1 + ..... + in[ops-1][n-1] * 2^(n-1) +
  25. ===
  26. out[0] * 2^0 + out[1] * 2^1 + + out[n+e-1] *2(n+e-1)
  27. To waranty binary outputs:
  28. out[0] * (out[0] - 1) === 0
  29. out[1] * (out[0] - 1) === 0
  30. .
  31. .
  32. .
  33. out[n+e-1] * (out[n+e-1] - 1) == 0
  34. */
  35. /*
  36. This function calculates the number of extra bits in the output to do the full sum.
  37. */
  38. function nbits(a) {
  39. var n = 1;
  40. var r = 0;
  41. while (n-1<a) {
  42. r++;
  43. n *= 2;
  44. }
  45. return r;
  46. }
  47. template BinSum(n, ops) {
  48. var nout = nbits((2**n -1)*ops);
  49. signal input in[ops][n];
  50. signal output out[nout];
  51. var lin = 0;
  52. var lout = 0;
  53. var k;
  54. var j;
  55. for (k=0; k<n; k++) {
  56. for (j=0; j<ops; j++) {
  57. lin += in[j][k] * 2**k;
  58. }
  59. }
  60. for (k=0; k<nout; k++) {
  61. out[k] <-- (lin >> k) & 1;
  62. // Ensure out is binary
  63. out[k] * (out[k] - 1) === 0;
  64. lout += out[k] * 2**k;
  65. }
  66. // Ensure the sum;
  67. lin === lout;
  68. }