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.

101 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. pragma circom 2.0.0;
  39. function nbits(a) {
  40. var n = 1;
  41. var r = 0;
  42. while (n-1<a) {
  43. r++;
  44. n *= 2;
  45. }
  46. return r;
  47. }
  48. template BinSum(n, ops) {
  49. var nout = nbits((2**n -1)*ops);
  50. signal input in[ops][n];
  51. signal output out[nout];
  52. var lin = 0;
  53. var lout = 0;
  54. var k;
  55. var j;
  56. var e2;
  57. e2 = 1;
  58. for (k=0; k<n; k++) {
  59. for (j=0; j<ops; j++) {
  60. lin += in[j][k] * e2;
  61. }
  62. e2 = e2 + e2;
  63. }
  64. e2 = 1;
  65. for (k=0; k<nout; k++) {
  66. out[k] <-- (lin >> k) & 1;
  67. // Ensure out is binary
  68. out[k] * (out[k] - 1) === 0;
  69. lout += out[k] * e2;
  70. e2 = e2+e2;
  71. }
  72. // Ensure the sum;
  73. lin === lout;
  74. }