1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
#![allow(non_snake_case)] //! Edwards Point operations and their implementations are //! shown with the corresponding definitions. //! Encoding/decoding process implementations are shown, //! as is support for all kind of interactions which apply //! each of the processes. //! //! # Examples //! ```rust //! use zerocaf::edwards::*; //! use zerocaf::traits::ops::*; //! use zerocaf::traits::Identity; //! use zerocaf::field::FieldElement; //! use zerocaf::scalar::Scalar; //! //! use subtle::Choice; //! use core::ops::{Add, Sub, Mul}; //! //! use rand::rngs::OsRng; //! //! // You can work in different point coordinates, such as: //! // Affine, Projective or Extended. //! // //! // It's highly recommended to work using the Extended cooridnates, //! // for defined curves such as as the one in Zerocaf, //! // as they they allow for the fastest known arithmetic operations. //! // Additionally, they formats can be directly compressed from just //! // a singular coordinate. //! //! // In order to produce a point over the Sonny curve, //! // you can do the following: //! //! // From the y-coordinate of a point: //! let y = FieldElement([2369245568431362, 2665603790611352, 3317390952748653, 1908583331312524, 8011773354506]); //! // The `Choice` specifies the symbol that we want to get as a result //! // for the `x-coordinate`. //! let ex_point = EdwardsPoint::new_from_y_coord(&y, Choice::from(0u8)).unwrap(); //! //! //! let rngp = EdwardsPoint::from(ProjectivePoint::identity()); //! //! // The same examples work for the ProjectivePoint struct. //! //! // You can perform the following operations with an EdwardsPoint //! // or a ProjectivePoint: //! //! // Point addition: //! let p1 = &ex_point + &rngp; //! // Point subtraction (which is a point negation and a sum): //! let p2 = &ex_point - &rngp; //! // Point doubling: //! let p3 = &ex_point.double(); //! // Scalar mul: //! let p4 = double_and_add(&ex_point, &Scalar::from(8u8)); //! //! // You can also multiply by the cofactor directly: //! assert!(p4 == mul_by_cofactor(&ex_point)); //! //! // In order to send points for saving space, you can use //! // compressed points, whih are repressented as: `CompressedEwdardsY`. //! //! // The only means of obtaining a `CompressedEdwardsY` is: //! // By compressing an `EdwardsPoint`: //! let cp_point = rngp.compress(); //! // Note that you can get your EdwardsPoint back just by doing: //! let decompr_point = &cp_point.decompress().unwrap(); //! //! // You can also get a compressed point by copying it from a //! // slice of bytes (as if it came from a socket or similar situations). //! let cpedw = CompressedEdwardsY::from_slice(&cp_point.to_bytes()); //! ``` use crate::constants; use crate::field::FieldElement; use crate::montgomery::MontgomeryPoint; use crate::scalar::Scalar; use crate::traits::{ops::*, Identity, ValidityCheck}; use crate::ristretto::RistrettoPoint; use rand::{CryptoRng, Rng}; use subtle::{Choice, ConstantTimeEq}; use std::default::Default; use std::fmt::Debug; use core::ops::{Index, IndexMut}; use std::ops::{Add, Mul, Neg, Sub}; // ------------- Common Point fn declarations ------------- // /// Implementation of the standard algorithm of `double_and_add`. /// This is a function implemented for Generic points that have /// implemented `Add`, `Double`, `Identity` and `Clone`. /// /// Hankerson, Darrel; Vanstone, Scott; Menezes, Alfred (2004). /// Guide to Elliptic Curve Cryptography. /// Springer Professional Computing. New York: Springer-Verlag. /// /// We implement this and not `windowing algorithms` because we /// prioritize less constraints on R1CS over the computational /// costs of the algorithm. pub fn double_and_add<'b, 'a, T>(point: &'a T, scalar: &'b Scalar) -> T where for<'c> &'c T: Add<Output = T> + Double<Output = T>, T: Identity + Clone, { let mut N = point.clone(); let mut n = *scalar; let mut Q = T::identity(); while n != Scalar::zero() { if !n.is_even() { Q = &Q + &N; }; N = N.double(); n = n.half_without_mod(); } Q } pub fn ltr_bin_mul<'a, 'b, T>(point: &'a T, scalar: &'b Scalar) -> T where for<'c> &'c T: Add<Output = T> + Double<Output = T>, T: Identity, { let scalar_bits = scalar.into_bits(); let mut Q = T::identity(); for i in (0..249).rev() { Q = Q.double(); if scalar_bits[i] == 1u8 {Q = &Q + &point;}; } Q } pub fn binary_naf_mul<'a, 'b, T>(point: &'a T, scalar: &'b Scalar) -> T where for <'c> &'c T: Add<Output = T> + Double<Output = T> + Sub<Output = T>, T: Identity, { let mut Q = T::identity(); let k_naf = scalar.compute_NAF(); for i in (0..250).rev() { Q = Q.double(); match k_naf[i] as i16 { 1i16 => Q = &Q + point, -1_i16 => Q = &Q - point, _ => (), }; } Q } pub fn window_naf_mul(scalar: &Scalar, window_width: u8) -> RistrettoPoint { let mut Q = RistrettoPoint::identity(); let scalar_wnaf = scalar.compute_window_NAF(window_width); for i in (0..250).rev() { Q = Q.double(); let ki = scalar_wnaf[i]; match (ki == 0i8, ki > 0i8) { (true, _) => (), (false, true) => Q = &Q + &constants::BASEPOINT_ODD_MULTIPLES_TABLE[ki as usize], (false, false) => Q = &Q - &constants::BASEPOINT_ODD_MULTIPLES_TABLE[ki.abs() as usize], } }; Q } /// Multiply by the cofactor: return (8 P). pub fn mul_by_cofactor<'a, T>(point: &'a T) -> T where for<'c> &'c T: Mul<&'c Scalar, Output = T>, { point * &Scalar::from(8u8) } /// Compute ([2^k] * P (mod l)). /// /// Note: The maximum pow allowed is 249 since otherways /// we will be able to get results greater than the /// prime of the sub-group. pub fn mul_by_pow_2<'a, T>(point: &'a T, _k: u64) -> T where for<'c> &'c T: Mul<&'c Scalar, Output = T>, { point * &Scalar::two_pow_k(_k) } /// Gets the value of a `y-coordinate` and finds the /// correspponding `x^2` by solving the next equation: /// `xx = (y^2 -1) / (d*y^2 -a)`. /// /// Note that this is an auxiliary function and shouldn't /// be used for anything else than the purposes mentioned /// avobe. pub(self) fn find_xx(y: &FieldElement) -> FieldElement { let a = y.square() - FieldElement::one(); let b = (constants::EDWARDS_D * y.square()) - constants::EDWARDS_A; a / b } // ---------------- Point Structs ---------------- // /// The first 255 bits of a `CompressedEdwardsY` represent the /// (y)-coordinate. The high bit of the 32nd byte gives the sign of (x). #[derive(Copy, Clone)] pub struct CompressedEdwardsY(pub [u8; 32]); impl ConstantTimeEq for CompressedEdwardsY { fn ct_eq(&self, other: &CompressedEdwardsY) -> Choice { self.to_bytes().ct_eq(&other.to_bytes()) } } impl PartialEq for CompressedEdwardsY { fn eq(&self, other: &CompressedEdwardsY) -> bool { self.ct_eq(&other).unwrap_u8() == 1u8 } } impl Eq for CompressedEdwardsY {} impl Index<usize> for CompressedEdwardsY { type Output = u8; fn index(&self, _index: usize) -> &u8 { &(self.0[_index]) } } impl IndexMut<usize> for CompressedEdwardsY { fn index_mut(&mut self, _index: usize) -> &mut u8 { &mut (self.0[_index]) } } impl Debug for CompressedEdwardsY { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "CompressedEdwardsY: {:?}", self.to_bytes()) } } impl Default for CompressedEdwardsY { /// Returns the identity for `CompressedEdwardsY` point. fn default() -> CompressedEdwardsY { CompressedEdwardsY::identity() } } impl<'a> Neg for &'a CompressedEdwardsY { type Output = CompressedEdwardsY; /// Negates an `CompressedEdwardsY` by decompressing /// it, negating over Twisted Edwards Extended /// Projective Coordinates and compressing it back. fn neg(self) -> CompressedEdwardsY { (-&self.decompress().unwrap()).compress() } } impl Neg for CompressedEdwardsY { type Output = CompressedEdwardsY; /// Negates an `CompressedEdwardsY` by decompressing /// it, negating over Twisted Edwards Extended /// Projective Coordinates and compressing it back. fn neg(self) -> CompressedEdwardsY { -&self } } impl Identity for CompressedEdwardsY { /// Returns the `CompressedEdwardsY` identity point value /// that corresponds to `1 (mod l)` /// with the x-sign bit setted to `0`. fn identity() -> CompressedEdwardsY { CompressedEdwardsY([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]) } } impl CompressedEdwardsY { /// Construct a `CompressedEdwardsY` from a slice of bytes. /// /// # Note: /// This function should only be used to get a /// `CompressedEdwardsY` compressed point from /// a [u8; 32] that we know that is already a /// compressed point. /// /// If this function is used with Y-coordinates /// randomly might give errors. pub fn from_slice(bytes: &[u8]) -> CompressedEdwardsY { let mut tmp = [0u8; 32]; tmp.copy_from_slice(bytes); CompressedEdwardsY(tmp) } /// Return the `CompressedEdwardsY` as an array of bytes (it's cannonical state). pub fn to_bytes(&self) -> [u8; 32] { self.0 } /// Attempt to decompress to an `EdwardsPoint`. /// /// Returns `None` if the input is not the Y-coordinate of a /// curve point. pub fn decompress(&self) -> Option<EdwardsPoint> { // Get the sign of the x-coordinate. let sign = Choice::from(self[31] >> 7 as u8); // Get the Y-coordinate without the high bit modified. // The max value that the 31st byte can hold is 16(1111), // so we truncate it since we already have the sign. let mut y = *self; y[31] &= 0b0000_1111; // Try to get the x coordinate (if exists). // Otherways, return `None`. EdwardsPoint::new_from_y_coord(&FieldElement::from_bytes(&y.to_bytes()), sign) } } /// An `EdwardsPoint` represents a point on the Sonny Curve which is expressed /// in the Twisted Edwards Extended Coordinates format, eg. (X, Y, Z, T). /// /// Extended coordinates represent X & Y as`(X Y Z T)` satisfying the following equations: /// X=X/Z /// Y=Y/Z /// X*Y=T/Z #[derive(Copy, Clone)] pub struct EdwardsPoint { pub X: FieldElement, pub Y: FieldElement, pub Z: FieldElement, pub T: FieldElement, } impl Debug for EdwardsPoint { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!( f, " EdwardsPoint {{ X: {:?}, Y: {:?}, Z: {:?}, T: {:?} }};", self.X, self.Y, self.Z, self.T ) } } impl ConstantTimeEq for EdwardsPoint { fn ct_eq(&self, other: &EdwardsPoint) -> Choice { AffinePoint::from(*self).ct_eq(&AffinePoint::from(*other)) } } impl PartialEq for EdwardsPoint { fn eq(&self, other: &EdwardsPoint) -> bool { self.ct_eq(other).unwrap_u8() == 1u8 } } impl Eq for EdwardsPoint {} impl Default for EdwardsPoint { /// Returns the default EdwardsPoint Extended Coordinates: (0, 1, 1, 0). fn default() -> EdwardsPoint { EdwardsPoint::identity() } } impl Identity for EdwardsPoint { /// Returns the Edwards Point identity value = `(0, 1, 1, 0)`. fn identity() -> EdwardsPoint { EdwardsPoint { X: FieldElement::zero(), Y: FieldElement::one(), Z: FieldElement::one(), T: FieldElement::zero(), } } } impl ValidityCheck for EdwardsPoint { /// Verifies if the curve equation (in projective twisted /// edwards coordinates) holds given the (X, Y, Z) coordinates /// of a point in Projective Coordinates. fn is_valid(&self) -> Choice { ProjectivePoint::from(*self).is_valid() } } impl From<ProjectivePoint> for EdwardsPoint { /// Given (X:Y:Z) in ε passing to εε can beperformed /// in 3M+ 1S by computing (X*Z, Y*Z, X*Y, Z^2). /// /// Twisted Edwards Curves Revisited - /// Huseyin Hisil, Kenneth Koon-Ho Wong, Gary Carter, /// and Ed Dawson, Section 3. fn from(point: ProjectivePoint) -> EdwardsPoint { EdwardsPoint { X: point.X * point.Z, Y: point.Y * point.Z, Z: point.Z.square(), T: point.X * point.Y, } } } impl From<AffinePoint> for EdwardsPoint { /// In affine form, each elliptic curve point has 2 coordinates, /// like (x,y). In the new projective form, /// each point will have 3 coordinates, like (X,Y,Z), /// with the restriction that Z is never zero. /// /// The forward mapping is given by (X,Y)→(XZ,YZ,Z), /// for any non-zero z (usually chosen to be 1 for convenience). /// /// After this is done, we move from Projective to Extended by /// setting the new coordinate `T = X * Y`. fn from(point: AffinePoint) -> EdwardsPoint { EdwardsPoint { X: point.X, Y: point.Y, Z: FieldElement::one(), T: point.X * point.Y, } } } impl<'a> Neg for &'a EdwardsPoint { type Output = EdwardsPoint; /// Negates an `EdwardsPoint` giving it's negated value /// as a result. /// /// Since the negative of a point is (-X:Y:Z:-T), it /// gives as a result: `(-X:Y:Z:-T)`. fn neg(self) -> EdwardsPoint { EdwardsPoint { X: -&self.X, Y: self.Y, Z: self.Z, T: -&self.T, } } } impl Neg for EdwardsPoint { type Output = EdwardsPoint; /// Negates an `EdwardsPoint` giving it as a result fn neg(self) -> EdwardsPoint { -&self } } impl<'a, 'b> Add<&'b EdwardsPoint> for &'a EdwardsPoint { type Output = EdwardsPoint; /// Add two EdwardsPoints and give the resulting `EdwardsPoint`. /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// [Source: 2008 Hisil–Wong–Carter–Dawson], /// (http://eprint.iacr.org/2008/522), Section 3.1. fn add(self, other: &'b EdwardsPoint) -> EdwardsPoint { let A = self.X * other.X; let B = self.Y * other.Y; let C = constants::EDWARDS_D * self.T * other.T; let D = self.Z * other.Z; let E = (self.X + self.Y) * (other.X + other.Y) - A - B; let F = D - C; let G = D + C; let H = B + A; EdwardsPoint { X: E * F, Y: G * H, Z: F * G, T: E * H, } } } impl Add<EdwardsPoint> for EdwardsPoint { type Output = EdwardsPoint; /// Add two EdwardsPoints and give the resulting `EdwardsPoint`. /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// [Source: 2008 Hisil–Wong–Carter–Dawson], /// (http://eprint.iacr.org/2008/522), Section 3.1. fn add(self, other: EdwardsPoint) -> EdwardsPoint { &self + &other } } impl<'a, 'b> Sub<&'b EdwardsPoint> for &'a EdwardsPoint { type Output = EdwardsPoint; /// Substract two EdwardsPoints and give the resulting `EdwardsPoint` /// This implementation is specific for curves with `a = -1` as Sonny is. /// Source: 2008 Hisil–Wong–Carter–Dawson, /// http://eprint.iacr.org/2008/522, Section 3.1. /// /// The only thing we do is negate the second `EdwardsPoint` /// and add it following the same addition algorithm. fn sub(self, other: &'b EdwardsPoint) -> EdwardsPoint { let other_neg = -other; let A = self.X * other_neg.X; let B = self.Y * other_neg.Y; let C = constants::EDWARDS_D * self.T * other_neg.T; let D = self.Z * other_neg.Z; let E = (self.X + self.Y) * (other_neg.X + other_neg.Y) - A - B; let F = D - C; let G = D + C; let H = B - (constants::EDWARDS_A * A); EdwardsPoint { X: E * F, Y: G * H, Z: F * G, T: E * H, } } } impl Sub<EdwardsPoint> for EdwardsPoint { type Output = EdwardsPoint; /// Substract two EdwardsPoints and give the resulting `EdwardsPoint` /// This implementation is specific for curves with `a = -1` as Sonny is. /// Source: 2008 Hisil–Wong–Carter–Dawson, /// http://eprint.iacr.org/2008/522, Section 3.1. /// /// The only thing we do is negate the second `EdwardsPoint` /// and add it following the same addition algorithm. fn sub(self, other: EdwardsPoint) -> EdwardsPoint { &self - &other } } impl<'a, 'b> Mul<&'b Scalar> for &'a EdwardsPoint { type Output = EdwardsPoint; /// Scalar multiplication: compute `self * Scalar`. /// This implementation uses the algorithm: /// `add_and_doubling` which is the standard one for /// this operations and also adds less constraints on /// R1CS. /// /// Hankerson, Darrel; Vanstone, Scott; Menezes, Alfred (2004). /// Guide to Elliptic Curve Cryptography. /// Springer Professional Computing. New York: Springer-Verlag. fn mul(self, scalar: &'b Scalar) -> EdwardsPoint { double_and_add(self, scalar) } } impl Mul<Scalar> for EdwardsPoint { type Output = EdwardsPoint; /// Scalar multiplication: compute `Scalar * self`. /// This implementation uses the algorithm: /// `add_and_doubling` which is the standard one for /// this operations and also adds less constraints on /// R1CS. /// /// Hankerson, Darrel; Vanstone, Scott; Menezes, Alfred (2004). /// Guide to Elliptic Curve Cryptography. /// Springer Professional Computing. New York: Springer-Verlag. fn mul(self, scalar: Scalar) -> EdwardsPoint { double_and_add(&self, &scalar) } } impl<'a> Double for &'a EdwardsPoint { type Output = EdwardsPoint; /// Performs the point doubling operation /// ie. `2*P` over the Twisted Edwards Extended /// Coordinates. /// /// This implementation is specific for curves with `a = -1` as Sonny is. /// Source: 2008 Hisil–Wong–Carter–Dawson, /// http://eprint.iacr.org/2008/522, Section 3.1. /// Cost: 4M+ 4S+ 1D fn double(self) -> EdwardsPoint { self + self } } impl EdwardsPoint { /// Convert this `EdwardsPoint` on the Edwards model to the /// corresponding `MontgomeryPoint` on the Montgomery model. pub fn to_montgomery(&self) -> MontgomeryPoint { unimplemented!() } /// Prints the 4Coset where the input `EdwardsPoint` /// lives in. pub fn coset4(&self) -> [EdwardsPoint; 4] { [ *self, self + &constants::FOUR_COSET_GROUP[0], self + &constants::FOUR_COSET_GROUP[1], self + &constants::FOUR_COSET_GROUP[2], ] } /// Compress this point to `CompressedEdwardsY` format. pub fn compress(&self) -> CompressedEdwardsY { // Get the Affine point coordinates and compress // the point using them. let point = AffinePoint::from(*self); let mut sign = Choice::from(0u8); let res = find_xx(&point.Y).mod_sqrt(sign).unwrap(); if res != point.X { sign = Choice::from(1u8); }; let mut compr = point.Y.to_bytes(); // Set the highest bit of the last byte as the symbol. compr[31] |= sign.unwrap_u8() << 7; CompressedEdwardsY::from_slice(&compr) } /// This function tries to build a Point over the Sonny Curve from /// a `Y` coordinate and a Choice that determines the sign of the `X` /// coordinate that the user wants to use. /// /// The function gets `X` by solving: /// `+-X = mod_sqrt((y^2 -1)/(dy^2 - a))`. /// /// The sign of `x` is choosen with a `Choice` parameter. /// /// For Choice(0) -> Negative result. /// For Choice(1) -> Positive result. /// /// Then Z is always equal to `1`. /// /// # Returns /// - `Some(EdwardsPoint)` if there exists a result for the `mod_sqrt`. /// - `None` if the resulting `x^2` isn't a QR modulo `FIELD_L`. pub fn new_from_y_coord(y: &FieldElement, sign: Choice) -> Option<EdwardsPoint> { match ProjectivePoint::new_from_y_coord(&y, sign) { None => None, Some(point) => Some(EdwardsPoint::from(point)), } } /// This function tries to build a Point over the Sonny Curve from /// a random `Y` coordinate and a random Choice that determines the /// sign of the `X` coordinate. pub fn new_random_point<T: Rng + CryptoRng>(rand: &mut T) -> EdwardsPoint { // Simply generate a random `ProjectivePoint` // and once we get one that is valid, switch // it to Extended Coordinates. EdwardsPoint::from(ProjectivePoint::new_random_point(rand)) } } /// A `ProjectivePoint` represents a point on the Sonny Curve expressed /// over the Twisted Edwards Projective Coordinates eg. (X:Y:Z). /// /// For Z1≠0 the point (X1:Y1:Z1) represents the affine point (x1= X1/Z1, y1= Y1/Z1) /// on EE,a,d. /// Projective coordinates represent `x` `y` as `(X, Y, Z`) satisfying the following equations: /// /// x=X/Z /// /// y=Y/Z /// /// Expressing an elliptic curve in twisted Edwards form saves time in arithmetic, /// even when the same curve can be expressed in the Edwards form. #[derive(Copy, Clone)] pub struct ProjectivePoint { pub X: FieldElement, pub Y: FieldElement, pub Z: FieldElement, } impl Debug for ProjectivePoint { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!( f, " ProjectivePoint {{ X: {:?}, Y: {:?}, Z: {:?} }};", self.X, self.Y, self.Z ) } } impl ConstantTimeEq for ProjectivePoint { fn ct_eq(&self, other: &ProjectivePoint) -> Choice { AffinePoint::from(*self).ct_eq(&AffinePoint::from(*other)) } } impl PartialEq for ProjectivePoint { fn eq(&self, other: &ProjectivePoint) -> bool { self.ct_eq(other).unwrap_u8() == 1u8 } } impl Eq for ProjectivePoint {} impl Default for ProjectivePoint { /// Returns the default ProjectivePoint Extended Coordinates: (0, 1, 1). fn default() -> ProjectivePoint { ProjectivePoint::identity() } } impl Identity for ProjectivePoint { /// Returns the Edwards Point identity value = `(0, 1, 1)`. fn identity() -> ProjectivePoint { ProjectivePoint { X: FieldElement::zero(), Y: FieldElement::one(), Z: FieldElement::one(), } } } impl ValidityCheck for ProjectivePoint { /// Verifies if the curve equation (in projective twisted /// edwards coordinates) holds given the (X, Y, Z) coordinates /// of a point in Projective Coordinates. fn is_valid(&self) -> Choice { // Use `(aX^{2}+Y^{2})Z^{2}=Z^{4}+dX^{2}Y^{2}` let x_sq = self.X.square(); let y_sq = self.Y.square(); let z_sq = self.Z.square(); let left = ((constants::EDWARDS_A * x_sq) + y_sq) * z_sq; let right = z_sq.square() + (constants::EDWARDS_D * x_sq * y_sq); left.ct_eq(&right) } } impl From<EdwardsPoint> for ProjectivePoint { /// Given (X:Y:T:Z) in εε, passing to ε is cost-free by /// simply ignoring `T`. /// /// Twisted Edwards Curves Revisited - /// Huseyin Hisil, Kenneth Koon-Ho Wong, Gary Carter, /// and Ed Dawson, Section 3. fn from(point: EdwardsPoint) -> ProjectivePoint { ProjectivePoint { X: point.X, Y: point.Y, Z: point.Z, } } } impl From<AffinePoint> for ProjectivePoint { /// The key idea of projective coordinates is that instead of /// performing every division immediately, we defer the /// divisions by multiplying them into a denominator. /// /// In affine form, each elliptic curve point has 2 coordinates, /// like (x,y). In the new projective form, /// each point will have 3 coordinates, like (X,Y,Z), /// with the restriction that Z is never zero. /// /// The forward mapping is given by (x,y)→(xz,yz,z), /// for any non-zero z (usually chosen to be 1 for convenience). fn from(point: AffinePoint) -> ProjectivePoint { ProjectivePoint { X: point.X, Y: point.Y, Z: FieldElement::one(), } } } impl<'a> Neg for &'a ProjectivePoint { type Output = ProjectivePoint; /// Negates an `ProjectivePoint` giving it as a result. /// Since the negative of a point is (-X:Y:Z:-T), it /// gives as a result: `(-X, Y, Z, -T)`. fn neg(self) -> ProjectivePoint { ProjectivePoint { X: -&self.X, Y: self.Y, Z: self.Z, } } } impl Neg for ProjectivePoint { type Output = ProjectivePoint; /// Negates an `ProjectivePoint` giving it as a result fn neg(self) -> ProjectivePoint { -&self } } impl<'a, 'b> Add<&'b ProjectivePoint> for &'a ProjectivePoint { type Output = ProjectivePoint; /// Add two ProjectivePoints and give the resulting `ProjectivePoint`. /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// Bernstein D.J., Birkner P., Joye M., Lange T., Peters C. /// (2008) Twisted Edwards Curves. In: Vaudenay S. (eds) /// Progress in Cryptology – AFRICACRYPT 2008. AFRICACRYPT 2008. /// Lecture Notes in Computer Science, vol 5023. Springer, Berlin, Heidelberg. /// See: https://eprint.iacr.org/2008/013.pdf - Section 6. fn add(self, other: &'b ProjectivePoint) -> ProjectivePoint { let A = self.Z * other.Z; let B = A.square(); let C = self.X * other.X; let D = self.Y * other.Y; let E = constants::EDWARDS_D * C * D; let F = B - E; let G = B + E; ProjectivePoint { X: A * (F * (((self.X + self.Y) * (other.X + other.Y) - C) - D)), Y: A * G * (D + C), Z: F * G, } } } impl Add<ProjectivePoint> for ProjectivePoint { type Output = ProjectivePoint; /// Add two ProjectivePoints and give the resulting `ProjectivePoint`. /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// Bernstein D.J., Birkner P., Joye M., Lange T., Peters C. /// (2008) Twisted Edwards Curves. In: Vaudenay S. (eds) /// Progress in Cryptology – AFRICACRYPT 2008. AFRICACRYPT 2008. /// Lecture Notes in Computer Science, vol 5023. Springer, Berlin, Heidelberg. /// See: https://eprint.iacr.org/2008/013.pdf - Section 6. fn add(self, other: ProjectivePoint) -> ProjectivePoint { &self + &other } } impl<'a, 'b> Sub<&'b ProjectivePoint> for &'a ProjectivePoint { type Output = ProjectivePoint; /// Add two ProjectivePoints, negating the second one, /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// Bernstein D.J., Birkner P., Joye M., Lange T., Peters C. /// (2008) Twisted Edwards Curves. In: Vaudenay S. (eds) /// Progress in Cryptology – AFRICACRYPT 2008. AFRICACRYPT 2008. /// Lecture Notes in Computer Science, vol 5023. Springer, Berlin, Heidelberg. /// See: https://eprint.iacr.org/2008/013.pdf - Section 6. fn sub(self, other: &'b ProjectivePoint) -> ProjectivePoint { self + &(-other) } } impl Sub<ProjectivePoint> for ProjectivePoint { type Output = ProjectivePoint; /// Add two ProjectivePoints, negating the second one, /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// Bernstein D.J., Birkner P., Joye M., Lange T., Peters C. /// (2008) Twisted Edwards Curves. In: Vaudenay S. (eds) /// Progress in Cryptology – AFRICACRYPT 2008. AFRICACRYPT 2008. /// Lecture Notes in Computer Science, vol 5023. Springer, Berlin, Heidelberg. /// See: https://eprint.iacr.org/2008/013.pdf - Section 6. fn sub(self, other: ProjectivePoint) -> ProjectivePoint { &self - &other } } impl<'a, 'b> Mul<&'a Scalar> for &'b ProjectivePoint { type Output = ProjectivePoint; /// Scalar multiplication: compute `Scalar * self`. /// This implementation uses the algorithm: /// `add_and_doubling` which is the standard one for /// this operations and also adds less constraints on /// R1CS. /// /// Hankerson, Darrel; Vanstone, Scott; Menezes, Alfred (2004). /// Guide to Elliptic Curve Cryptography. /// Springer Professional Computing. New York: Springer-Verlag. fn mul(self, scalar: &'a Scalar) -> ProjectivePoint { double_and_add(self, scalar) } } impl Mul<Scalar> for ProjectivePoint { type Output = ProjectivePoint; /// Scalar multiplication: compute `Scalar * self`. /// This implementation uses the algorithm: /// `add_and_doubling` which is the standard one for /// this operations and also adds less constraints on /// R1CS. /// /// Hankerson, Darrel; Vanstone, Scott; Menezes, Alfred (2004). /// Guide to Elliptic Curve Cryptography. /// Springer Professional Computing. New York: Springer-Verlag. fn mul(self, scalar: Scalar) -> ProjectivePoint { &self * &scalar } } impl<'a> Double for &'a ProjectivePoint { type Output = ProjectivePoint; /// Double the given point following: /// This implementation is specific for curves with `a = -1` as Sonny is. /// /// /// Bernstein D.J., Birkner P., Joye M., Lange T., Peters C. /// (2008) Twisted Edwards Curves. In: Vaudenay S. (eds) /// Progress in Cryptology – AFRICACRYPT 2008. AFRICACRYPT 2008. /// Lecture Notes in Computer Science, vol 5023. Springer, Berlin, Heidelberg. /// See: https://eprint.iacr.org/2008/013.pdf - Section 6. /// /// Cost: 3M+ 4S+ +7a + 1D. fn double(self) -> ProjectivePoint { let B = (self.X + self.Y).square(); let C = self.X.square(); let D = self.Y.square(); let E = constants::EDWARDS_A * C; let F = E + D; let H = self.Z.square(); let J = F - (FieldElement::from(2u8) * H); ProjectivePoint { X: ((B - C) - D) * J, Y: F * (E - D), Z: F * J, } } } impl ProjectivePoint { /// This function tries to build a Point over the Sonny Curve from /// a `Y` coordinate and a Choice that determines the sign of the `X` /// coordinate that the user wants to use. /// /// The function gets `X` by solving: /// `+-X = mod_sqrt((y^2 -1)/(dy^2 - a))`. /// /// The sign of `x` is choosen with a `Choice` parameter. /// /// For Choice(0) -> Negative result. /// For Choice(1) -> Positive result. /// /// Then Z is always equal to `1`. /// /// # Returns /// `Some(ProjectivePoint)` if there exists a result for the `mod_sqrt` /// and `None` if the resulting `x^2` isn't a QR modulo `FIELD_L`. pub fn new_from_y_coord(y: &FieldElement, sign: Choice) -> Option<ProjectivePoint> { let one = FieldElement::one(); let x: FieldElement; let xx = (y.square() - one) / ((constants::EDWARDS_D * y.square()) - constants::EDWARDS_A); // Match the sqrt(x) Option. match xx.mod_sqrt(sign) { // If we get `None`, we know that None => return None, Some(_x) => x = _x, }; Some(ProjectivePoint { X: x, Y: *y, Z: one, }) } /// This function tries to build a Point over the Sonny Curve from /// a random `Y` coordinate and a random Choice that determines the /// sign of the `X` coordinate. pub fn new_random_point<T: Rng + CryptoRng>(rand: &mut T) -> ProjectivePoint { // Gen a random `Y` coordinate value from an user-provided // randomness source. let y = FieldElement::random(rand); // Gen a random sign choice. let sign = Choice::from(rand.gen_range(0u8, 1u8)); // Until we don't get a valid `Y` value, call the // function recursively. match ProjectivePoint::new_from_y_coord(&y, sign) { None => ProjectivePoint::new_random_point(rand), Some(point) => point, } } } /// An `AffinePoint` represents a point on the Sonny Curve expressed /// over the Twisted Edwards Affine Coordinates also known as /// cartesian coordinates: (X, Y). /// /// This Twisted Edwards coordinates are ONLY implemented for /// equalty testing, since all of the Point operations /// defined over them are much slower than the same ones /// defined over Extended or Projective coordinates. pub struct AffinePoint { pub X: FieldElement, pub Y: FieldElement, } impl Debug for AffinePoint { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!( f, " AffinePoint {{ X: {:?}, Y: {:?} }};", self.X, self.Y ) } } impl Default for AffinePoint { /// Returns the default Twisted Edwards AffinePoint Coordinates: (0, 1). fn default() -> AffinePoint { AffinePoint::identity() } } impl Identity for AffinePoint { /// Returns the Edwards Point identity value = `(0, 1)`. fn identity() -> AffinePoint { AffinePoint { X: FieldElement::zero(), Y: FieldElement::one(), } } } impl ConstantTimeEq for AffinePoint { fn ct_eq(&self, other: &Self) -> Choice { self.X.ct_eq(&other.X) & self.Y.ct_eq(&other.Y) } } impl PartialEq for AffinePoint { fn eq(&self, other: &Self) -> bool { self.ct_eq(&other).unwrap_u8() == 1u8 } } impl Eq for AffinePoint {} impl ValidityCheck for AffinePoint { /// Verifies if the curve equation holds given the /// (X, Y) coordinates of a point in Affine Coordinates. fn is_valid(&self) -> Choice { let x_sq = self.X.square(); let y_sq = self.Y.square(); let left = (FieldElement::minus_one() * x_sq) + y_sq; let right = FieldElement::one() + ((constants::EDWARDS_D * x_sq) * y_sq); left.ct_eq(&right) } } impl From<EdwardsPoint> for AffinePoint { /// Given (X:Y:Z:T) in εε, passing to affine can be /// performed in 3M+ 1I by computing: /// /// First, move to Projective Coordinates by removing `T`. /// /// Then, reduce the point from Projective to Affine /// coordinates computing: (X*Zinv, Y*Zinv, Z*Zinv). /// /// And once Z coord = `1` we can simply remove it. /// /// Twisted Edwards Curves Revisited - /// Huseyin Hisil, Kenneth Koon-Ho Wong, Gary Carter, /// and Ed Dawson. fn from(point: EdwardsPoint) -> AffinePoint { let Zinv = point.Z.inverse(); AffinePoint { X: point.X * Zinv, Y: point.Y * Zinv, } } } impl From<ProjectivePoint> for AffinePoint { /// Reduce the point from Projective to Affine /// coordinates computing: (X*Zinv, Y*Zinv, Z*Zinv). /// /// And once the Z coord = `1` we can simply remove it. /// /// Twisted Edwards Curves Revisited - /// Huseyin Hisil, Kenneth Koon-Ho Wong, Gary Carter, /// and Ed Dawson. fn from(point: ProjectivePoint) -> AffinePoint { let Zinv = point.Z.inverse(); AffinePoint { X: point.X * Zinv, Y: point.Y * Zinv, } } } impl<'a> Neg for &'a AffinePoint { type Output = AffinePoint; /// Negates an `AffinePoint` giving it as a result. /// Since the negative of a point is (-X:Y), it /// gives as a result: `(-X, Y)`. fn neg(self) -> AffinePoint { AffinePoint { X: -&self.X, Y: self.Y, } } } impl Neg for AffinePoint { type Output = AffinePoint; /// Negates an `AffinePoint` giving it as a result. /// Since the negative of a point is (-X:Y), it /// gives as a result: `(-X, Y)`. fn neg(self) -> AffinePoint { -&self } } #[allow(dead_code)] #[cfg(test)] /// Module used for tesing `EdwardsPoint` operations and implementations. /// Also used to check the correctness of the transformation functions. pub mod tests { use super::*; #[cfg(feature = "rand")] use rand::rngs::OsRng; pub(self) const P1_AFFINE: AffinePoint = AffinePoint { X: FieldElement([13, 0, 0, 0, 0]), Y: FieldElement([ 606320128494542, 1597163540666577, 1835599237877421, 1667478411389512, 3232679738299, ]), }; pub(self) const P2_AFFINE: AffinePoint = AffinePoint { X: FieldElement([67, 0, 0, 0, 0]), Y: FieldElement([ 2369245568431362, 2665603790611352, 3317390952748653, 1908583331312524, 8011773354506, ]), }; pub(self) const P1_EXTENDED: EdwardsPoint = EdwardsPoint { X: FieldElement([13, 0, 0, 0, 0]), Y: FieldElement([ 606320128494542, 1597163540666577, 1835599237877421, 1667478411389512, 3232679738299, ]), Z: FieldElement([1, 0, 0, 0, 0]), T: FieldElement([ 2034732376387996, 3922598123714460, 1344791952818393, 3662820838581677, 6840464509059, ]), }; pub(self) const P2_EXTENDED: EdwardsPoint = EdwardsPoint { X: FieldElement([67, 0, 0, 0, 0]), Y: FieldElement([ 2369245568431362, 2665603790611352, 3317390952748653, 1908583331312524, 8011773354506, ]), Z: FieldElement([1, 0, 0, 0, 0]), T: FieldElement([ 3474019263728064, 2548729061993416, 1588812051971430, 1774293631565269, 9023233419450, ]), }; /// `P4_EXTENDED = P1_EXTENDED + P2_EXTENDED` over Twisted Edwards Extended Coordinates. pub(self) const P4_EXTENDED: EdwardsPoint = EdwardsPoint { X: FieldElement([ 28731243678497, 3605893500953713, 4417389530006141, 299092414682919, 4656166963268, ]), Y: FieldElement([ 1108585916087857, 594338741746768, 1302451816332899, 2952667069736952, 9685400790709, ]), Z: FieldElement([ 3678126740275983, 2102367182843193, 1215780564383894, 577880234309233, 3967832577760, ]), T: FieldElement([ 1187490310723625, 475595246262913, 1092363334429875, 285623496107549, 15708045001361, ]), }; /// `P3_EXTENDED = 2P1_EXTENDED` over Twisted Edwards Extended Coordinates. pub(self) const P3_EXTENDED: EdwardsPoint = EdwardsPoint { X: FieldElement([ 1476979596852032, 1246004597497903, 209071396735379, 2301211094775178, 8305779568088, ]), Y: FieldElement([ 2443441861872082, 2091934391169607, 4475713698486302, 2663476425643860, 11068724258563, ]), Z: FieldElement([ 3359568035147073, 1010422717320416, 4098443973666364, 1207164847672527, 9657319892454, ]), T: FieldElement([ 4430735055822517, 4109982164990701, 4066725032805467, 1974812232939042, 2107656041478, ]), }; pub(self) const P1_PROJECTIVE: ProjectivePoint = ProjectivePoint { X: FieldElement([13, 0, 0, 0, 0]), Y: FieldElement([ 606320128494542, 1597163540666577, 1835599237877421, 1667478411389512, 3232679738299, ]), Z: FieldElement([1, 0, 0, 0, 0]), }; pub(self) const P2_PROJECTIVE: ProjectivePoint = ProjectivePoint { X: FieldElement([67, 0, 0, 0, 0]), Y: FieldElement([ 2369245568431362, 2665603790611352, 3317390952748653, 1908583331312524, 8011773354506, ]), Z: FieldElement([1, 0, 0, 0, 0]), }; /// `P4_PROJECTIVE = P1_PROJECTIVE + P2_PROJECTIVE` over Twisted Edwards Projective Coordinates. pub(self) const P4_PROJECTIVE: ProjectivePoint = ProjectivePoint { X: FieldElement([ 28731243678497, 3605893500953713, 4417389530006141, 299092414682919, 4656166963268, ]), Y: FieldElement([ 1108585916087857, 594338741746768, 1302451816332899, 2952667069736952, 9685400790709, ]), Z: FieldElement([ 3678126740275983, 2102367182843193, 1215780564383894, 577880234309233, 3967832577760, ]), }; /// `P3_PROJECTIVE = 2P1_PROJECTIVE` over Twisted Edwards Projective Coordinates. pub(self) const P3_PROJECTIVE: ProjectivePoint = ProjectivePoint { X: FieldElement([ 1476979596852032, 1246004597497903, 209071396735379, 2301211094775178, 8305779568088, ]), Y: FieldElement([ 2443441861872082, 2091934391169607, 4475713698486302, 2663476425643860, 11068724258563, ]), Z: FieldElement([ 3359568035147073, 1010422717320416, 4098443973666364, 1207164847672527, 9657319892454, ]), }; /// `P1_EXTENDED on `CompressedEdwardsY` format. pub(self) const P1_COMPRESSED: CompressedEdwardsY = CompressedEdwardsY([ 206, 11, 225, 231, 113, 39, 18, 141, 213, 215, 201, 201, 90, 173, 14, 134, 192, 119, 133, 134, 164, 26, 38, 1, 201, 94, 187, 59, 186, 170, 240, 2, ]); /// `P1_EXTENDED on `CompressedEdwardsY` format. pub(self) const P2_COMPRESSED: CompressedEdwardsY = CompressedEdwardsY([ 2, 245, 125, 248, 208, 106, 136, 57, 210, 240, 163, 133, 151, 109, 214, 81, 69, 38, 201, 203, 56, 203, 247, 138, 125, 108, 10, 162, 231, 98, 73, 7, ]); //------------------ Tests ------------------// #[test] fn from_projective_to_extended() { assert!(EdwardsPoint::from(P1_PROJECTIVE) == P1_EXTENDED); } #[test] fn from_extended_to_projective() { assert!(P1_PROJECTIVE == ProjectivePoint::from(P1_EXTENDED)); } #[test] fn extended_point_neg() { let a = EdwardsPoint::default(); let inv_a = EdwardsPoint { X: FieldElement::zero(), Y: FieldElement::one(), Z: FieldElement::one(), T: FieldElement::zero(), }; let res = -a; assert!(res == inv_a); } #[test] fn extended_coords_neg_identity() { let res = -EdwardsPoint::identity(); assert!(res == EdwardsPoint::identity()) } #[test] fn extended_point_addition() { let res = &P1_EXTENDED + &P2_EXTENDED; assert!(res == P4_EXTENDED); } #[test] fn extended_point_doubling_by_addition() { let res: EdwardsPoint = &P1_EXTENDED + &P1_EXTENDED; assert!(res == P3_EXTENDED); } #[test] fn extended_point_doubling() { let res = P1_EXTENDED.double(); assert!(res == P3_EXTENDED); // Identity case. let res = EdwardsPoint::identity(); assert!(res == res.double()); } #[test] fn extended_double_and_add() { // Since we compute (8*P) we don't need // to test `mul_by_cofactor` if this passes. let expect = P1_EXTENDED.double().double().double(); let res = P1_EXTENDED * Scalar::from(8u8); assert!(expect == res); } #[test] fn extended_point_generation() { let y2 = FieldElement([ 2369245568431362, 2665603790611352, 3317390952748653, 1908583331312524, 8011773354506, ]); let p2 = EdwardsPoint::new_from_y_coord(&y2, Choice::from(0u8)).unwrap(); assert!(p2 == P2_EXTENDED); let y1 = FieldElement([ 606320128494542, 1597163540666577, 1835599237877421, 1667478411389512, 3232679738299, ]); let p1 = EdwardsPoint::new_from_y_coord(&y1, Choice::from(0u8)).unwrap(); assert!(p1 == P1_EXTENDED); // `A = 15` which is not a QR over the prime of the field. let y_failure = FieldElement::from(15u8); let p_fail = EdwardsPoint::new_from_y_coord(&y_failure, Choice::from(0u8)); assert!(p_fail.is_none()) } #[test] fn projective_point_neg() { let a = ProjectivePoint::default(); let inv_a = ProjectivePoint { X: FieldElement::zero(), Y: FieldElement::one(), Z: FieldElement::one(), }; let res = -a; assert!(res == inv_a); } #[test] fn projective_coords_neg_identity() { let res = -&ProjectivePoint::identity(); assert!(res == ProjectivePoint::identity()) } #[test] fn projective_point_addition() { let res = P1_PROJECTIVE + P2_PROJECTIVE; assert!(res == P4_PROJECTIVE); } #[test] fn projective_point_doubling() { let res = P1_PROJECTIVE.double(); assert!(res == P3_PROJECTIVE); } #[test] fn projective_double_and_add() { // Since we compute (8*P) we don't need // to test `mul_by_cofactor` if this passes. let expect = P1_PROJECTIVE.double().double().double(); let res = P1_PROJECTIVE * Scalar::from(8u8); assert!(expect == res); } #[test] fn projective_point_generation() { let y2 = FieldElement([ 2369245568431362, 2665603790611352, 3317390952748653, 1908583331312524, 8011773354506, ]); let p2 = ProjectivePoint::new_from_y_coord(&y2, Choice::from(0u8)).unwrap(); assert!(p2 == P2_PROJECTIVE); let y1 = FieldElement([ 606320128494542, 1597163540666577, 1835599237877421, 1667478411389512, 3232679738299, ]); let p1 = ProjectivePoint::new_from_y_coord(&y1, Choice::from(0u8)).unwrap(); assert!(p1 == P1_PROJECTIVE); // `A = 15` which is not a QR over the prime of the field. let y_failure = FieldElement::from(15u8); let p_fail = ProjectivePoint::new_from_y_coord(&y_failure, Choice::from(0u8)); assert!(p_fail.is_none()) } #[test] fn affine_point_ct_eq() { // Test true case for equalty. assert!(P1_AFFINE.ct_eq(&P2_AFFINE).unwrap_u8() == 0u8); // Test false case for equalty. assert!(P1_AFFINE.ct_eq(&P1_AFFINE).unwrap_u8() == 1u8); // After Point doubling case. Z's are different but points are equivalent. assert!( AffinePoint::from(P3_PROJECTIVE) .ct_eq(&AffinePoint::from(P1_PROJECTIVE.double())) .unwrap_u8() == 1u8 ); } #[test] fn affine_point_eq() { assert!(P1_AFFINE == P1_AFFINE); assert!(P1_AFFINE != P2_AFFINE); assert!(AffinePoint::from(P3_PROJECTIVE) == AffinePoint::from(P1_PROJECTIVE.double())); } #[test] fn point_compression() { let compr = CompressedEdwardsY::from_slice(&[ 206, 11, 225, 231, 113, 39, 18, 141, 213, 215, 201, 201, 90, 173, 14, 134, 192, 119, 133, 134, 164, 26, 38, 1, 201, 94, 187, 59, 186, 170, 240, 2, ]); assert!(compr == P1_EXTENDED.compress()); let compr2 = CompressedEdwardsY::from_slice(&[ 2, 245, 125, 248, 208, 106, 136, 57, 210, 240, 163, 133, 151, 109, 214, 81, 69, 38, 201, 203, 56, 203, 247, 138, 125, 108, 10, 162, 231, 98, 73, 7, ]); assert!(compr2 == P2_EXTENDED.compress()); } #[test] fn point_decompression() { assert!(P1_COMPRESSED.decompress().unwrap() == P1_EXTENDED); assert!(P2_COMPRESSED.decompress().unwrap() == P2_EXTENDED); // Define a compressed point which Y coordinate does not // rely on the curve. let fail_compr = CompressedEdwardsY::from_slice(&[ 250, 144, 188, 47, 13, 101, 118, 114, 201, 185, 169, 115, 255, 111, 40, 25, 69, 105, 170, 255, 113, 65, 120, 126, 170, 192, 48, 109, 112, 20, 221, 149, ]); assert!(fail_compr.decompress().is_none()); } #[test] fn validity_check() { // Affine Coords. assert!(AffinePoint::identity().is_valid().unwrap_u8() == 1u8); assert!(P1_AFFINE.is_valid().unwrap_u8() == 1u8); assert!(P2_AFFINE.is_valid().unwrap_u8() == 1u8); // Projective / Extended Coords (use the same formula). assert!(EdwardsPoint::identity().is_valid().unwrap_u8() == 1u8); assert!(P1_EXTENDED.is_valid().unwrap_u8() == 1u8); assert!(P2_PROJECTIVE.is_valid().unwrap_u8() == 1u8); assert!(P4_EXTENDED.is_valid().unwrap_u8() == 1u8); } #[test] fn unique_basepoint_test() { let y = FieldElement::from(3u8) / FieldElement::from(5u8); let basep = EdwardsPoint::new_from_y_coord(&y, Choice::from(0u8)).unwrap(); assert!(basep.is_valid().unwrap_u8() == 1u8); assert!(basep * constants::L == EdwardsPoint::identity()); } #[test] fn left_to_right_bin_mul() { assert!(P1_EXTENDED * Scalar::two_pow_k(215) == ltr_bin_mul(&P1_EXTENDED, &Scalar::two_pow_k(215))); } #[test] fn naf_bin_mul() { let scalar = Scalar::two_pow_k(7); assert!(double_and_add(&P1_EXTENDED, &scalar) == binary_naf_mul(&P1_EXTENDED, &scalar)); let scalar = Scalar::two_pow_k(215); assert!(double_and_add(&P1_EXTENDED, &scalar) == binary_naf_mul(&P1_EXTENDED, &scalar)); let scalar = Scalar::two_pow_k(249) - Scalar::one(); assert!(binary_naf_mul(&P1_EXTENDED, &scalar) == double_and_add(&P1_EXTENDED, &scalar)); assert!(P1_EXTENDED * Scalar::minus_one() == binary_naf_mul(&P1_EXTENDED, &Scalar::minus_one())); } /* #[test] fn aaaaa() { // Doubling test. let scalar = Scalar::from(2u8); assert!(double_and_add(&constants::RISTRETTO_BASEPOINT, &scalar) == window_naf_mul(&scalar, 2u8)); // Pow of 2. let scalar = Scalar::two_pow_k(215); assert!(double_and_add(&constants::RISTRETTO_BASEPOINT, &scalar) == window_naf_mul(&scalar, 3u8)); // Not pow of 2. let scalar = Scalar::two_pow_k(249) - Scalar::one(); assert!(window_naf_mul(&scalar,4u8) == binary_naf_mul(&constants::RISTRETTO_BASEPOINT, &scalar)); // Minus one case. let scalar = Scalar::minus_one() - Scalar::one(); assert!(double_and_add(&constants::RISTRETTO_BASEPOINT, &scalar) == window_naf_mul(&scalar, 5u8)); }*/ }