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.

123 lines
2.3 KiB

  1. /*
  2. Source: https://en.wikipedia.org/wiki/Montgomery_curve
  3. 1 + y 1 + y
  4. [u, v] = [ ------- , ---------- ]
  5. 1 - y (1 - y)x
  6. */
  7. template Edwards2Montgomery() {
  8. signal input in[2];
  9. signal output out[2];
  10. out[0] <-- (1 + in[1]) / (1 - in[1]);
  11. out[1] <-- out[0] / in[0];
  12. out[0] * (1-in[1]) === (1 + in[1]);
  13. out[1] * in[0] === out[0];
  14. }
  15. /*
  16. u u - 1
  17. [x, y] = [ ---, ------- ]
  18. v u + 1
  19. */
  20. template Montgomery2Edwards() {
  21. signal input in[2];
  22. signal output out[2];
  23. out[0] <-- in[0] / in[1];
  24. out[1] <-- (in[0] - 1) / (in[0] + 1);
  25. out[0] * in[1] === in[0];
  26. out[1] * (in[0] + 1) === in[0] - 1;
  27. }
  28. /*
  29. x2 - x1
  30. lamda = ---------
  31. y2 - y1
  32. x3 + A + x1 + x2
  33. x3 = B * lamda^2 - A - x1 -x2 => lamda^2 = ------------------
  34. B
  35. y3 = (2*x1 + x2 + A)*lamda - B*lamda^3 - y1 =>
  36. => y3 = lamda * ( 2*x1 + x2 + A - x3 - A - x1 - x2) - y1 =>
  37. => y3 = lamda * ( x1 - x3 ) - y1
  38. ----------
  39. y2 - y1
  40. lamda = ---------
  41. x2 - x1
  42. x3 = B * lamda^2 - A - x1 -x2
  43. y3 = lamda * ( x1 - x3 ) - y1
  44. */
  45. template MontgomeryAdd() {
  46. signal input in1[2];
  47. signal input in2[2];
  48. signal output out[2];
  49. var a = 168700;
  50. var d = 168696;
  51. var A = (2 * (a + d)) / (a - d);
  52. var B = 4 / (a - d);
  53. signal lamda;
  54. lamda <-- (in2[1] - in1[1]) / (in2[0] - in1[0]);
  55. lamda * (in2[0] - in1[0]) === (in2[1] - in1[1]);
  56. out[0] <== B*lamda*lamda - A - in1[0] -in2[0];
  57. out[1] <== lamda * (in1[0] - out[0]) - in1[1];
  58. }
  59. /*
  60. x1_2 = x1*x1
  61. 3*x1_2 + 2*A*x1 + 1
  62. lamda = ---------------------
  63. 2*B*y1
  64. x3 = B * lamda^2 - A - x1 -x1
  65. y3 = lamda * ( x1 - x3 ) - y1
  66. */
  67. template MontgomeryDouble() {
  68. signal input in[2];
  69. signal output out[2];
  70. var a = 168700;
  71. var d = 168696;
  72. var A = (2 * (a + d)) / (a - d);
  73. var B = 4 / (a - d);
  74. signal lamda;
  75. signal x1_2;
  76. x1_2 <== in[0] * in[0];
  77. lamda <-- (3*x1_2 + 2*A*in[0] + 1 ) / (2*B*in[1]);
  78. lamda * (2*B*in[1]) === (3*x1_2 + 2*A*in[0] + 1 );
  79. out[0] <== B*lamda*lamda - A - 2*in[0];
  80. out[1] <== lamda * (in[0] - out[0]) - in[1];
  81. }