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.

100 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. /*
  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. var e2;
  56. e2 = 1;
  57. for (k=0; k<n; k++) {
  58. for (j=0; j<ops; j++) {
  59. lin += in[j][k] * e2;
  60. }
  61. e2 = e2 + e2;
  62. }
  63. e2 = 1;
  64. for (k=0; k<nout; k++) {
  65. out[k] <-- (lin >> k) & 1;
  66. // Ensure out is binary
  67. out[k] * (out[k] - 1) === 0;
  68. lout += out[k] * e2;
  69. e2 = e2+e2;
  70. }
  71. // Ensure the sum;
  72. lin === lout;
  73. }