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.

127 lines
2.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. /*
  2. Copyright 2018 0kims association.
  3. This file is part of zksnark JavaScript library.
  4. zksnark JavaScript library is a free software: you can redistribute it and/or
  5. modify it under the terms of the GNU General Public License as published by the
  6. Free Software Foundation, either version 3 of the License, or (at your option)
  7. any later version.
  8. zksnark JavaScript library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  10. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. more details.
  12. You should have received a copy of the GNU General Public License along with
  13. zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. const fUtils = require("./futils.js");
  16. class RatField {
  17. constructor(F) {
  18. this.F = F;
  19. this.zero = [F.zero, F.one];
  20. this.one = [F.one, F.one];
  21. this.two = [F.two, F.one];
  22. this.twoinv = [F.one, F.two];
  23. this.q = F.q;
  24. }
  25. add(a,b) {
  26. return [
  27. this.F.add(
  28. this.F.mul(a[0], b[1]),
  29. this.F.mul(a[1], b[0])),
  30. this.F.mul(a[1], b[1])];
  31. }
  32. double(a) {
  33. return [this.F.add(a[0], a[0]), a[1]];
  34. }
  35. sub(a,b) {
  36. return [
  37. this.F.sub(
  38. this.F.mul(a[0], b[1]),
  39. this.F.mul(a[1], b[0])),
  40. this.F.mul(a[1], b[1])];
  41. }
  42. neg(a) {
  43. return [this.F.neg(a[0]), a[1]];
  44. }
  45. mul(a,b) {
  46. return [
  47. this.F.mul(a[0], b[0]),
  48. this.F.mul(a[1], b[1]),
  49. ];
  50. }
  51. copy(a) {
  52. return [a[0], a[1]];
  53. }
  54. div(a, b) {
  55. return [
  56. this.F.mul(a[0], b[1]),
  57. this.F.mul(a[1], b[0]),
  58. ];
  59. }
  60. inverse(a) {
  61. return [a[1], a[0]];
  62. }
  63. square(a) {
  64. return [
  65. this.F.square(a[0]),
  66. this.F.square(a[1])
  67. ];
  68. }
  69. mulScalar(base, e) {
  70. return [this.F.mulScalar(base[0], e) , base[1]];
  71. }
  72. exp(base, e) {
  73. return fUtils.exp(this, base, e);
  74. }
  75. equals(a, b) {
  76. return this.F.equals(
  77. this.F.mul(a[0], b[1]),
  78. this.F.mul(a[1], b[0])
  79. );
  80. }
  81. isZero(a) {
  82. return this.F.isZero(a[0]);
  83. }
  84. affine(a) {
  85. return [this.F.div(a[0], a[1]), this.F.one];
  86. }
  87. toString(a) {
  88. const ca = this.affine(a);
  89. return `"0x${ca[0].toString(16)}"`;
  90. }
  91. random() {
  92. return [this.F.random(), this.F.one];
  93. }
  94. fromF(a) {
  95. return [a, this.F.one];
  96. }
  97. toF(a) {
  98. return this.affine(a)[0];
  99. }
  100. }
  101. module.exports = RatField;