diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..be1aec0a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +target +Cargo.lock +.DS_Store +.idea +*.iml +*.ipynb_checkpoints +*.pyc +*.sage.py +params diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 000000000..39f2ca644 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,6 @@ +Sean Bowe +Alessandro Chiesa +Matthew Green +Ian Miers +Pratyush Mishra +Howard Wu diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..8251e6197 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,25 @@ +[workspace] + +members = [ "dpc", "algebra", "snark", "snark-gadgets", "bench-utils" ] + +[profile.release] +opt-level = 3 +lto = "thin" +incremental = true + +[profile.bench] +opt-level = 3 +debug = false +rpath = false +lto = "thin" +incremental = true +debug-assertions = false + +[profile.dev] +opt-level = 0 + +[profile.test] +opt-level = 3 +incremental = true +debug-assertions = true +debug = true diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 000000000..16fe87b06 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 000000000..72dc60d84 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 000000000..3f58bc09b --- /dev/null +++ b/README.md @@ -0,0 +1,85 @@ +

ZEXE (Zero knowledge EXEcution)

+ +___ZEXE___ (pronounced */zeksē/*) is a Rust library for decentralized private computation. + +This library was initially developed as part of the paper *"[ZEXE: Enabling Decentralized Private Computation][zexe]"*, and it is released under the MIT License and the Apache v2 License (see [License](#license)). + +**WARNING:** This is an academic proof-of-concept prototype, and in particular has not received careful code review. This implementation is NOT ready for production use. + +## Overview + +This library implements a ledger-based system that enables users to execute offline computations and subsequently produce publicly-verifiable transactions that attest to the correctness of these offline executions. The transactions contain *zero-knowledge succinct arguments* (zkSNARKs) attesting to the correctness of the offline computations, and provide strong notions of privacy and succinctness. + +- **Privacy** - transactions reveal no information about the offline computation. +- **Succinctness** - transactions can be validated in time that is independent of the offline computation. +- **Application isolation** - malicious applications cannot affect the execution of honest applications. +- **Application interaction** - applications can safely communicate with each other. + +Informally, the library provides the ability to create transactions that run arbitrary (Turing-complete) scripts on hidden data stored on the ledger. In more detail, the library implements a cryptographic primitive known as *decentralized private computation* (DPC) schemes, which are described in detail in the [ZEXE paper][zexe]. + +## Directory structure + +This repository contains several Rust crates that implement the different building blocks of ZEXE. The high-level structure of the repository is as follows. + +* [`algebra`](algebra): Rust crate that provides finite fields and elliptic curves +* [`dpc`](dpc): Rust crate that implements DPC schemes (the main cryptographic primitive in this repository) +* [`snark`](snark): Rust crate that provides succinct zero-knowledge arguments +* [`snark-gadgets`](snark-gadgets): Rust crate that provides various gadgets used to construct constraint systems + +In addition, there is a [`bench-utils`](bench-utils) crate which contains infrastructure for benchmarking. This crate includes macros for timing code segments and is used for profiling the building blocks of ZEXE. + +## Build guide + +The library relies on the `nightly` toolchain of the Rust compiler (only for the relatively well-tested `const_fn` feature). To install the latest Rust nightly, first install `rustup` by following the instructions [here](https://rustup.rs/), or via your platform's package manager. Once `rustup` is installed, install the latest nightly by invoking: +```bash +rustup install nightly +``` + +After that, use `cargo`, the standard Rust build tool, to build the library: +```bash +git clone https://github.com/scipr-lab/zexe.git +cd zexe/dpc +cargo +nightly build --release +``` + +This library comes with unit tests for each of the provided crates. Run the tests with: +```bash +cargo test +``` + +Lastly, this library comes with benchmarks for the following crates: + +- [`algebra`](algebra) +- [`dpc`](dpc) + +To perform the benchmarks, run the following command: +```bash +cargo bench +``` + +## License + +ZEXE is licensed under either of the following licenses, at your discretion. + + * Apache License Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +Unless you explicitly state otherwise, any contribution submitted for inclusion in ZEXE by you shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions. + +[zexe]: https://ia.cr/2018/962 + +## Reference paper + +[_ZEXE: Enabling Decentralized Private Computation_][zexe] +Sean Bowe, Alessandro Chiesa, Matthew Green, Ian Miers, [Pratyush Mishra](https://www.github.com/pratyush), [Howard Wu](https://www.github.com/howardwu) +*IACR ePrint Report 2018/962* + +## Acknowledgements + +This work was supported by: +a Google Faculty Award; +the National Science Foundation; +the UC Berkeley Center for Long-Term Cybersecurity; +and donations from the Ethereum Foundation, the Interchain Foundation, and Qtum. + +Some parts of the finite field arithmetic, elliptic curve arithmetic, FFTs, and multi-threading infrastructure in the `algebra` crate have been adapted from code in the [`ff`](https://github.com/zkcrypto/ff), [`pairing`](https://github.com/zkcrypto/pairing), and [`bellman`](https://github.com/zkcrypto/bellman) crates, developed by [Sean Bowe](https://www.github.com/ebfull) and others from Zcash. diff --git a/algebra/Cargo.toml b/algebra/Cargo.toml new file mode 100644 index 000000000..fec6ec285 --- /dev/null +++ b/algebra/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "algebra" +version = "0.1.0" +authors = [ + "Sean Bowe", + "Alessandro Chiesa", + "Matthew Green", + "Ian Miers", + "Pratyush Mishra", + "Howard Wu" +] +description = "A library for finite fields and elliptic curves" +homepage = "https://libzexe.org" +repository = "https://github.com/scipr/zexe" +documentation = "https://docs.rs/algebra/" +keywords = ["cryptography", "finite fields", "elliptic curves", "pairing"] +categories = ["cryptography"] +include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +license = "MIT/Apache-2.0" +edition = "2018" + +################################# Dependencies ################################ + +[dependencies] +byteorder = { version = "1" } +rand = { version = "0.4" } +rand_derive = { version = "0.3" } +derivative = { version = "1" } + +failure = { version = "0.1.1" } +failure_derive = { version = "0.1.1" } + +colored = { version = "1", optional = true } +rayon = { version = "1", optional = true } +clippy = { version = "*", optional = true } + +[dev-dependencies] +blake2 = "0.7" +criterion = "0.2" + +[features] +parallel = [ "rayon" ] diff --git a/algebra/LICENSE-APACHE b/algebra/LICENSE-APACHE new file mode 120000 index 000000000..965b606f3 --- /dev/null +++ b/algebra/LICENSE-APACHE @@ -0,0 +1 @@ +../LICENSE-APACHE \ No newline at end of file diff --git a/algebra/LICENSE-MIT b/algebra/LICENSE-MIT new file mode 120000 index 000000000..76219eb72 --- /dev/null +++ b/algebra/LICENSE-MIT @@ -0,0 +1 @@ +../LICENSE-MIT \ No newline at end of file diff --git a/algebra/benches/bls12_377/ec.rs b/algebra/benches/bls12_377/ec.rs new file mode 100644 index 000000000..9408e18ef --- /dev/null +++ b/algebra/benches/bls12_377/ec.rs @@ -0,0 +1,184 @@ +mod g1 { + use rand::{Rand, SeedableRng, XorShiftRng}; + use std::ops::AddAssign; + + use algebra::{ + curves::bls12_377::{G1Affine, G1Projective as G1}, + fields::bls12_377::Fr, + ProjectiveCurve, + }; + + #[bench] + fn bench_g1_rand(b: &mut ::test::Bencher) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + b.iter(|| G1::rand(&mut rng)); + } + + #[bench] + fn bench_g1_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, Fr)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_add_assign_mixed(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1Affine)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng).into())) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign_mixed(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); + } +} + +mod g2 { + use algebra::{ + curves::bls12_377::{G2Affine, G2Projective as G2}, + fields::bls12_377::Fr, + ProjectiveCurve, + }; + use rand::{Rand, SeedableRng, XorShiftRng}; + use std::ops::AddAssign; + + #[bench] + fn bench_g2_rand(b: &mut ::test::Bencher) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + b.iter(|| G2::rand(&mut rng)); + } + + #[bench] + fn bench_g2_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, Fr)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_add_assign_mixed(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2Affine)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng).into())) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign_mixed(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); + } +} diff --git a/algebra/benches/bls12_377/fq.rs b/algebra/benches/bls12_377/fq.rs new file mode 100644 index 000000000..042363a5e --- /dev/null +++ b/algebra/benches/bls12_377/fq.rs @@ -0,0 +1,288 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::{ + biginteger::BigInteger384 as FqRepr, fields::bls12_377::fq::Fq, BigInteger, Field, PrimeField, + SquareRootField, +}; + +#[bench] +fn bench_fq_repr_add_nocarry(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FqRepr, FqRepr)> = (0..SAMPLES) + .map(|_| { + let mut tmp1 = FqRepr::rand(&mut rng); + let mut tmp2 = FqRepr::rand(&mut rng); + // Shave a few bits off to avoid overflow. + for _ in 0..3 { + tmp1.div2(); + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_nocarry(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_sub_noborrow(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FqRepr, FqRepr)> = (0..SAMPLES) + .map(|_| { + let tmp1 = FqRepr::rand(&mut rng); + let mut tmp2 = tmp1; + // Ensure tmp2 is smaller than tmp1. + for _ in 0..10 { + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_noborrow(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_num_bits(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].num_bits(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_mul2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.mul2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_div2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.div2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].inverse() + }); +} + +#[bench] +fn bench_fq_negate(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp = -tmp; + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + let mut tmp = Fq::rand(&mut rng); + tmp.square_in_place(); + tmp + }) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].sqrt() + }); +} + +#[bench] +fn bench_fq_into_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].into_repr() + }); +} + +#[bench] +fn bench_fq_from_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| Fq::rand(&mut rng).into_repr()) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + Fq::from_repr(v[count]) + }); +} diff --git a/algebra/benches/bls12_377/fq12.rs b/algebra/benches/bls12_377/fq12.rs new file mode 100644 index 000000000..cc0e85d85 --- /dev/null +++ b/algebra/benches/bls12_377/fq12.rs @@ -0,0 +1,111 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::fields::{bls12_377::fq12::Fq12, Field}; + +#[bench] +fn bench_fq12_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq12, Fq12)> = (0..SAMPLES) + .map(|_| (Fq12::rand(&mut rng), Fq12::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq12, Fq12)> = (0..SAMPLES) + .map(|_| (Fq12::rand(&mut rng), Fq12::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq12, Fq12)> = (0..SAMPLES) + .map(|_| (Fq12::rand(&mut rng), Fq12::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq12::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq12::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq12::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].inverse(); + count = (count + 1) % SAMPLES; + tmp + }); +} diff --git a/algebra/benches/bls12_377/fq2.rs b/algebra/benches/bls12_377/fq2.rs new file mode 100644 index 000000000..53cf2e1d8 --- /dev/null +++ b/algebra/benches/bls12_377/fq2.rs @@ -0,0 +1,127 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::{fields::bls12_377::fq2::Fq2, Field, SquareRootField}; + +#[bench] +fn bench_fq2_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq2, Fq2)> = (0..SAMPLES) + .map(|_| (Fq2::rand(&mut rng), Fq2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq2, Fq2)> = (0..SAMPLES) + .map(|_| (Fq2::rand(&mut rng), Fq2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq2, Fq2)> = (0..SAMPLES) + .map(|_| (Fq2::rand(&mut rng), Fq2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].inverse(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].sqrt(); + count = (count + 1) % SAMPLES; + tmp + }); +} diff --git a/algebra/benches/bls12_377/fr.rs b/algebra/benches/bls12_377/fr.rs new file mode 100644 index 000000000..fff0ee539 --- /dev/null +++ b/algebra/benches/bls12_377/fr.rs @@ -0,0 +1,288 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::{ + biginteger::BigInteger256 as FrRepr, fields::bls12_377::fr::Fr, BigInteger, Field, PrimeField, + SquareRootField, +}; + +#[bench] +fn bench_fr_repr_add_nocarry(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FrRepr, FrRepr)> = (0..SAMPLES) + .map(|_| { + let mut tmp1 = FrRepr::rand(&mut rng); + let mut tmp2 = FrRepr::rand(&mut rng); + // Shave a few bits off to avoid overflow. + for _ in 0..3 { + tmp1.div2(); + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_nocarry(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_sub_noborrow(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FrRepr, FrRepr)> = (0..SAMPLES) + .map(|_| { + let tmp1 = FrRepr::rand(&mut rng); + let mut tmp2 = tmp1; + // Ensure tmp2 is smaller than tmp1. + for _ in 0..10 { + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_noborrow(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_num_bits(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].num_bits(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_mul2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.mul2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_div2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.div2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].inverse() + }); +} + +#[bench] +fn bench_fr_negate(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp = -tmp; + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + let mut tmp = Fr::rand(&mut rng); + tmp.square_in_place(); + tmp + }) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].sqrt() + }); +} + +#[bench] +fn bench_fr_into_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].into_repr() + }); +} + +#[bench] +fn bench_fr_from_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| Fr::rand(&mut rng).into_repr()) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + Fr::from_repr(v[count]) + }); +} diff --git a/algebra/benches/bls12_377/mod.rs b/algebra/benches/bls12_377/mod.rs new file mode 100644 index 000000000..ea18d0268 --- /dev/null +++ b/algebra/benches/bls12_377/mod.rs @@ -0,0 +1,6 @@ +mod ec; +mod fq; +mod fq12; +mod fq2; +mod fr; +mod pairing; diff --git a/algebra/benches/bls12_377/pairing.rs b/algebra/benches/bls12_377/pairing.rs new file mode 100644 index 000000000..dc18bac8e --- /dev/null +++ b/algebra/benches/bls12_377/pairing.rs @@ -0,0 +1,83 @@ +mod pairing { + use rand::{Rand, SeedableRng, XorShiftRng}; + + use algebra::{ + curves::{ + bls12::{G1Prepared, G2Prepared}, + bls12_377::{ + Bls12_377, Bls12_377Parameters, G1Affine, G1Projective as G1, G2Affine, + G2Projective as G2, + }, + PairingCurve, PairingEngine, + }, + fields::bls12_377::Fq12, + }; + + #[bench] + fn bench_pairing_miller_loop(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<( + G1Prepared, + G2Prepared, + )> = (0..SAMPLES) + .map(|_| { + ( + G1Affine::from(G1::rand(&mut rng)).prepare(), + G2Affine::from(G2::rand(&mut rng)).prepare(), + ) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = Bls12_377::miller_loop(&[(&v[count].0, &v[count].1)]); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_pairing_final_exponentiation(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + ( + G1Affine::from(G1::rand(&mut rng)).prepare(), + G2Affine::from(G2::rand(&mut rng)).prepare(), + ) + }) + .map(|(ref p, ref q)| Bls12_377::miller_loop(&[(p, q)])) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = Bls12_377::final_exponentiation(&v[count]); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_pairing_full(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G2)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = Bls12_377::pairing(v[count].0, v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } +} diff --git a/algebra/benches/bls12_381/ec.rs b/algebra/benches/bls12_381/ec.rs new file mode 100644 index 000000000..d9a1956af --- /dev/null +++ b/algebra/benches/bls12_381/ec.rs @@ -0,0 +1,185 @@ +mod g1 { + use rand::{Rand, SeedableRng, XorShiftRng}; + use std::ops::AddAssign; + + use algebra::{ + curves::bls12_381::{G1Affine, G1Projective as G1}, + fields::bls12_381::Fr, + ProjectiveCurve, + }; + + #[bench] + fn bench_g1_rand(b: &mut ::test::Bencher) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + b.iter(|| G1::rand(&mut rng)); + } + + #[bench] + fn bench_g1_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, Fr)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_add_assign_mixed(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1Affine)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng).into())) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign_mixed(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); + } +} + +mod g2 { + use rand::{Rand, SeedableRng, XorShiftRng}; + use std::ops::AddAssign; + + use algebra::{ + curves::bls12_381::{G2Affine, G2Projective as G2}, + fields::bls12_381::Fr, + ProjectiveCurve, + }; + + #[bench] + fn bench_g2_rand(b: &mut ::test::Bencher) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + b.iter(|| G2::rand(&mut rng)); + } + + #[bench] + fn bench_g2_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, Fr)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_add_assign_mixed(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2Affine)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng).into())) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign_mixed(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); + } +} diff --git a/algebra/benches/bls12_381/fq.rs b/algebra/benches/bls12_381/fq.rs new file mode 100644 index 000000000..0a0c7a653 --- /dev/null +++ b/algebra/benches/bls12_381/fq.rs @@ -0,0 +1,288 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::{ + biginteger::BigInteger384 as FqRepr, fields::bls12_381::fq::Fq, BigInteger, Field, PrimeField, + SquareRootField, +}; + +#[bench] +fn bench_fq_repr_add_nocarry(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FqRepr, FqRepr)> = (0..SAMPLES) + .map(|_| { + let mut tmp1 = FqRepr::rand(&mut rng); + let mut tmp2 = FqRepr::rand(&mut rng); + // Shave a few bits off to avoid overflow. + for _ in 0..3 { + tmp1.div2(); + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_nocarry(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_sub_noborrow(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FqRepr, FqRepr)> = (0..SAMPLES) + .map(|_| { + let tmp1 = FqRepr::rand(&mut rng); + let mut tmp2 = tmp1; + // Ensure tmp2 is smaller than tmp1. + for _ in 0..10 { + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_noborrow(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_num_bits(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].num_bits(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_mul2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.mul2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_div2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.div2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].inverse() + }); +} + +#[bench] +fn bench_fq_negate(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp = -tmp; + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + let mut tmp = Fq::rand(&mut rng); + tmp.square_in_place(); + tmp + }) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].sqrt() + }); +} + +#[bench] +fn bench_fq_into_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].into_repr() + }); +} + +#[bench] +fn bench_fq_from_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| Fq::rand(&mut rng).into_repr()) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + Fq::from_repr(v[count]) + }); +} diff --git a/algebra/benches/bls12_381/fq12.rs b/algebra/benches/bls12_381/fq12.rs new file mode 100644 index 000000000..3fb9b199d --- /dev/null +++ b/algebra/benches/bls12_381/fq12.rs @@ -0,0 +1,111 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::fields::{bls12_381::fq12::Fq12, Field}; + +#[bench] +fn bench_fq12_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq12, Fq12)> = (0..SAMPLES) + .map(|_| (Fq12::rand(&mut rng), Fq12::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq12, Fq12)> = (0..SAMPLES) + .map(|_| (Fq12::rand(&mut rng), Fq12::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq12, Fq12)> = (0..SAMPLES) + .map(|_| (Fq12::rand(&mut rng), Fq12::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq12::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq12::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq12_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq12::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].inverse(); + count = (count + 1) % SAMPLES; + tmp + }); +} diff --git a/algebra/benches/bls12_381/fq2.rs b/algebra/benches/bls12_381/fq2.rs new file mode 100644 index 000000000..b79e4cf7b --- /dev/null +++ b/algebra/benches/bls12_381/fq2.rs @@ -0,0 +1,127 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::{fields::bls12_381::fq2::Fq2, Field, SquareRootField}; + +#[bench] +fn bench_fq2_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq2, Fq2)> = (0..SAMPLES) + .map(|_| (Fq2::rand(&mut rng), Fq2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq2, Fq2)> = (0..SAMPLES) + .map(|_| (Fq2::rand(&mut rng), Fq2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq2, Fq2)> = (0..SAMPLES) + .map(|_| (Fq2::rand(&mut rng), Fq2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].inverse(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq2_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq2::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].sqrt(); + count = (count + 1) % SAMPLES; + tmp + }); +} diff --git a/algebra/benches/bls12_381/fr.rs b/algebra/benches/bls12_381/fr.rs new file mode 100644 index 000000000..c29f170c2 --- /dev/null +++ b/algebra/benches/bls12_381/fr.rs @@ -0,0 +1,288 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +use algebra::{ + biginteger::BigInteger256 as FrRepr, fields::bls12_381::fr::Fr, BigInteger, Field, PrimeField, + SquareRootField, +}; + +#[bench] +fn bench_fr_repr_add_nocarry(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FrRepr, FrRepr)> = (0..SAMPLES) + .map(|_| { + let mut tmp1 = FrRepr::rand(&mut rng); + let mut tmp2 = FrRepr::rand(&mut rng); + // Shave a few bits off to avoid overflow. + for _ in 0..3 { + tmp1.div2(); + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_nocarry(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_sub_noborrow(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FrRepr, FrRepr)> = (0..SAMPLES) + .map(|_| { + let tmp1 = FrRepr::rand(&mut rng); + let mut tmp2 = tmp1; + // Ensure tmp2 is smaller than tmp1. + for _ in 0..10 { + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_noborrow(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_num_bits(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].num_bits(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_mul2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.mul2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_div2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.div2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].inverse() + }); +} + +#[bench] +fn bench_fr_negate(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp = -tmp; + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + let mut tmp = Fr::rand(&mut rng); + tmp.square_in_place(); + tmp + }) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].sqrt() + }); +} + +#[bench] +fn bench_fr_into_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].into_repr() + }); +} + +#[bench] +fn bench_fr_from_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| Fr::rand(&mut rng).into_repr()) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + Fr::from_repr(v[count]) + }); +} diff --git a/algebra/benches/bls12_381/mod.rs b/algebra/benches/bls12_381/mod.rs new file mode 100644 index 000000000..ea18d0268 --- /dev/null +++ b/algebra/benches/bls12_381/mod.rs @@ -0,0 +1,6 @@ +mod ec; +mod fq; +mod fq12; +mod fq2; +mod fr; +mod pairing; diff --git a/algebra/benches/bls12_381/pairing.rs b/algebra/benches/bls12_381/pairing.rs new file mode 100644 index 000000000..64ea3c9f3 --- /dev/null +++ b/algebra/benches/bls12_381/pairing.rs @@ -0,0 +1,83 @@ +mod pairing { + use rand::{Rand, SeedableRng, XorShiftRng}; + + use algebra::{ + curves::{ + bls12::{G1Prepared, G2Prepared}, + bls12_381::{ + Bls12_381, Bls12_381Parameters, G1Affine, G1Projective as G1, G2Affine, + G2Projective as G2, + }, + PairingCurve, PairingEngine, + }, + fields::bls12_381::Fq12, + }; + + #[bench] + fn bench_pairing_miller_loop(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<( + G1Prepared, + G2Prepared, + )> = (0..SAMPLES) + .map(|_| { + ( + G1Affine::from(G1::rand(&mut rng)).prepare(), + G2Affine::from(G2::rand(&mut rng)).prepare(), + ) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = Bls12_381::miller_loop(&[(&v[count].0, &v[count].1)]); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_pairing_final_exponentiation(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + ( + G1Affine::from(G1::rand(&mut rng)).prepare(), + G2Affine::from(G2::rand(&mut rng)).prepare(), + ) + }) + .map(|(ref p, ref q)| Bls12_381::miller_loop(&[(p, q)])) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = Bls12_381::final_exponentiation(&v[count]); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_pairing_full(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G2)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = Bls12_381::pairing(v[count].0, v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } +} diff --git a/algebra/benches/curve_and_field_benches.rs b/algebra/benches/curve_and_field_benches.rs new file mode 100644 index 000000000..044e3cec6 --- /dev/null +++ b/algebra/benches/curve_and_field_benches.rs @@ -0,0 +1,7 @@ +#![feature(test)] + +extern crate test; + +mod bls12_377; +mod bls12_381; +mod sw6; diff --git a/algebra/benches/sw6/ec.rs b/algebra/benches/sw6/ec.rs new file mode 100644 index 000000000..abaef7d91 --- /dev/null +++ b/algebra/benches/sw6/ec.rs @@ -0,0 +1,183 @@ +mod g1 { + use algebra::{ + curves::sw6::{G1Affine, G1Projective as G1}, + fields::sw6::Fr, + ProjectiveCurve, + }; + use rand::{Rand, SeedableRng, XorShiftRng}; + use std::ops::AddAssign; + + #[bench] + fn bench_g1_rand(b: &mut ::test::Bencher) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + b.iter(|| G1::rand(&mut rng)); + } + + #[bench] + fn bench_g1_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, Fr)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_add_assign_mixed(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1Affine)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng).into())) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign_mixed(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g1_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G1)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G1::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); + } +} + +mod g2 { + use algebra::{ + curves::sw6::{G2Affine, G2Projective as G2}, + fields::sw6::Fr, + ProjectiveCurve, + }; + use rand::{Rand, SeedableRng, XorShiftRng}; + use std::ops::AddAssign; + + #[bench] + fn bench_g2_rand(b: &mut ::test::Bencher) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + b.iter(|| G2::rand(&mut rng)); + } + + #[bench] + fn bench_g2_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, Fr)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_add_assign_mixed(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2Affine)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng).into())) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign_mixed(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_g2_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G2, G2)> = (0..SAMPLES) + .map(|_| (G2::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); + } +} diff --git a/algebra/benches/sw6/fq.rs b/algebra/benches/sw6/fq.rs new file mode 100644 index 000000000..2ba39c406 --- /dev/null +++ b/algebra/benches/sw6/fq.rs @@ -0,0 +1,288 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; + +use algebra::{ + biginteger::BigInteger832 as FqRepr, fields::sw6::fq::Fq, BigInteger, Field, PrimeField, + SquareRootField, +}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +#[bench] +fn bench_fq_repr_add_nocarry(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FqRepr, FqRepr)> = (0..SAMPLES) + .map(|_| { + let mut tmp1 = FqRepr::rand(&mut rng); + let mut tmp2 = FqRepr::rand(&mut rng); + // Shave a few bits off to avoid overflow. + for _ in 0..3 { + tmp1.div2(); + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_nocarry(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_sub_noborrow(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FqRepr, FqRepr)> = (0..SAMPLES) + .map(|_| { + let tmp1 = FqRepr::rand(&mut rng); + let mut tmp2 = tmp1; + // Ensure tmp2 is smaller than tmp1. + for _ in 0..10 { + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_noborrow(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_num_bits(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].num_bits(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_mul2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.mul2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_repr_div2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FqRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.div2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq, Fq)> = (0..SAMPLES) + .map(|_| (Fq::rand(&mut rng), Fq::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].inverse() + }); +} + +#[bench] +fn bench_fq_negate(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp = -tmp; + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + let mut tmp = Fq::rand(&mut rng); + tmp.square_in_place(); + tmp + }) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].sqrt() + }); +} + +#[bench] +fn bench_fq_into_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].into_repr() + }); +} + +#[bench] +fn bench_fq_from_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| Fq::rand(&mut rng).into_repr()) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + Fq::from_repr(v[count]) + }); +} diff --git a/algebra/benches/sw6/fq3.rs b/algebra/benches/sw6/fq3.rs new file mode 100644 index 000000000..afe0c095b --- /dev/null +++ b/algebra/benches/sw6/fq3.rs @@ -0,0 +1,127 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; + +use algebra::{fields::sw6::fq3::Fq3, Field, SquareRootField}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +#[bench] +fn bench_fq3_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq3, Fq3)> = (0..SAMPLES) + .map(|_| (Fq3::rand(&mut rng), Fq3::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq3_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq3, Fq3)> = (0..SAMPLES) + .map(|_| (Fq3::rand(&mut rng), Fq3::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq3_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq3, Fq3)> = (0..SAMPLES) + .map(|_| (Fq3::rand(&mut rng), Fq3::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq3_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq3::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq3_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq3::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq3_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq3::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].inverse(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq3_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq3::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].sqrt(); + count = (count + 1) % SAMPLES; + tmp + }); +} diff --git a/algebra/benches/sw6/fq6.rs b/algebra/benches/sw6/fq6.rs new file mode 100644 index 000000000..f9732af97 --- /dev/null +++ b/algebra/benches/sw6/fq6.rs @@ -0,0 +1,111 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; + +use algebra::fields::{sw6::fq6::Fq6, Field}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +#[bench] +fn bench_fq6_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq6, Fq6)> = (0..SAMPLES) + .map(|_| (Fq6::rand(&mut rng), Fq6::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq6_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq6, Fq6)> = (0..SAMPLES) + .map(|_| (Fq6::rand(&mut rng), Fq6::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq6_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fq6, Fq6)> = (0..SAMPLES) + .map(|_| (Fq6::rand(&mut rng), Fq6::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq6_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq6::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq6_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq6::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fq6_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fq6::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].inverse(); + count = (count + 1) % SAMPLES; + tmp + }); +} diff --git a/algebra/benches/sw6/fr.rs b/algebra/benches/sw6/fr.rs new file mode 100644 index 000000000..80abc40b4 --- /dev/null +++ b/algebra/benches/sw6/fr.rs @@ -0,0 +1,288 @@ +use rand::{Rand, SeedableRng, XorShiftRng}; + +use algebra::{ + biginteger::{BigInteger, BigInteger384 as FrRepr}, + fields::{sw6::fr::Fr, Field, PrimeField, SquareRootField}, +}; +use std::ops::{AddAssign, MulAssign, SubAssign}; + +#[bench] +fn bench_fr_repr_add_nocarry(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FrRepr, FrRepr)> = (0..SAMPLES) + .map(|_| { + let mut tmp1 = FrRepr::rand(&mut rng); + let mut tmp2 = FrRepr::rand(&mut rng); + // Shave a few bits off to avoid overflow. + for _ in 0..3 { + tmp1.div2(); + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_nocarry(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_sub_noborrow(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(FrRepr, FrRepr)> = (0..SAMPLES) + .map(|_| { + let tmp1 = FrRepr::rand(&mut rng); + let mut tmp2 = tmp1; + // Ensure tmp2 is smaller than tmp1. + for _ in 0..10 { + tmp2.div2(); + } + (tmp1, tmp2) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_noborrow(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_num_bits(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let tmp = v[count].num_bits(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_mul2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.mul2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_repr_div2(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| FrRepr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.div2(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_add_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.add_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_sub_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.sub_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_mul_assign(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(Fr, Fr)> = (0..SAMPLES) + .map(|_| (Fr::rand(&mut rng), Fr::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count].0; + tmp.mul_assign(&v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_double(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.double_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_square(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp.square_in_place(); + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_inverse(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].inverse() + }); +} + +#[bench] +fn bench_fr_negate(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + let mut tmp = v[count]; + tmp = -tmp; + count = (count + 1) % SAMPLES; + tmp + }); +} + +#[bench] +fn bench_fr_sqrt(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + let mut tmp = Fr::rand(&mut rng); + tmp.square_in_place(); + tmp + }) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].sqrt() + }); +} + +#[bench] +fn bench_fr_into_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + v[count].into_repr() + }); +} + +#[bench] +fn bench_fr_from_repr(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| Fr::rand(&mut rng).into_repr()) + .collect(); + + let mut count = 0; + b.iter(|| { + count = (count + 1) % SAMPLES; + Fr::from_repr(v[count]) + }); +} diff --git a/algebra/benches/sw6/mod.rs b/algebra/benches/sw6/mod.rs new file mode 100644 index 000000000..66eed9a18 --- /dev/null +++ b/algebra/benches/sw6/mod.rs @@ -0,0 +1,6 @@ +mod ec; +mod fq; +mod fq3; +mod fq6; +mod fr; +mod pairing; diff --git a/algebra/benches/sw6/pairing.rs b/algebra/benches/sw6/pairing.rs new file mode 100644 index 000000000..a1f4e8d11 --- /dev/null +++ b/algebra/benches/sw6/pairing.rs @@ -0,0 +1,75 @@ +mod pairing { + use algebra::{ + curves::{ + sw6::{G1Affine, G1Projective as G1, G2Affine, G2Projective as G2, SW6}, + PairingCurve, PairingEngine, + }, + fields::sw6::Fq6, + }; + use rand::{Rand, SeedableRng, XorShiftRng}; + + #[bench] + fn bench_pairing_miller_loop(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1Affine, G2Affine)> = (0..SAMPLES) + .map(|_| { + ( + G1Affine::from(G1::rand(&mut rng)).prepare(), + G2Affine::from(G2::rand(&mut rng)).prepare(), + ) + }) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = SW6::miller_loop(&[(&v[count].0, &v[count].1)]); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_pairing_final_exponentiation(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec = (0..SAMPLES) + .map(|_| { + ( + G1Affine::from(G1::rand(&mut rng)).prepare(), + G2Affine::from(G2::rand(&mut rng)).prepare(), + ) + }) + .map(|(ref p, ref q)| SW6::miller_loop(&[(p, q)])) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = SW6::final_exponentiation(&v[count]); + count = (count + 1) % SAMPLES; + tmp + }); + } + + #[bench] + fn bench_pairing_full(b: &mut ::test::Bencher) { + const SAMPLES: usize = 1000; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v: Vec<(G1, G2)> = (0..SAMPLES) + .map(|_| (G1::rand(&mut rng), G2::rand(&mut rng))) + .collect(); + + let mut count = 0; + b.iter(|| { + let tmp = SW6::pairing(v[count].0, v[count].1); + count = (count + 1) % SAMPLES; + tmp + }); + } +} diff --git a/algebra/src/biginteger/macros.rs b/algebra/src/biginteger/macros.rs new file mode 100644 index 000000000..f151bc6c1 --- /dev/null +++ b/algebra/src/biginteger/macros.rs @@ -0,0 +1,276 @@ +macro_rules! bigint_impl { + ($name:ident, $num_limbs:expr) => { + #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)] + pub struct $name(pub [u64; $num_limbs]); + + impl $name { + pub fn new(value: [u64; $num_limbs]) -> Self { + $name(value) + } + } + + impl BigInteger for $name { + #[inline] + fn add_nocarry(&mut self, other: &Self) -> bool { + let mut carry = 0; + + for (a, b) in self.0.iter_mut().zip(other.0.iter()) { + *a = arithmetic::adc(*a, *b, &mut carry); + } + + carry != 0 + } + + #[inline] + fn sub_noborrow(&mut self, other: &Self) -> bool { + let mut borrow = 0; + + for (a, b) in self.0.iter_mut().zip(other.0.iter()) { + *a = arithmetic::sbb(*a, *b, &mut borrow); + } + + borrow != 0 + } + + #[inline] + fn mul2(&mut self) { + let mut last = 0; + for i in &mut self.0 { + let tmp = *i >> 63; + *i <<= 1; + *i |= last; + last = tmp; + } + } + + #[inline] + fn muln(&mut self, mut n: u32) { + if n >= 64 * $num_limbs { + *self = Self::from(0); + return; + } + + while n >= 64 { + let mut t = 0; + for i in &mut self.0 { + ::std::mem::swap(&mut t, i); + } + n -= 64; + } + + if n > 0 { + let mut t = 0; + for i in &mut self.0 { + let t2 = *i >> (64 - n); + *i <<= n; + *i |= t; + t = t2; + } + } + } + + #[inline] + fn div2(&mut self) { + let mut t = 0; + for i in self.0.iter_mut().rev() { + let t2 = *i << 63; + *i >>= 1; + *i |= t; + t = t2; + } + } + + #[inline] + fn divn(&mut self, mut n: u32) { + if n >= 64 * $num_limbs { + *self = Self::from(0); + return; + } + + while n >= 64 { + let mut t = 0; + for i in self.0.iter_mut().rev() { + ::std::mem::swap(&mut t, i); + } + n -= 64; + } + + if n > 0 { + let mut t = 0; + for i in self.0.iter_mut().rev() { + let t2 = *i << (64 - n); + *i >>= n; + *i |= t; + t = t2; + } + } + } + + #[inline] + fn is_odd(&self) -> bool { + self.0[0] & 1 == 1 + } + + #[inline] + fn is_even(&self) -> bool { + !self.is_odd() + } + + #[inline] + fn is_zero(&self) -> bool { + self.0.iter().all(|&e| e == 0) + } + + #[inline] + fn num_bits(&self) -> u32 { + let mut ret = $num_limbs * 64; + for i in self.0.iter().rev() { + let leading = i.leading_zeros(); + ret -= leading; + if leading != 64 { + break; + } + } + + ret + } + + #[inline] + fn get_bit(&self, i: usize) -> bool { + if i >= 64 * $num_limbs { + false + } else { + let limb = i / 64; + let bit = i - (64 * limb); + (self.0[limb] & (1 << bit)) != 0 + } + } + + #[inline] + fn from_bits(bits: &[bool]) -> Self { + let mut res = Self::default(); + let mut acc: u64 = 0; + + let mut bits = bits.to_vec(); + bits.reverse(); + for (i, bits64) in bits.chunks(64).enumerate() { + for bit in bits64.iter().rev() { + acc <<= 1; + acc += *bit as u64; + } + res.0[i] = acc; + acc = 0; + } + res + } + + #[inline] + fn to_bits(&self) -> Vec { + let mut res = Vec::with_capacity(256); + for b in BitIterator::new(self.0) { + res.push(b); + } + res + } + + #[inline] + fn find_wnaf(&self) -> Vec { + let mut res = vec![]; + + let mut e = self.clone(); + while !e.is_zero() { + let z: i64; + if e.is_odd() { + z = 2 - (e.0[0] % 4) as i64; + if z >= 0 { + e.sub_noborrow(&Self::from(z as u64)); + } else { + e.add_nocarry(&Self::from((-z) as u64)); + } + } else { + z = 0; + } + res.push(z); + e.div2(); + } + + res + } + } + + impl ToBytes for $name { + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + self.0.write(writer) + } + } + + impl FromBytes for $name { + #[inline] + fn read(reader: R) -> IoResult { + <[u64; $num_limbs]>::read(reader).map(Self::new) + } + } + + impl Display for $name { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + for i in self.0.iter().rev() { + write!(f, "{:020}", *i)?; + } + Ok(()) + } + } + + impl Ord for $name { + #[inline] + fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { + for (a, b) in self.0.iter().rev().zip(other.0.iter().rev()) { + if a < b { + return ::std::cmp::Ordering::Less; + } else if a > b { + return ::std::cmp::Ordering::Greater; + } + } + + ::std::cmp::Ordering::Equal + } + } + + impl PartialOrd for $name { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { + Some(self.cmp(other)) + } + } + + impl Rand for $name { + #[inline] + fn rand(rng: &mut R) -> Self { + $name(rng.gen()) + } + } + + impl AsMut<[u64]> for $name { + #[inline] + fn as_mut(&mut self) -> &mut [u64] { + &mut self.0 + } + } + + impl AsRef<[u64]> for $name { + #[inline] + fn as_ref(&self) -> &[u64] { + &self.0 + } + } + + impl From for $name { + #[inline] + fn from(val: u64) -> $name { + let mut repr = Self::default(); + repr.0[0] = val; + repr + } + } + }; +} diff --git a/algebra/src/biginteger/mod.rs b/algebra/src/biginteger/mod.rs new file mode 100644 index 000000000..528582f5d --- /dev/null +++ b/algebra/src/biginteger/mod.rs @@ -0,0 +1,140 @@ +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::BitIterator, +}; +use rand::{Rand, Rng}; +use std::{ + fmt::{Debug, Display}, + io::{Read, Result as IoResult, Write}, +}; + +#[macro_use] +mod macros; + +bigint_impl!(BigInteger64, 1); +bigint_impl!(BigInteger128, 2); +bigint_impl!(BigInteger256, 4); +bigint_impl!(BigInteger320, 5); +bigint_impl!(BigInteger384, 6); +bigint_impl!(BigInteger768, 12); +bigint_impl!(BigInteger832, 13); + +#[cfg(test)] +mod tests; + +/// This defines a `BigInteger`, a smart wrapper around a +/// sequence of `u64` limbs, least-significant digit first. +pub trait BigInteger: + ToBytes + + FromBytes + + Copy + + Clone + + Debug + + Default + + Display + + Eq + + Ord + + Send + + Sized + + Sync + + 'static + + Rand + + AsMut<[u64]> + + AsRef<[u64]> + + From +{ + /// Add another representation to this one, returning the carry bit. + fn add_nocarry(&mut self, other: &Self) -> bool; + + /// Subtract another representation from this one, returning the borrow bit. + fn sub_noborrow(&mut self, other: &Self) -> bool; + + /// Performs a leftwise bitshift of this number, effectively multiplying + /// it by 2. Overflow is ignored. + fn mul2(&mut self); + + /// Performs a leftwise bitshift of this number by some amount. + fn muln(&mut self, amt: u32); + + /// Performs a rightwise bitshift of this number, effectively dividing + /// it by 2. + fn div2(&mut self); + + /// Performs a rightwise bitshift of this number by some amount. + fn divn(&mut self, amt: u32); + + /// Returns true iff this number is odd. + fn is_odd(&self) -> bool; + + /// Returns true iff this number is even. + fn is_even(&self) -> bool; + + /// Returns true iff this number is zero. + fn is_zero(&self) -> bool; + + /// Compute the number of bits needed to encode this number. Always a + /// multiple of 64. + fn num_bits(&self) -> u32; + + /// Compute the `i`-th bit of `self`. + fn get_bit(&self, i: usize) -> bool; + + /// Returns the big integer representation of a given big endian boolean + /// array. + fn from_bits(bits: &[bool]) -> Self; + + /// Returns the bit representation in a big endian boolean array, without + /// leading zeros. + fn to_bits(&self) -> Vec; + + /// Returns a vector for wnaf. + fn find_wnaf(&self) -> Vec; + + /// Writes this `BigInteger` as a big endian integer. Always writes + /// `(num_bits` / 8) bytes. + fn write_le(&self, writer: &mut W) -> IoResult<()> { + self.write(writer) + } + + /// Reads a big endian integer occupying (`num_bits` / 8) bytes into this + /// representation. + fn read_le(&mut self, reader: &mut R) -> IoResult<()> { + *self = Self::read(reader)?; + Ok(()) + } +} + +pub mod arithmetic { + /// Calculate a + b + carry, returning the sum and modifying the + /// carry value. + #[inline(always)] + pub(crate) fn adc(a: u64, b: u64, carry: &mut u64) -> u64 { + let tmp = u128::from(a) + u128::from(b) + u128::from(*carry); + + *carry = (tmp >> 64) as u64; + + tmp as u64 + } + + /// Calculate a - b - borrow, returning the result and modifying + /// the borrow value. + #[inline(always)] + pub(crate) fn sbb(a: u64, b: u64, borrow: &mut u64) -> u64 { + let tmp = (1u128 << 64) + u128::from(a) - u128::from(b) - u128::from(*borrow); + + *borrow = if tmp >> 64 == 0 { 1 } else { 0 }; + + tmp as u64 + } + + /// Calculate a + (b * c) + carry, returning the least significant digit + /// and setting carry to the most significant digit. + #[inline(always)] + pub(crate) fn mac_with_carry(a: u64, b: u64, c: u64, carry: &mut u64) -> u64 { + let tmp = (u128::from(a)) + u128::from(b) * u128::from(c) + u128::from(*carry); + + *carry = (tmp >> 64) as u64; + + tmp as u64 + } +} diff --git a/algebra/src/biginteger/tests.rs b/algebra/src/biginteger/tests.rs new file mode 100644 index 000000000..d57dc6e3e --- /dev/null +++ b/algebra/src/biginteger/tests.rs @@ -0,0 +1,101 @@ +use crate::biginteger::BigInteger; +use rand; + +fn biginteger_arithmetic_test(a: B, b: B, zero: B) { + // zero == zero + assert_eq!(zero, zero); + + // zero.is_zero() == true + assert_eq!(zero.is_zero(), true); + + // a == a + assert_eq!(a, a); + + // a + 0 = a + let mut a0_add = a.clone(); + a0_add.add_nocarry(&zero); + assert_eq!(a0_add, a); + + // a - 0 = a + let mut a0_sub = a.clone(); + a0_sub.sub_noborrow(&zero); + assert_eq!(a0_sub, a); + + // a - a = 0 + let mut aa_sub = a.clone(); + aa_sub.sub_noborrow(&a); + assert_eq!(aa_sub, zero); + + // a + b = b + a + let mut ab_add = a.clone(); + ab_add.add_nocarry(&b); + let mut ba_add = b.clone(); + ba_add.add_nocarry(&a); + assert_eq!(ab_add, ba_add); +} + +fn biginteger_bits_test() { + let mut one = B::from(1u64); + assert!(one.get_bit(0)); + assert!(!one.get_bit(1)); + one.muln(5); + let thirty_two = one; + assert!(!thirty_two.get_bit(0)); + assert!(!thirty_two.get_bit(1)); + assert!(!thirty_two.get_bit(2)); + assert!(!thirty_two.get_bit(3)); + assert!(!thirty_two.get_bit(4)); + assert!(thirty_two.get_bit(5), "{:?}", thirty_two); +} + +fn biginteger_bytes_test() { + let mut bytes = [0u8; 256]; + let x: B = rand::random(); + x.write(bytes.as_mut()).unwrap(); + let y = B::read(bytes.as_ref()).unwrap(); + assert_eq!(x, y); +} + +fn test_biginteger(zero: B) { + let a: B = rand::random(); + let b: B = rand::random(); + biginteger_arithmetic_test(a, b, zero); + biginteger_bytes_test::(); + biginteger_bits_test::(); +} + +#[test] +fn test_biginteger64() { + use crate::biginteger::BigInteger64 as B; + test_biginteger(B::new([0u64; 1])); +} + +#[test] +fn test_biginteger128() { + use crate::biginteger::BigInteger128 as B; + test_biginteger(B::new([0u64; 2])); +} + +#[test] +fn test_biginteger256() { + use crate::biginteger::BigInteger256 as B; + test_biginteger(B::new([0u64; 4])); +} + +#[test] +fn test_biginteger384() { + use crate::biginteger::BigInteger384 as B; + test_biginteger(B::new([0u64; 6])); +} + +#[test] +fn test_biginteger768() { + use crate::biginteger::BigInteger768 as B; + test_biginteger(B::new([0u64; 12])); +} + +#[test] +fn test_biginteger832() { + use crate::biginteger::BigInteger832 as B; + test_biginteger(B::new([0u64; 13])); +} diff --git a/algebra/src/bytes.rs b/algebra/src/bytes.rs new file mode 100644 index 000000000..585a6128c --- /dev/null +++ b/algebra/src/bytes.rs @@ -0,0 +1,310 @@ +use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; +use std::io::{Read, Result as IoResult, Write}; + +pub trait ToBytes { + /// Serializes `self` into `writer`. + fn write(&self, writer: W) -> IoResult<()>; +} + +pub trait FromBytes: Sized { + /// Reads `Self` from `reader`. + fn read(reader: R) -> IoResult; +} + +macro_rules! array_bytes { + ($N:expr) => { + impl ToBytes for [u8; $N] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + writer.write_all(self) + } + } + + impl FromBytes for [u8; $N] { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut arr = [0u8; $N]; + reader.read_exact(&mut arr)?; + Ok(arr) + } + } + + impl ToBytes for [u16; $N] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for num in self { + writer.write_u16::(*num)?; + } + Ok(()) + } + } + + impl FromBytes for [u16; $N] { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut res = [0u16; $N]; + reader.read_u16_into::(&mut res)?; + Ok(res) + } + } + + impl ToBytes for [u32; $N] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for num in self { + writer.write_u32::(*num)?; + } + Ok(()) + } + } + + impl FromBytes for [u32; $N] { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut res = [0u32; $N]; + reader.read_u32_into::(&mut res)?; + Ok(res) + } + } + + impl ToBytes for [u64; $N] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for num in self { + writer.write_u64::(*num)?; + } + Ok(()) + } + } + + impl FromBytes for [u64; $N] { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut res = [0u64; $N]; + reader.read_u64_into::(&mut res)?; + Ok(res) + } + } + }; +} + +array_bytes!(0); +array_bytes!(1); +array_bytes!(2); +array_bytes!(3); +array_bytes!(4); +array_bytes!(5); +array_bytes!(6); +array_bytes!(7); +array_bytes!(8); +array_bytes!(9); +array_bytes!(10); +array_bytes!(11); +array_bytes!(12); +array_bytes!(13); +array_bytes!(14); +array_bytes!(15); +array_bytes!(16); +array_bytes!(17); +array_bytes!(18); +array_bytes!(19); +array_bytes!(20); +array_bytes!(21); +array_bytes!(22); +array_bytes!(23); +array_bytes!(24); +array_bytes!(25); +array_bytes!(26); +array_bytes!(27); +array_bytes!(28); +array_bytes!(29); +array_bytes!(30); +array_bytes!(31); +array_bytes!(32); + +/// Takes as input a sequence of structs, and converts them to a series of +/// bytes. All traits that implement `Bytes` can be automatically converted to +/// bytes in this manner. +#[macro_export] +macro_rules! to_bytes { + ($($x:expr),*) => ({ + use std::io::Cursor; + let mut buf = Cursor::new(vec![]); + {$crate::push_to_vec!(buf, $($x),*)}.map(|_| buf.into_inner()) + }); +} + +#[macro_export] +macro_rules! push_to_vec { + ($buf:expr, $y:expr, $($x:expr),*) => ({ + { + ToBytes::write(&$y, &mut $buf) + }.and({$crate::push_to_vec!($buf, $($x),*)}) + }); + + ($buf:expr, $x:expr) => ({ + ToBytes::write(&$x, &mut $buf) + }) +} + +impl ToBytes for u8 { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + writer.write_u8(*self) + } +} + +impl FromBytes for u8 { + #[inline] + fn read(mut reader: R) -> IoResult { + reader.read_u8() + } +} + +impl ToBytes for u16 { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + writer.write_u16::(*self) + } +} + +impl FromBytes for u16 { + #[inline] + fn read(mut reader: R) -> IoResult { + reader.read_u16::() + } +} + +impl ToBytes for u32 { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + writer.write_u32::(*self) + } +} + +impl FromBytes for u32 { + #[inline] + fn read(mut reader: R) -> IoResult { + reader.read_u32::() + } +} + +impl ToBytes for u64 { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + writer.write_u64::(*self) + } +} + +impl FromBytes for u64 { + #[inline] + fn read(mut reader: R) -> IoResult { + reader.read_u64::() + } +} + +impl ToBytes for () { + #[inline] + fn write(&self, _writer: W) -> IoResult<()> { + Ok(()) + } +} + +impl FromBytes for () { + #[inline] + fn read(_bytes: R) -> IoResult { + Ok(()) + } +} + +impl ToBytes for bool { + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + u8::write(&(*self as u8), writer) + } +} + +impl FromBytes for bool { + #[inline] + fn read(reader: R) -> IoResult { + match u8::read(reader) { + Ok(0) => Ok(false), + Ok(1) => Ok(true), + Ok(_) => Err(::std::io::ErrorKind::Other.into()), + Err(err) => Err(err), + } + } +} + +impl ToBytes for [T] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for item in self { + item.write(&mut writer)?; + } + Ok(()) + } +} + +impl ToBytes for Vec { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for item in self { + item.write(&mut writer)?; + } + Ok(()) + } +} + +impl<'a, T: 'a + ToBytes> ToBytes for &'a [T] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for item in *self { + item.write(&mut writer)?; + } + Ok(()) + } +} + +impl<'a, T: 'a + ToBytes> ToBytes for &'a T { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + (*self).write(&mut writer) + } +} + +impl FromBytes for Vec { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut buf = Vec::new(); + let _ = reader.read_to_end(&mut buf)?; + Ok(buf) + } +} + +#[cfg(test)] +mod test { + use super::ToBytes; + #[test] + fn test_macro_empty() { + let array: Vec = vec![]; + let bytes: Vec = to_bytes![array].unwrap(); + assert_eq!(&bytes, &[]); + assert_eq!(bytes.len(), 0); + } + + #[test] + fn test_macro() { + let array1 = [1u8; 32]; + let array2 = [2u8; 16]; + let array3 = [3u8; 8]; + let bytes = to_bytes![array1, array2, array3].unwrap(); + assert_eq!(bytes.len(), 56); + + let mut actual_bytes = Vec::new(); + actual_bytes.extend_from_slice(&array1); + actual_bytes.extend_from_slice(&array2); + actual_bytes.extend_from_slice(&array3); + assert_eq!(bytes, actual_bytes); + } +} diff --git a/algebra/src/curves/bls12_377/g1.rs b/algebra/src/curves/bls12_377/g1.rs new file mode 100644 index 000000000..567265320 --- /dev/null +++ b/algebra/src/curves/bls12_377/g1.rs @@ -0,0 +1,74 @@ +use crate::{ + biginteger::{BigInteger256, BigInteger384}, + curves::models::{ModelParameters, SWModelParameters}, + fields::{ + bls12_377::{Fq, Fr}, + Field, + }, +}; + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct Bls12_377G1Parameters; + +impl ModelParameters for Bls12_377G1Parameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl SWModelParameters for Bls12_377G1Parameters { + /// COEFF_A = 0 + const COEFF_A: Fq = Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])); + + /// COEFF_B = 1 + const COEFF_B: Fq = Fq::new(BigInteger384([ + 0x2cdffffffffff68, + 0x51409f837fffffb1, + 0x9f7db3a98a7d3ff2, + 0x7b4e97b76e7c6305, + 0x4cf495bf803c84e8, + 0x8d6661e2fdf49a, + ])); + + /// COFACTOR = (x - 1)^2 / 3 = 30631250834960419227450344600217059328 + const COFACTOR: &'static [u64] = &[0x0, 0x170b5d4430000000]; + + /// COFACTOR_INV = COFACTOR^{-1} mod r + /// = 5285428838741532253824584287042945485047145357130994810877 + const COFACTOR_INV: Fr = Fr::new(BigInteger256([ + 2013239619100046060, + 4201184776506987597, + 2526766393982337036, + 1114629510922847535, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G1_GENERATOR_X, G1_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G1_GENERATOR_X, G1_GENERATOR_Y); + + #[inline(always)] + fn mul_by_a(_: &Self::BaseField) -> Self::BaseField { + Self::BaseField::zero() + } +} + +/// G1_GENERATOR_X = +/// 81937999373150964239938255573465948239988671502647976594219695644855304257327692006745978603320413799295628339695 +pub const G1_GENERATOR_X: Fq = Fq::new(BigInteger384([ + 0x260f33b9772451f4, + 0xc54dd773169d5658, + 0x5c1551c469a510dd, + 0x761662e4425e1698, + 0xc97d78cc6f065272, + 0xa41206b361fd4d, +])); + +/// G1_GENERATOR_Y = +/// 241266749859715473739788878240585681733927191168601896383759122102112907357779751001206799952863815012735208165030 +pub const G1_GENERATOR_Y: Fq = Fq::new(BigInteger384([ + 0x8193961fb8cb81f3, + 0x638d4c5f44adb8, + 0xfafaf3dad4daf54a, + 0xc27849e2d655cd18, + 0x2ec3ddb401d52814, + 0x7da93326303c71, +])); diff --git a/algebra/src/curves/bls12_377/g2.rs b/algebra/src/curves/bls12_377/g2.rs new file mode 100644 index 000000000..48def7f77 --- /dev/null +++ b/algebra/src/curves/bls12_377/g2.rs @@ -0,0 +1,121 @@ +use super::g1::Bls12_377G1Parameters; +use crate::{ + biginteger::{BigInteger256, BigInteger384}, + curves::models::{ModelParameters, SWModelParameters}, + fields::{ + bls12_377::{Fq, Fq2, Fr}, + Field, + }, +}; + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct Bls12_377G2Parameters; + +impl ModelParameters for Bls12_377G2Parameters { + type BaseField = Fq2; + type ScalarField = Fr; +} + +impl SWModelParameters for Bls12_377G2Parameters { + /// COEFF_A = [0, 0] + const COEFF_A: Fq2 = Fq2::new( + Bls12_377G1Parameters::COEFF_A, + Bls12_377G1Parameters::COEFF_A, + ); + + // As per https://eprint.iacr.org/2012/072.pdf, + // this curve has b' = b/i, where b is the COEFF_B of G1, and x^6 -i is + // the irreducible poly used to extend from Fp2 to Fp12. + // In our case, i = u (App A.3, T_6). + /// COEFF_B = [0, + /// 155198655607781456406391640216936120121836107652948796323930557600032281009004493664981332883744016074664192874906] + const COEFF_B: Fq2 = Fq2::new( + Fq::new(BigInteger384([0, 0, 0, 0, 0, 0])), + Fq::new(BigInteger384([ + 9255502405446297221, + 10229180150694123945, + 9215585410771530959, + 13357015519562362907, + 5437107869987383107, + 16259554076827459, + ])), + ); + + /// COFACTOR = + /// 7923214915284317143930293550643874566881017850177945424769256759165301436616933228209277966774092486467289478618404761412630691835764674559376407658497 + const COFACTOR: &'static [u64] = &[ + 0x0000000000000001, + 0x452217cc90000000, + 0xa0f3622fba094800, + 0xd693e8c36676bd09, + 0x8c505634fae2e189, + 0xfbb36b00e1dcc40c, + 0xddd88d99a6f6a829, + 0x26ba558ae9562a, + ]; + + /// COFACTOR_INV = COFACTOR^{-1} mod r + /// = 6764900296503390671038341982857278410319949526107311149686707033187604810669 + const COFACTOR_INV: Fr = Fr::new(BigInteger256([ + 15499857013495546999, + 4613531467548868169, + 14546778081091178013, + 549402535258503313, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G2_GENERATOR_X, G2_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G2_GENERATOR_X, G2_GENERATOR_Y); + + #[inline(always)] + fn mul_by_a(_: &Self::BaseField) -> Self::BaseField { + Self::BaseField::zero() + } +} + +pub const G2_GENERATOR_X: Fq2 = Fq2::new(G2_GENERATOR_X_C0, G2_GENERATOR_X_C1); +pub const G2_GENERATOR_Y: Fq2 = Fq2::new(G2_GENERATOR_Y_C0, G2_GENERATOR_Y_C1); + +/// G2_GENERATOR_X_C0 = +/// 234578317943903156414447896945035370700304028234853167447393856512937666360375779588739582059160128921763932828251 +pub const G2_GENERATOR_X_C0: Fq = Fq::new(BigInteger384([ + 0x68904082f268725b, + 0x668f2ea74f45328b, + 0xebca7a65802be84f, + 0x1e1850f4c1ada3e6, + 0x830dc22d588ef1e9, + 0x1862a81767c0982, +])); + +/// G2_GENERATOR_X_C1 = +/// 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758 +pub const G2_GENERATOR_X_C1: Fq = Fq::new(BigInteger384([ + 0x5f02a915c91c7f39, + 0xf8c553ba388da2a7, + 0xd51a416dbd198850, + 0xe943c6f38ae3073a, + 0xffe24aa8259a4981, + 0x11853391e73dfdd, +])); + +/// G2_GENERATOR_Y_C0 = +/// 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 +pub const G2_GENERATOR_Y_C0: Fq = Fq::new(BigInteger384([ + 0xd5b19b897881430f, + 0x5be9118a5b371ed, + 0x6063f91f86c131ee, + 0x3244a61be8f4ec19, + 0xa02e425b9f9a3a12, + 0x18af8c04f3360d2, +])); + +/// G2_GENERATOR_Y_C1 = +/// 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582 +pub const G2_GENERATOR_Y_C1: Fq = Fq::new(BigInteger384([ + 0x57601ac71a5b96f5, + 0xe99acc1714f2440e, + 0x2339612f10118ea9, + 0x8321e68a3b1cd722, + 0x2b543b050cc74917, + 0x590182b396c112, +])); diff --git a/algebra/src/curves/bls12_377/mod.rs b/algebra/src/curves/bls12_377/mod.rs new file mode 100644 index 000000000..f0fa85dd1 --- /dev/null +++ b/algebra/src/curves/bls12_377/mod.rs @@ -0,0 +1,70 @@ +use crate::{ + curves::{ + bls12::{ + Bls12, Bls12Parameters, G1Affine as Bls12G1Affine, G1Prepared, + G1Projective as Bls12G1Projective, G2Affine as Bls12G2Affine, G2Prepared, + G2Projective as Bls12G2Projective, TwistType, + }, + PairingCurve, PairingEngine, + }, + fields::bls12_377::{Fq, Fq12, Fq12Parameters, Fq2Parameters, Fq6Parameters}, +}; + +pub mod g1; +pub mod g2; +#[cfg(test)] +mod tests; + +use self::{g1::Bls12_377G1Parameters, g2::Bls12_377G2Parameters}; + +pub struct Bls12_377Parameters; + +impl Bls12Parameters for Bls12_377Parameters { + const X: &'static [u64] = &[0x8508c00000000001]; + /// `x` is positive. + const X_IS_NEGATIVE: bool = false; + const TWIST_TYPE: TwistType = TwistType::D; + type Fp = Fq; + type Fp2Params = Fq2Parameters; + type Fp6Params = Fq6Parameters; + type Fp12Params = Fq12Parameters; + type G1Parameters = Bls12_377G1Parameters; + type G2Parameters = Bls12_377G2Parameters; +} + +pub type Bls12_377 = Bls12; + +pub type G1Affine = Bls12G1Affine; +pub type G1Projective = Bls12G1Projective; +pub type G2Affine = Bls12G2Affine; +pub type G2Projective = Bls12G2Projective; + +impl PairingCurve for G1Affine { + type Engine = Bls12_377; + type Prepared = G1Prepared; + type PairWith = G2Affine; + type PairingResult = Fq12; + + fn prepare(&self) -> Self::Prepared { + Self::Prepared::from_affine(*self) + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + Bls12_377::pairing(*self, *other) + } +} + +impl PairingCurve for G2Affine { + type Engine = Bls12_377; + type Prepared = G2Prepared; + type PairWith = G1Affine; + type PairingResult = Fq12; + + fn prepare(&self) -> Self::Prepared { + Self::Prepared::from_affine(*self) + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + Bls12_377::pairing(*other, *self) + } +} diff --git a/algebra/src/curves/bls12_377/tests.rs b/algebra/src/curves/bls12_377/tests.rs new file mode 100644 index 000000000..b256018d9 --- /dev/null +++ b/algebra/src/curves/bls12_377/tests.rs @@ -0,0 +1,146 @@ +#![allow(unused_imports)] +use crate::{ + curves::{ + bls12_377::{ + g1::Bls12_377G1Parameters, Bls12_377, G1Affine, G1Projective, G2Affine, G2Projective, + }, + models::SWModelParameters, + tests::curve_tests, + AffineCurve, PairingEngine, ProjectiveCurve, + }, + fields::{ + bls12_377::{Fq, Fq12, Fq2, Fr}, + Field, FpParameters, PrimeField, SquareRootField, + }, + groups::tests::group_test, +}; +use std::ops::{AddAssign, MulAssign}; + +#[test] +fn test_g1_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g1_projective_group() { + let a: G1Projective = rand::random(); + let b: G1Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g1_generator() { + let generator = G1Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_g2_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g2_projective_group() { + let a: G2Projective = rand::random(); + let b: G2Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g2_generator() { + let generator = G2Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +// #[test] +// fn test_bilinearity() { +// let a: G1Projective = rand::random(); +// let b: G2Projective = rand::random(); +// let s: Fr = rand::random(); +// +// let sa = a * &s; +// let sb = b * &s; +// +// let ans1 = Bls12_377::pairing(sa, b); +// let ans2 = Bls12_377::pairing(a, sb); +// let ans3 = Bls12_377::pairing(a, b).pow(s.into_repr()); +// +// assert_eq!(ans1, ans2); +// assert_eq!(ans2, ans3); +// +// assert_ne!(ans1, Fq12::one()); +// assert_ne!(ans2, Fq12::one()); +// assert_ne!(ans3, Fq12::one()); +// +// assert_eq!(ans1.pow(Fr::characteristic()), Fq12::one()); +// assert_eq!(ans2.pow(Fr::characteristic()), Fq12::one()); +// assert_eq!(ans3.pow(Fr::characteristic()), Fq12::one()); +// } + +#[test] +fn test_bilinearity() { + let a: G1Projective = G1Projective::prime_subgroup_generator(); + let b: G2Projective = G2Projective::prime_subgroup_generator(); + let s: Fr = Fr::one() + &Fr::one(); + + let sa = a * &s; + let sb = b * &s; + + println!("a\n{:?}\n", a.into_affine()); + println!("b\n{:?}\n", b.into_affine()); + println!("s\n{:?}\n", s); + println!("sa\n{:?}\n", sa.into_affine()); + println!("sb\n{:?}\n", sb.into_affine()); + + let ans1 = Bls12_377::pairing(sa, b); + let ans2 = Bls12_377::pairing(a, sb); + + assert_eq!(ans1, ans2); + + assert_ne!(ans1, Fq12::one()); + assert_ne!(ans2, Fq12::one()); + assert_eq!(ans1.pow(Fr::characteristic()), Fq12::one()); + assert_eq!(ans2.pow(Fr::characteristic()), Fq12::one()); +} + +#[test] +fn test_g1_generator_raw() { + let mut x = Fq::zero(); + let mut i = 0; + loop { + // y^2 = x^3 + b + let mut rhs = x; + rhs.square_in_place(); + rhs.mul_assign(&x); + rhs.add_assign(&Bls12_377G1Parameters::COEFF_B); + + if let Some(y) = rhs.sqrt() { + let p = G1Affine::new(x, if y < -y { y } else { -y }, false); + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + + let g1 = p.scale_by_cofactor(); + if !g1.is_zero() { + assert_eq!(i, 1); + let g1 = G1Affine::from(g1); + + assert!(g1.is_in_correct_subgroup_assuming_on_curve()); + + assert_eq!(g1, G1Affine::prime_subgroup_generator()); + break; + } + } + + i += 1; + x.add_assign(&Fq::one()); + } +} + +#[test] +fn bls12_377_unique() { + use crate::fields::bls12_377::fq::Fq; + + use std::str::FromStr; + println!("{}", Fq::from_str("155198655607781456406391640216936120121836107652948796323930557600032281009004493664981332883744016074664192874906").unwrap()); +} diff --git a/algebra/src/curves/bls12_381/g1.rs b/algebra/src/curves/bls12_381/g1.rs new file mode 100644 index 000000000..8c0098d16 --- /dev/null +++ b/algebra/src/curves/bls12_381/g1.rs @@ -0,0 +1,97 @@ +use crate::{ + biginteger::{BigInteger256, BigInteger384}, + curves::{ + bls12::{G1Affine as Bls12G1Affine, G1Prepared, G1Projective as Bls12G1Projective}, + bls12_381::{g2::G2Affine, Bls12_381, Bls12_381Parameters}, + models::{ModelParameters, SWModelParameters}, + PairingCurve, PairingEngine, + }, + fields::{ + bls12_381::{Fq, Fq12, Fr}, + Field, + }, +}; + +pub type G1Affine = Bls12G1Affine; +pub type G1Projective = Bls12G1Projective; + +impl PairingCurve for G1Affine { + type Engine = Bls12_381; + type Prepared = G1Prepared; + type PairWith = G2Affine; + type PairingResult = Fq12; + + fn prepare(&self) -> Self::Prepared { + Self::Prepared::from_affine(*self) + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + Bls12_381::pairing(*self, *other) + } +} + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct Bls12_381G1Parameters; + +impl ModelParameters for Bls12_381G1Parameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl SWModelParameters for Bls12_381G1Parameters { + /// COEFF_A = 0 + const COEFF_A: Fq = Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])); + + /// COEFF_B = 4 + const COEFF_B: Fq = Fq::new(BigInteger384([ + 0xaa270000000cfff3, + 0x53cc0032fc34000a, + 0x478fe97a6b0a807f, + 0xb1d37ebee6ba24d7, + 0x8ec9733bbf78ab2f, + 0x9d645513d83de7e, + ])); + + /// COFACTOR = (x - 1)^2 / 3 = 76329603384216526031706109802092473003 + const COFACTOR: &'static [u64] = &[0x8c00aaab0000aaab, 0x396c8c005555e156]; + + /// COFACTOR_INV = COFACTOR^{-1} mod r + /// = 52435875175126190458656871551744051925719901746859129887267498875565241663483 + const COFACTOR_INV: Fr = Fr::new(BigInteger256([ + 288839107172787499, + 1152722415086798946, + 2612889808468387987, + 5124657601728438008, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G1_GENERATOR_X, G1_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G1_GENERATOR_X, G1_GENERATOR_Y); + + #[inline(always)] + fn mul_by_a(_: &Self::BaseField) -> Self::BaseField { + Self::BaseField::zero() + } +} + +/// G1_GENERATOR_X = +/// 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 +pub const G1_GENERATOR_X: Fq = Fq::new(BigInteger384([ + 0x5cb38790fd530c16, + 0x7817fc679976fff5, + 0x154f95c7143ba1c1, + 0xf0ae6acdf3d0e747, + 0xedce6ecc21dbf440, + 0x120177419e0bfb75, +])); + +/// G1_GENERATOR_Y = +/// 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 +pub const G1_GENERATOR_Y: Fq = Fq::new(BigInteger384([ + 0xbaac93d50ce72271, + 0x8c22631a7918fd8e, + 0xdd595f13570725ce, + 0x51ac582950405194, + 0xe1c8c3fad0059c0, + 0xbbc3efc5008a26a, +])); diff --git a/algebra/src/curves/bls12_381/g2.rs b/algebra/src/curves/bls12_381/g2.rs new file mode 100644 index 000000000..858309aa5 --- /dev/null +++ b/algebra/src/curves/bls12_381/g2.rs @@ -0,0 +1,135 @@ +use crate::{ + biginteger::{BigInteger256, BigInteger384}, + curves::{ + bls12::{G2Affine as Bls12G2Affine, G2Prepared, G2Projective as Bls12G2Projective}, + bls12_381::{ + g1::{Bls12_381G1Parameters, G1Affine}, + Bls12_381, Bls12_381Parameters, + }, + models::{ModelParameters, SWModelParameters}, + PairingCurve, PairingEngine, + }, + fields::{ + bls12_381::{Fq, Fq12, Fq2, Fr}, + Field, + }, +}; + +pub type G2Affine = Bls12G2Affine; +pub type G2Projective = Bls12G2Projective; + +impl PairingCurve for G2Affine { + type Engine = Bls12_381; + type Prepared = G2Prepared; + type PairWith = G1Affine; + type PairingResult = Fq12; + + fn prepare(&self) -> Self::Prepared { + Self::Prepared::from_affine(*self) + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + Bls12_381::pairing(*other, *self) + } +} + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct Bls12_381G2Parameters; + +impl ModelParameters for Bls12_381G2Parameters { + type BaseField = Fq2; + type ScalarField = Fr; +} + +impl SWModelParameters for Bls12_381G2Parameters { + /// COEFF_A = [0, 0] + const COEFF_A: Fq2 = Fq2::new( + Bls12_381G1Parameters::COEFF_A, + Bls12_381G1Parameters::COEFF_A, + ); + + /// COEFF_B = [4, 4] + const COEFF_B: Fq2 = Fq2::new( + Bls12_381G1Parameters::COEFF_B, + Bls12_381G1Parameters::COEFF_B, + ); + + /// COFACTOR = (x^8 - 4 x^7 + 5 x^6) - (4 x^4 + 6 x^3 - 4 x^2 - 4 x + 13) // + /// 9 + /// = 305502333931268344200999753193121504214466019254188142667664032982267604182971884026507427359259977847832272839041616661285803823378372096355777062779109 + const COFACTOR: &'static [u64] = &[ + 0xcf1c38e31c7238e5, + 0x1616ec6e786f0c70, + 0x21537e293a6691ae, + 0xa628f1cb4d9e82ef, + 0xa68a205b2e5a7ddf, + 0xcd91de4547085aba, + 0x91d50792876a202, + 0x5d543a95414e7f1, + ]; + + /// COFACTOR_INV = COFACTOR^{-1} mod r + /// 26652489039290660355457965112010883481355318854675681319708643586776743290055 + const COFACTOR_INV: Fr = Fr::new(BigInteger256([ + 6746407649509787816, + 1304054119431494378, + 2461312685643913071, + 5956596749362435284, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G2_GENERATOR_X, G2_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G2_GENERATOR_X, G2_GENERATOR_Y); + + #[inline(always)] + fn mul_by_a(_: &Self::BaseField) -> Self::BaseField { + Self::BaseField::zero() + } +} + +pub const G2_GENERATOR_X: Fq2 = Fq2::new(G2_GENERATOR_X_C0, G2_GENERATOR_X_C1); +pub const G2_GENERATOR_Y: Fq2 = Fq2::new(G2_GENERATOR_Y_C0, G2_GENERATOR_Y_C1); + +/// G2_GENERATOR_X_C0 = +/// 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160 +pub const G2_GENERATOR_X_C0: Fq = Fq::new(BigInteger384([ + 0xf5f28fa202940a10, + 0xb3f5fb2687b4961a, + 0xa1a893b53e2ae580, + 0x9894999d1a3caee9, + 0x6f67b7631863366b, + 0x58191924350bcd7, +])); + +/// G2_GENERATOR_X_C1 = +/// 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758 +pub const G2_GENERATOR_X_C1: Fq = Fq::new(BigInteger384([ + 0xa5a9c0759e23f606, + 0xaaa0c59dbccd60c3, + 0x3bb17e18e2867806, + 0x1b1ab6cc8541b367, + 0xc2b6ed0ef2158547, + 0x11922a097360edf3, +])); + +/// G2_GENERATOR_Y_C0 = +/// 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 +pub const G2_GENERATOR_Y_C0: Fq = Fq::new(BigInteger384([ + 0x4c730af860494c4a, + 0x597cfa1f5e369c5a, + 0xe7e6856caa0a635a, + 0xbbefb5e96e0d495f, + 0x7d3a975f0ef25a2, + 0x83fd8e7e80dae5, +])); + +/// G2_GENERATOR_Y_C1 = +/// 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582 +pub const G2_GENERATOR_Y_C1: Fq = Fq::new(BigInteger384([ + 0xadc0fc92df64b05d, + 0x18aa270a2b1461dc, + 0x86adac6a3be4eba0, + 0x79495c4ec93da33a, + 0xe7175850a43ccaed, + 0xb2bc2a163de1bf2, +])); diff --git a/algebra/src/curves/bls12_381/mod.rs b/algebra/src/curves/bls12_381/mod.rs new file mode 100644 index 000000000..013f8c6b8 --- /dev/null +++ b/algebra/src/curves/bls12_381/mod.rs @@ -0,0 +1,32 @@ +use crate::{ + curves::bls12::{Bls12, Bls12Parameters, TwistType}, + fields::bls12_381::{Fq, Fq12Parameters, Fq2Parameters, Fq6Parameters}, +}; + +pub mod g1; +pub mod g2; +#[cfg(test)] +mod tests; + +use self::{g1::Bls12_381G1Parameters, g2::Bls12_381G2Parameters}; + +pub use self::{ + g1::{G1Affine, G1Projective}, + g2::{G2Affine, G2Projective}, +}; + +pub type Bls12_381 = Bls12; + +pub struct Bls12_381Parameters; + +impl Bls12Parameters for Bls12_381Parameters { + const X: &'static [u64] = &[0xd201000000010000]; + const X_IS_NEGATIVE: bool = true; + const TWIST_TYPE: TwistType = TwistType::M; + type Fp = Fq; + type Fp2Params = Fq2Parameters; + type Fp6Params = Fq6Parameters; + type Fp12Params = Fq12Parameters; + type G1Parameters = Bls12_381G1Parameters; + type G2Parameters = Bls12_381G2Parameters; +} diff --git a/algebra/src/curves/bls12_381/tests.rs b/algebra/src/curves/bls12_381/tests.rs new file mode 100644 index 000000000..5c23947ae --- /dev/null +++ b/algebra/src/curves/bls12_381/tests.rs @@ -0,0 +1,784 @@ +use crate::{ + biginteger::BigInteger384, + curves::{ + bls12_381::{ + g1::{Bls12_381G1Parameters, G1Affine, G1Projective}, + g2::{Bls12_381G2Parameters, G2Affine, G2Projective}, + Bls12_381, + }, + models::SWModelParameters, + tests::curve_tests, + AffineCurve, PairingEngine, ProjectiveCurve, + }, + fields::{ + bls12_381::{Fq, Fq12, Fq2, Fr}, + Field, PrimeField, SquareRootField, + }, + groups::tests::group_test, +}; +use rand; +use std::ops::{AddAssign, MulAssign}; + +#[test] +fn test_g1_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g1_projective_group() { + let a: G1Projective = rand::random(); + let b: G1Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g1_generator() { + let generator = G1Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_g2_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g2_projective_group() { + let a: G2Projective = rand::random(); + let b: G2Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g2_generator() { + let generator = G2Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_bilinearity() { + let a: G1Projective = rand::random(); + let b: G2Projective = rand::random(); + let s: Fr = rand::random(); + + let sa = a * &s; + let sb = b * &s; + + let ans1 = Bls12_381::pairing(sa, b); + let ans2 = Bls12_381::pairing(a, sb); + let ans3 = Bls12_381::pairing(a, b).pow(s.into_repr()); + + assert_eq!(ans1, ans2); + assert_eq!(ans2, ans3); + + assert_ne!(ans1, Fq12::one()); + assert_ne!(ans2, Fq12::one()); + assert_ne!(ans3, Fq12::one()); + + assert_eq!(ans1.pow(Fr::characteristic()), Fq12::one()); + assert_eq!(ans2.pow(Fr::characteristic()), Fq12::one()); + assert_eq!(ans3.pow(Fr::characteristic()), Fq12::one()); +} + +#[test] +fn test_g1_generator_raw() { + let mut x = Fq::zero(); + let mut i = 0; + loop { + // y^2 = x^3 + b + let mut rhs = x; + rhs.square_in_place(); + rhs.mul_assign(&x); + rhs.add_assign(&Bls12_381G1Parameters::COEFF_B); + + if let Some(y) = rhs.sqrt() { + let p = G1Affine::new(x, if y < -y { y } else { -y }, false); + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + + let g1 = p.scale_by_cofactor(); + if !g1.is_zero() { + assert_eq!(i, 4); + let g1 = G1Affine::from(g1); + + assert!(g1.is_in_correct_subgroup_assuming_on_curve()); + + assert_eq!(g1, G1Affine::prime_subgroup_generator()); + break; + } + } + + i += 1; + x.add_assign(&Fq::one()); + } +} + +#[test] +fn test_g1_is_valid() { + // Reject point on isomorphic twist (b = 24) + { + let p = G1Affine::new( + Fq::from_repr(BigInteger384([ + 0xc58d887b66c035dc, + 0x10cbfd301d553822, + 0xaf23e064f1131ee5, + 0x9fe83b1b4a5d648d, + 0xf583cc5a508f6a40, + 0xc3ad2aefde0bb13, + ])), + Fq::from_repr(BigInteger384([ + 0x60aa6f9552f03aae, + 0xecd01d5181300d35, + 0x8af1cdb8aa8ce167, + 0xe760f57922998c9d, + 0x953703f5795a39e5, + 0xfe3ae0922df702c, + ])), + false, + ); + assert!(!p.is_on_curve()); + assert!(p.is_in_correct_subgroup_assuming_on_curve()); + } + + // Reject point on a twist (b = 3) + { + let p = G1Affine::new( + Fq::from_repr(BigInteger384([ + 0xee6adf83511e15f5, + 0x92ddd328f27a4ba6, + 0xe305bd1ac65adba7, + 0xea034ee2928b30a8, + 0xbd8833dc7c79a7f7, + 0xe45c9f0c0438675, + ])), + Fq::from_repr(BigInteger384([ + 0x3b450eb1ab7b5dad, + 0xa65cb81e975e8675, + 0xaa548682b21726e5, + 0x753ddf21a2601d20, + 0x532d0b640bd3ff8b, + 0x118d2c543f031102, + ])), + false, + ); + assert!(!p.is_on_curve()); + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + } + + // Reject point in an invalid subgroup + // There is only one r-order subgroup, as r does not divide the cofactor. + { + let p = G1Affine::new( + Fq::from_repr(BigInteger384([ + 0x76e1c971c6db8fe8, + 0xe37e1a610eff2f79, + 0x88ae9c499f46f0c0, + 0xf35de9ce0d6b4e84, + 0x265bddd23d1dec54, + 0x12a8778088458308, + ])), + Fq::from_repr(BigInteger384([ + 0x8a22defa0d526256, + 0xc57ca55456fcb9ae, + 0x1ba194e89bab2610, + 0x921beef89d4f29df, + 0x5b6fda44ad85fa78, + 0xed74ab9f302cbe0, + ])), + false, + ); + assert!(p.is_on_curve()); + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + } +} + +#[test] +fn test_g1_addition_correctness() { + let mut p = G1Projective::new( + Fq::from_repr(BigInteger384([ + 0x47fd1f891d6e8bbf, + 0x79a3b0448f31a2aa, + 0x81f3339e5f9968f, + 0x485e77d50a5df10d, + 0x4c6fcac4b55fd479, + 0x86ed4d9906fb064, + ])), + Fq::from_repr(BigInteger384([ + 0xd25ee6461538c65, + 0x9f3bbb2ecd3719b9, + 0xa06fd3f1e540910d, + 0xcefca68333c35288, + 0x570c8005f8573fa6, + 0x152ca696fe034442, + ])), + Fq::one(), + ); + + p.add_assign(&G1Projective::new( + Fq::from_repr(BigInteger384([ + 0xeec78f3096213cbf, + 0xa12beb1fea1056e6, + 0xc286c0211c40dd54, + 0x5f44314ec5e3fb03, + 0x24e8538737c6e675, + 0x8abd623a594fba8, + ])), + Fq::from_repr(BigInteger384([ + 0x6b0528f088bb7044, + 0x2fdeb5c82917ff9e, + 0x9a5181f2fac226ad, + 0xd65104c6f95a872a, + 0x1f2998a5a9c61253, + 0xe74846154a9e44, + ])), + Fq::one(), + )); + + let p = G1Affine::from(p); + + assert_eq!( + p, + G1Affine::new( + Fq::from_repr(BigInteger384([ + 0x6dd3098f22235df, + 0xe865d221c8090260, + 0xeb96bb99fa50779f, + 0xc4f9a52a428e23bb, + 0xd178b28dd4f407ef, + 0x17fb8905e9183c69, + ])), + Fq::from_repr(BigInteger384([ + 0xd0de9d65292b7710, + 0xf6a05f2bcf1d9ca7, + 0x1040e27012f20b64, + 0xeec8d1a5b7466c58, + 0x4bc362649dce6376, + 0x430cbdc5455b00a, + ])), + false, + ) + ); +} + +#[test] +fn test_g1_doubling_correctness() { + let mut p = G1Projective::new( + Fq::from_repr(BigInteger384([ + 0x47fd1f891d6e8bbf, + 0x79a3b0448f31a2aa, + 0x81f3339e5f9968f, + 0x485e77d50a5df10d, + 0x4c6fcac4b55fd479, + 0x86ed4d9906fb064, + ])), + Fq::from_repr(BigInteger384([ + 0xd25ee6461538c65, + 0x9f3bbb2ecd3719b9, + 0xa06fd3f1e540910d, + 0xcefca68333c35288, + 0x570c8005f8573fa6, + 0x152ca696fe034442, + ])), + Fq::one(), + ); + + p.double_in_place(); + + let p = G1Affine::from(p); + + assert_eq!( + p, + G1Affine::new( + Fq::from_repr(BigInteger384([ + 0xf939ddfe0ead7018, + 0x3b03942e732aecb, + 0xce0e9c38fdb11851, + 0x4b914c16687dcde0, + 0x66c8baf177d20533, + 0xaf960cff3d83833, + ])), + Fq::from_repr(BigInteger384([ + 0x3f0675695f5177a8, + 0x2b6d82ae178a1ba0, + 0x9096380dd8e51b11, + 0x1771a65b60572f4e, + 0x8b547c1313b27555, + 0x135075589a687b1e, + ])), + false, + ) + ); +} + +#[test] +fn test_g1_same_y() { + // Test the addition of two points with different x coordinates + // but the same y coordinate. + + // x1 = 128100205326445210408953809171070606737678357140298133325128175840781723996595026100005714405541449960643523234125 + // x2 = 3821408151224848222394078037104966877485040835569514006839342061575586899845797797516352881516922679872117658572470 + // y = 2291134451313223670499022936083127939567618746216464377735567679979105510603740918204953301371880765657042046687078 + + let a = G1Affine::new( + Fq::from_repr(BigInteger384([ + 0xea431f2cc38fc94d, + 0x3ad2354a07f5472b, + 0xfe669f133f16c26a, + 0x71ffa8021531705, + 0x7418d484386d267, + 0xd5108d8ff1fbd6, + ])), + Fq::from_repr(BigInteger384([ + 0xa776ccbfe9981766, + 0x255632964ff40f4a, + 0xc09744e650b00499, + 0x520f74773e74c8c3, + 0x484c8fc982008f0, + 0xee2c3d922008cc6, + ])), + false, + ); + + let b = G1Affine::new( + Fq::from_repr(BigInteger384([ + 0xe06cdb156b6356b6, + 0xd9040b2d75448ad9, + 0xe702f14bb0e2aca5, + 0xc6e05201e5f83991, + 0xf7c75910816f207c, + 0x18d4043e78103106, + ])), + Fq::from_repr(BigInteger384([ + 0xa776ccbfe9981766, + 0x255632964ff40f4a, + 0xc09744e650b00499, + 0x520f74773e74c8c3, + 0x484c8fc982008f0, + 0xee2c3d922008cc6, + ])), + false, + ); + + // Expected + // x = 52901198670373960614757979459866672334163627229195745167587898707663026648445040826329033206551534205133090753192 + // y = 1711275103908443722918766889652776216989264073722543507596490456144926139887096946237734327757134898380852225872709 + let c = G1Affine::new( + Fq::from_repr(BigInteger384([ + 0xef4f05bdd10c8aa8, + 0xad5bf87341a2df9, + 0x81c7424206b78714, + 0x9676ff02ec39c227, + 0x4c12c15d7e55b9f3, + 0x57fd1e317db9bd, + ])), + Fq::from_repr(BigInteger384([ + 0x1288334016679345, + 0xf955cd68615ff0b5, + 0xa6998dbaa600f18a, + 0x1267d70db51049fb, + 0x4696deb9ab2ba3e7, + 0xb1e4e11177f59d4, + ])), + false, + ); + + assert!(a.is_on_curve() && a.is_in_correct_subgroup_assuming_on_curve()); + assert!(b.is_on_curve() && b.is_in_correct_subgroup_assuming_on_curve()); + assert!(c.is_on_curve() && c.is_in_correct_subgroup_assuming_on_curve()); + + let mut tmp1 = a.into_projective(); + tmp1.add_assign(&b.into_projective()); + assert_eq!(tmp1.into_affine(), c); + assert_eq!(tmp1, c.into_projective()); + + let mut tmp2 = a.into_projective(); + tmp2.add_assign_mixed(&b); + assert_eq!(tmp2.into_affine(), c); + assert_eq!(tmp2, c.into_projective()); +} + +#[test] +fn test_g2_generator_raw() { + let mut x = Fq2::zero(); + let mut i = 0; + loop { + // y^2 = x^3 + b + let rhs = (x.square() * &x) + &Bls12_381G2Parameters::COEFF_B; + if let Some(y) = rhs.sqrt() { + let p = G2Affine::new(x, if y < -y { y } else { -y }, false); + + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + + let g2 = p.scale_by_cofactor(); + if !g2.is_zero() { + assert_eq!(i, 2); + let g2 = G2Affine::from(g2); + + assert!(g2.is_in_correct_subgroup_assuming_on_curve()); + assert_eq!(g2, G2Affine::prime_subgroup_generator()); + break; + } + } + + i += 1; + x += &Fq2::one(); + } +} + +#[test] +fn test_g2_is_valid() { + // Reject point on isomorphic twist (b = 3 * (u + 1)) + { + let p = G2Affine::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xa757072d9fa35ba9, + 0xae3fb2fb418f6e8a, + 0xc1598ec46faa0c7c, + 0x7a17a004747e3dbe, + 0xcc65406a7c2e5a73, + 0x10b8c03d64db4d0c, + ])), + Fq::from_repr(BigInteger384([ + 0xd30e70fe2f029778, + 0xda30772df0f5212e, + 0x5b47a9ff9a233a50, + 0xfb777e5b9b568608, + 0x789bac1fec71a2b9, + 0x1342f02e2da54405, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xfe0812043de54dca, + 0xe455171a3d47a646, + 0xa493f36bc20be98a, + 0x663015d9410eb608, + 0x78e82a79d829a544, + 0x40a00545bb3c1e, + ])), + Fq::from_repr(BigInteger384([ + 0x4709802348e79377, + 0xb5ac4dc9204bcfbd, + 0xda361c97d02f42b2, + 0x15008b1dc399e8df, + 0x68128fd0548a3829, + 0x16a613db5c873aaa, + ])), + ), + false, + ); + assert!(!p.is_on_curve()); + assert!(p.is_in_correct_subgroup_assuming_on_curve()); + } + + // Reject point on a twist (b = 2 * (u + 1)) + { + let p = G2Affine::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xf4fdfe95a705f917, + 0xc2914df688233238, + 0x37c6b12cca35a34b, + 0x41abba710d6c692c, + 0xffcc4b2b62ce8484, + 0x6993ec01b8934ed, + ])), + Fq::from_repr(BigInteger384([ + 0xb94e92d5f874e26, + 0x44516408bc115d95, + 0xe93946b290caa591, + 0xa5a0c2b7131f3555, + 0x83800965822367e7, + 0x10cf1d3ad8d90bfa, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xbf00334c79701d97, + 0x4fe714f9ff204f9a, + 0xab70b28002f3d825, + 0x5a9171720e73eb51, + 0x38eb4fd8d658adb7, + 0xb649051bbc1164d, + ])), + Fq::from_repr(BigInteger384([ + 0x9225814253d7df75, + 0xc196c2513477f887, + 0xe05e2fbd15a804e0, + 0x55f2b8efad953e04, + 0x7379345eda55265e, + 0x377f2e6208fd4cb, + ])), + ), + false, + ); + assert!(!p.is_on_curve()); + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + } + + // Reject point in an invalid subgroup + // There is only one r-order subgroup, as r does not divide the cofactor. + { + let p = G2Affine::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x262cea73ea1906c, + 0x2f08540770fabd6, + 0x4ceb92d0a76057be, + 0x2199bc19c48c393d, + 0x4a151b732a6075bf, + 0x17762a3b9108c4a7, + ])), + Fq::from_repr(BigInteger384([ + 0x26f461e944bbd3d1, + 0x298f3189a9cf6ed6, + 0x74328ad8bc2aa150, + 0x7e147f3f9e6e241, + 0x72a9b63583963fff, + 0x158b0083c000462, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x91fb0b225ecf103b, + 0x55d42edc1dc46ba0, + 0x43939b11997b1943, + 0x68cad19430706b4d, + 0x3ccfb97b924dcea8, + 0x1660f93434588f8d, + ])), + Fq::from_repr(BigInteger384([ + 0xaaed3985b6dcb9c7, + 0xc1e985d6d898d9f4, + 0x618bd2ac3271ac42, + 0x3940a2dbb914b529, + 0xbeb88137cf34f3e7, + 0x1699ee577c61b694, + ])), + ), + false, + ); + assert!(p.is_on_curve()); + assert!(!p.is_in_correct_subgroup_assuming_on_curve()); + } +} + +#[test] +fn test_g2_addition_correctness() { + let mut p = G2Projective::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x6c994cc1e303094e, + 0xf034642d2c9e85bd, + 0x275094f1352123a9, + 0x72556c999f3707ac, + 0x4617f2e6774e9711, + 0x100b2fe5bffe030b, + ])), + Fq::from_repr(BigInteger384([ + 0x7a33555977ec608, + 0xe23039d1fe9c0881, + 0x19ce4678aed4fcb5, + 0x4637c4f417667e2e, + 0x93ebe7c3e41f6acc, + 0xde884f89a9a371b, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xe073119472e1eb62, + 0x44fb3391fe3c9c30, + 0xaa9b066d74694006, + 0x25fd427b4122f231, + 0xd83112aace35cae, + 0x191b2432407cbb7f, + ])), + Fq::from_repr(BigInteger384([ + 0xf68ae82fe97662f5, + 0xe986057068b50b7d, + 0x96c30f0411590b48, + 0x9eaa6d19de569196, + 0xf6a03d31e2ec2183, + 0x3bdafaf7ca9b39b, + ])), + ), + Fq2::one(), + ); + + p.add_assign(&G2Projective::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xa8c763d25910bdd3, + 0x408777b30ca3add4, + 0x6115fcc12e2769e, + 0x8e73a96b329ad190, + 0x27c546f75ee1f3ab, + 0xa33d27add5e7e82, + ])), + Fq::from_repr(BigInteger384([ + 0x93b1ebcd54870dfe, + 0xf1578300e1342e11, + 0x8270dca3a912407b, + 0x2089faf462438296, + 0x828e5848cd48ea66, + 0x141ecbac1deb038b, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xf5d2c28857229c3f, + 0x8c1574228757ca23, + 0xe8d8102175f5dc19, + 0x2767032fc37cc31d, + 0xd5ee2aba84fd10fe, + 0x16576ccd3dd0a4e8, + ])), + Fq::from_repr(BigInteger384([ + 0x4da9b6f6a96d1dd2, + 0x9657f7da77f1650e, + 0xbc150712f9ffe6da, + 0x31898db63f87363a, + 0xabab040ddbd097cc, + 0x11ad236b9ba02990, + ])), + ), + Fq2::one(), + )); + + let p = G2Affine::from(p); + + assert_eq!( + p, + G2Affine::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xcde7ee8a3f2ac8af, + 0xfc642eb35975b069, + 0xa7de72b7dd0e64b7, + 0xf1273e6406eef9cc, + 0xababd760ff05cb92, + 0xd7c20456617e89, + ])), + Fq::from_repr(BigInteger384([ + 0xd1a50b8572cbd2b8, + 0x238f0ac6119d07df, + 0x4dbe924fe5fd6ac2, + 0x8b203284c51edf6b, + 0xc8a0b730bbb21f5e, + 0x1a3b59d29a31274, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x9e709e78a8eaa4c9, + 0xd30921c93ec342f4, + 0x6d1ef332486f5e34, + 0x64528ab3863633dc, + 0x159384333d7cba97, + 0x4cb84741f3cafe8, + ])), + Fq::from_repr(BigInteger384([ + 0x242af0dc3640e1a4, + 0xe90a73ad65c66919, + 0x2bd7ca7f4346f9ec, + 0x38528f92b689644d, + 0xb6884deec59fb21f, + 0x3c075d3ec52ba90, + ])), + ), + false, + ) + ); +} + +#[test] +fn test_g2_doubling_correctness() { + let mut p = G2Projective::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x6c994cc1e303094e, + 0xf034642d2c9e85bd, + 0x275094f1352123a9, + 0x72556c999f3707ac, + 0x4617f2e6774e9711, + 0x100b2fe5bffe030b, + ])), + Fq::from_repr(BigInteger384([ + 0x7a33555977ec608, + 0xe23039d1fe9c0881, + 0x19ce4678aed4fcb5, + 0x4637c4f417667e2e, + 0x93ebe7c3e41f6acc, + 0xde884f89a9a371b, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xe073119472e1eb62, + 0x44fb3391fe3c9c30, + 0xaa9b066d74694006, + 0x25fd427b4122f231, + 0xd83112aace35cae, + 0x191b2432407cbb7f, + ])), + Fq::from_repr(BigInteger384([ + 0xf68ae82fe97662f5, + 0xe986057068b50b7d, + 0x96c30f0411590b48, + 0x9eaa6d19de569196, + 0xf6a03d31e2ec2183, + 0x3bdafaf7ca9b39b, + ])), + ), + Fq2::one(), + ); + + p.double_in_place(); + + let p = G2Affine::from(p); + + assert_eq!( + p, + G2Affine::new( + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x91ccb1292727c404, + 0x91a6cb182438fad7, + 0x116aee59434de902, + 0xbcedcfce1e52d986, + 0x9755d4a3926e9862, + 0x18bab73760fd8024, + ])), + Fq::from_repr(BigInteger384([ + 0x4e7c5e0a2ae5b99e, + 0x96e582a27f028961, + 0xc74d1cf4ef2d5926, + 0xeb0cf5e610ef4fe7, + 0x7b4c2bae8db6e70b, + 0xf136e43909fca0, + ])), + ), + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x954d4466ab13e58, + 0x3ee42eec614cf890, + 0x853bb1d28877577e, + 0xa5a2a51f7fde787b, + 0x8b92866bc6384188, + 0x81a53fe531d64ef, + ])), + Fq::from_repr(BigInteger384([ + 0x4c5d607666239b34, + 0xeddb5f48304d14b3, + 0x337167ee6e8e3cb6, + 0xb271f52f12ead742, + 0x244e6c2015c83348, + 0x19e2deae6eb9b441, + ])), + ), + false, + ) + ); +} diff --git a/algebra/src/curves/edwards_bls12/mod.rs b/algebra/src/curves/edwards_bls12/mod.rs new file mode 100644 index 000000000..0e573bdae --- /dev/null +++ b/algebra/src/curves/edwards_bls12/mod.rs @@ -0,0 +1,114 @@ +use crate::{ + biginteger::BigInteger256, + curves::{ + models::{ModelParameters, TEModelParameters}, + twisted_edwards_extended::{GroupAffine, GroupProjective}, + }, + fields::edwards_bls12::{fq::Fq, fr::Fr}, +}; +use std::str::FromStr; + +#[cfg(test)] +mod tests; + +pub type EdwardsAffine = GroupAffine; +pub type EdwardsProjective = GroupProjective; + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct EdwardsParameters; + +impl ModelParameters for EdwardsParameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl TEModelParameters for EdwardsParameters { + /// COEFF_A = -1 + const COEFF_A: Fq = Fq::new(BigInteger256([ + 0x8cf500000000000e, + 0xe75281ef6000000e, + 0x49dc37a90b0ba012, + 0x55f8b2c6e710ab9, + ])); + + /// COEFF_D = 3021 + const COEFF_D: Fq = Fq::new(BigInteger256([ + 0xd047ffffffff5e30, + 0xf0a91026ffff57d2, + 0x9013f560d102582, + 0x9fd242ca7be5700, + ])); + + /// COFACTOR = 4 + const COFACTOR: &'static [u64] = &[4]; + + /// COFACTOR_INV = + /// 527778859339273151515551558673846658209717731602102048798421311598680340096 + const COFACTOR_INV: Fr = Fr::new(BigInteger256([ + 10836190823041854989, + 14880086764632731920, + 5023208332782666747, + 239524813690824359, + ])); + + /// Generated randomly + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = (GENERATOR_X, GENERATOR_Y); + + /// Multiplication by `a` is just negation. + /// Is `a` 1 or -1? + #[inline(always)] + fn mul_by_a(elem: &Self::BaseField) -> Self::BaseField { + -*elem + } +} + +impl FromStr for EdwardsAffine { + type Err = (); + + fn from_str(mut s: &str) -> Result { + s = s.trim(); + if s.is_empty() { + return Err(()); + } + if s.len() < 3 { + return Err(()); + } + if !(s.starts_with('(') && s.ends_with(')')) { + return Err(()); + } + let mut point = Vec::new(); + for substr in s.split(|c| c == '(' || c == ')' || c == ',' || c == ' ') { + if !substr.is_empty() { + point.push(Fq::from_str(substr)?); + } + } + if point.len() != 2 { + return Err(()); + } + let point = EdwardsAffine::new(point[0], point[1]); + + if !point.is_on_curve() { + Err(()) + } else { + Ok(point) + } + } +} + +/// GENERATOR_X = +/// 7810607721416582242904415504650443951498042435501746664987470571546413371306 +const GENERATOR_X: Fq = Fq::new(BigInteger256([ + 0x5bbc9878d817221d, + 0xd2b03489424e720, + 0x6b66f128c16bb3c9, + 0xdd3bff78733576d, +])); + +/// GENERATOR_Y = +/// 1867362672570137759132108893390349941423731440336755218616442213142473202417 +const GENERATOR_Y: Fq = Fq::new(BigInteger256([ + 0x471517ae5e5e979e, + 0xd9c97f6a73a7ff83, + 0x85a95b45a5494402, + 0xfad27c9b545b1f0, +])); diff --git a/algebra/src/curves/edwards_bls12/tests.rs b/algebra/src/curves/edwards_bls12/tests.rs new file mode 100644 index 000000000..6a0e0a284 --- /dev/null +++ b/algebra/src/curves/edwards_bls12/tests.rs @@ -0,0 +1,50 @@ +use crate::{ + curves::{edwards_bls12::*, tests::curve_tests, AffineCurve, ProjectiveCurve}, + groups::tests::group_test, +}; +use rand; + +#[test] +fn test_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_projective_group() { + let a = rand::random(); + let b = rand::random(); + for _i in 0..100 { + group_test::(a, b); + } +} + +#[test] +fn test_affine_group() { + let a: EdwardsAffine = rand::random(); + let b: EdwardsAffine = rand::random(); + for _i in 0..100 { + group_test::(a, b); + } +} + +#[test] +fn test_generator() { + let generator = EdwardsAffine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_conversion() { + let a: EdwardsAffine = rand::random(); + let b: EdwardsAffine = rand::random(); + let a_b = { + use crate::groups::Group; + (a + &b).double().double() + }; + let a_b2 = (a.into_projective() + &b.into_projective()) + .double() + .double(); + assert_eq!(a_b, a_b2.into_affine()); + assert_eq!(a_b.into_projective(), a_b2); +} diff --git a/algebra/src/curves/edwards_sw6/mod.rs b/algebra/src/curves/edwards_sw6/mod.rs new file mode 100644 index 000000000..6b13f6e03 --- /dev/null +++ b/algebra/src/curves/edwards_sw6/mod.rs @@ -0,0 +1,124 @@ +use crate::{ + biginteger::BigInteger384 as BigInteger, + curves::{ + models::{ModelParameters, TEModelParameters}, + twisted_edwards_extended::{GroupAffine, GroupProjective}, + }, + fields::edwards_sw6::{fq::Fq, fr::Fr}, +}; +use std::str::FromStr; + +#[cfg(test)] +mod tests; + +pub type EdwardsAffine = GroupAffine; +pub type EdwardsProjective = GroupProjective; + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct EdwardsParameters; + +impl ModelParameters for EdwardsParameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl TEModelParameters for EdwardsParameters { + /// COEFF_A = -1 = + /// 258664426012969094010652733694893533536393512754914660539884262666720468348340822774968888139573360124440321458176 + const COEFF_A: Fq = Fq::new(BigInteger([ + 9384023879812382873, + 14252412606051516495, + 9184438906438551565, + 11444845376683159689, + 8738795276227363922, + 81297770384137296, + ])); + + /// COEFF_D = 79743 + const COEFF_D: Fq = Fq::new(BigInteger([ + 0x4669ffffff46a638, + 0xa56bbe0a7f9fae05, + 0x403b425466a710b4, + 0xf6648db6ea4e988b, + 0x74d51b5923d35a8d, + 0xf8ed90b17fe903, + ])); + + /// COFACTOR = 8 + const COFACTOR: &'static [u64] = &[8]; + + /// COFACTOR^(-1) mod r = + /// 12124894969357926281749346891948134384518445910386624712788431705725441736421489799867521238554906438478484045560 + const COFACTOR_INV: Fr = Fr::new(BigInteger([ + 7353538464571651976, + 2030910049503177537, + 16726103313845754033, + 1110650741117127777, + 5304838729792721053, + 4975067790294675, + ])); + + /// AFFINE_GENERATOR_COEFFS = (GENERATOR_X, GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = (GENERATOR_X, GENERATOR_Y); + + /// Multiplication by `a` is just negation. + #[inline(always)] + fn mul_by_a(elem: &Self::BaseField) -> Self::BaseField { + -*elem + } +} + +impl FromStr for EdwardsAffine { + type Err = (); + + fn from_str(mut s: &str) -> Result { + s = s.trim(); + if s.is_empty() { + return Err(()); + } + if s.len() < 3 { + return Err(()); + } + if !(s.starts_with('(') && s.ends_with(')')) { + return Err(()); + } + let mut point = Vec::new(); + for substr in s.split(|c| c == '(' || c == ')' || c == ',' || c == ' ') { + if !substr.is_empty() { + point.push(Fq::from_str(substr)?); + } + } + if point.len() != 2 { + return Err(()); + } + let point = EdwardsAffine::new(point[0], point[1]); + + if !point.is_on_curve() { + Err(()) + } else { + Ok(point) + } + } +} + +/// GENERATOR_X = +/// 174701772324485506941690903512423551998294352968833659960042362742684869862495746426366187462669992073196420267127 +const GENERATOR_X: Fq = Fq::new(BigInteger([ + 3737364149926089590, + 13002967008679663837, + 9954144214462864555, + 3365719140389487049, + 8643066672427471196, + 120355578793479865, +])); + +/// GENERATOR_Y = +/// 208487200052258845495340374451540775445408439654930191324011635560142523886549663106522691296420655144190624954833 +const GENERATOR_Y: Fq = Fq::new(BigInteger([ + 6027299446526298157, + 12854429557810467099, + 11207279014226687864, + 17040621363687352702, + 6112671509202865855, + 44040319652922447, +])); diff --git a/algebra/src/curves/edwards_sw6/tests.rs b/algebra/src/curves/edwards_sw6/tests.rs new file mode 100644 index 000000000..c439ef1ad --- /dev/null +++ b/algebra/src/curves/edwards_sw6/tests.rs @@ -0,0 +1,50 @@ +use crate::{ + curves::{edwards_sw6::*, tests::curve_tests, AffineCurve, ProjectiveCurve}, + groups::tests::group_test, +}; +use rand; + +#[test] +fn test_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_projective_group() { + let a = rand::random(); + let b = rand::random(); + for _i in 0..100 { + group_test::(a, b); + } +} + +#[test] +fn test_affine_group() { + let a: EdwardsAffine = rand::random(); + let b: EdwardsAffine = rand::random(); + for _i in 0..100 { + group_test::(a, b); + } +} + +#[test] +fn test_generator() { + let generator = EdwardsAffine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_conversion() { + let a: EdwardsAffine = rand::random(); + let b: EdwardsAffine = rand::random(); + let a_b = { + use crate::groups::Group; + (a + &b).double().double() + }; + let a_b2 = (a.into_projective() + &b.into_projective()) + .double() + .double(); + assert_eq!(a_b, a_b2.into_affine()); + assert_eq!(a_b.into_projective(), a_b2); +} diff --git a/algebra/src/curves/jubjub/mod.rs b/algebra/src/curves/jubjub/mod.rs new file mode 100644 index 000000000..dff77f1ec --- /dev/null +++ b/algebra/src/curves/jubjub/mod.rs @@ -0,0 +1,129 @@ +use crate::{ + biginteger::BigInteger256, + curves::{ + models::{ModelParameters, TEModelParameters}, + twisted_edwards_extended::{GroupAffine, GroupProjective}, + }, + fields::jubjub::{fq::Fq, fr::Fr}, +}; +use std::str::FromStr; + +#[cfg(test)] +mod tests; + +pub type JubJubAffine = GroupAffine; +pub type JubJubProjective = GroupProjective; + +const GENERATOR_X: Fq = Fq::new(BigInteger256([ + 14080349899812819339, + 4104857150246327429, + 8293216003873356624, + 7400363483732984990, +])); +const GENERATOR_Y: Fq = Fq::new(BigInteger256([ + 13388310974700241893, + 7654361511478576605, + 8037907163910805792, + 5188938133920569885, +])); + +/// `JubJub` is a twisted Edwards curve. These curves have equations of the +/// form: ax² + y² = 1 - dx²y². +/// over some base finite field Fq. +/// +/// JubJub's curve equation: -x² + y² = 1 - (10240/10241)x²y² +/// +/// q = 52435875175126190479447740508185965837690552500527637822603658699938581184513. +/// +/// a = -1. +/// d = (10240/10241) mod q +/// = 19257038036680949359750312669786877991949435402254120286184196891950884077233. +/// +/// Sage script to calculate these: +/// +/// ```text +/// q = 52435875175126190479447740508185965837690552500527637822603658699938581184513 +/// Fq = GF(q) +/// d = -(Fq(10240)/Fq(10241)) +/// ``` +/// These parameters and the sage script obtained from: +/// +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct JubJubParameters; + +impl ModelParameters for JubJubParameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl TEModelParameters for JubJubParameters { + /// COEFF_A = -1 + const COEFF_A: Fq = Fq::new(BigInteger256([ + 18446744060824649731, + 18102478225614246908, + 11073656695919314959, + 6613806504683796440, + ])); + + /// COEFF_D = (10240/10241) mod q + const COEFF_D: Fq = Fq::new(BigInteger256([ + 3049539848285517488, + 18189135023605205683, + 8793554888777148625, + 6339087681201251886, + ])); + + /// COFACTOR = 8 + const COFACTOR: &'static [u64] = &[8]; + + /// COFACTOR^(-1) mod r = + /// 819310549611346726241370945440405716213240158234039660170669895299022906775 + const COFACTOR_INV: Fr = Fr::new(BigInteger256([ + 6832491983681988242, + 12911748493335322362, + 17523939349049608702, + 217463794347581613, + ])); + + /// AFFINE_GENERATOR_COEFFS = (GENERATOR_X, GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = (GENERATOR_X, GENERATOR_Y); + + /// Multiplication by `a` is simply negation here. + #[inline(always)] + fn mul_by_a(elem: &Self::BaseField) -> Self::BaseField { + -(*elem) + } +} + +impl FromStr for JubJubAffine { + type Err = (); + + fn from_str(mut s: &str) -> Result { + s = s.trim(); + if s.is_empty() { + return Err(()); + } + if s.len() < 3 { + return Err(()); + } + if !(s.starts_with('(') && s.ends_with(')')) { + return Err(()); + } + let mut point = Vec::new(); + for substr in s.split(|c| c == '(' || c == ')' || c == ',' || c == ' ') { + if !substr.is_empty() { + point.push(Fq::from_str(substr)?); + } + } + if point.len() != 2 { + return Err(()); + } + let point = JubJubAffine::new(point[0], point[1]); + + if !point.is_on_curve() { + Err(()) + } else { + Ok(point) + } + } +} diff --git a/algebra/src/curves/jubjub/tests.rs b/algebra/src/curves/jubjub/tests.rs new file mode 100644 index 000000000..21248cf57 --- /dev/null +++ b/algebra/src/curves/jubjub/tests.rs @@ -0,0 +1,104 @@ +use crate::{ + bytes::{FromBytes, ToBytes}, + curves::{jubjub::*, tests::curve_tests, AffineCurve, ProjectiveCurve}, + fields::jubjub::fr::Fr, + groups::tests::group_test, +}; +use rand; +use std::str::FromStr; + +#[test] +fn test_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_projective_group() { + let a = rand::random(); + let b = rand::random(); + for _i in 0..100 { + group_test::(a, b); + } +} + +#[test] +fn test_affine_group() { + let a: JubJubAffine = rand::random(); + let b: JubJubAffine = rand::random(); + for _i in 0..100 { + group_test::(a, b); + } +} + +#[test] +fn test_generator() { + let generator = JubJubAffine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_conversion() { + let a: JubJubAffine = rand::random(); + let b: JubJubAffine = rand::random(); + let a_b = { + use crate::groups::Group; + (a + &b).double().double() + }; + let a_b2 = (a.into_projective() + &b.into_projective()) + .double() + .double(); + assert_eq!(a_b, a_b2.into_affine()); + assert_eq!(a_b.into_projective(), a_b2); +} + +#[test] +fn test_scalar_multiplication() { + println!("Started getting field elements"); + let f1 = Fr::from_str( + "4691331900926794624732159288782398864809513177368446695323460897088210774597", + ) + .unwrap(); + let f2 = Fr::from_str( + "1305028103380024953477151132159456965337646722479526711736847301646466538045", + ) + .unwrap(); + + println!("Finished getting field elements"); + let g = JubJubAffine::from_str( + "(1158870117176967269192899343636553522971009777237254192973081388797299308391, \ + 36933624999642413792569726058244472742169727126562409632889593958355839948294)", + ) + .unwrap(); + let f1f2g = JubJubAffine::from_str( + "(12638652891150111215300246576936483137884466359309882317048163368620501191944, \ + 38385045634663742820428406709832518145724237919360177362175527604556651918148)", + ) + .unwrap(); + + println!("Finished getting group elements"); + + assert!(!g.is_zero()); + assert!(!f1f2g.is_zero()); + + let f1g = g * &f1; + println!("f1: {:?}", f1); + println!("f2: {:?}", f2); + println!("g: {:?}", g); + println!("f1f2g: {:?}", f1f2g); + assert_eq!(g * &(f1 * &f2), f1f2g); + assert_eq!(f1g * &f2, f1f2g); +} + +#[test] +fn test_bytes() { + let g_from_repr = JubJubAffine::from_str( + "(1158870117176967269192899343636553522971009777237254192973081388797299308391, \ + 36933624999642413792569726058244472742169727126562409632889593958355839948294)", + ) + .unwrap(); + + let g_bytes = to_bytes![g_from_repr].unwrap(); + let g = JubJubAffine::read(g_bytes.as_slice()).unwrap(); + assert_eq!(g_from_repr, g); +} diff --git a/algebra/src/curves/mnt6/g1.rs b/algebra/src/curves/mnt6/g1.rs new file mode 100644 index 000000000..f9990b625 --- /dev/null +++ b/algebra/src/curves/mnt6/g1.rs @@ -0,0 +1,122 @@ +use crate::{ + biginteger::BigInteger320, + bytes::ToBytes, + curves::{ + mnt6::{G2Affine, MNT6}, + models::{ModelParameters, SWModelParameters}, + short_weierstrass_projective::{GroupAffine, GroupProjective}, + AffineCurve, PairingCurve, PairingEngine, + }, + fields::mnt6::{Fq, Fq3, Fq6, Fr}, +}; +use std::io::{Result as IoResult, Write}; + +pub type G1Affine = GroupAffine; +pub type G1Projective = GroupProjective; + +impl PairingCurve for G1Affine { + type Engine = MNT6; + type Prepared = G1Prepared; + type PairWith = G2Affine; + type PairingResult = Fq6; + + fn prepare(&self) -> Self::Prepared { + Self::Prepared::from_affine(self) + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + MNT6::pairing(*self, *other) + } +} + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct MNT6G1Parameters; + +impl ModelParameters for MNT6G1Parameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl SWModelParameters for MNT6G1Parameters { + /// COEFF_A = + const COEFF_A: Fq = Fq::new(BigInteger320([ + 0xb9b2411bfd0eafef, + 0xc61a10fadd9fecbd, + 0x89f128e59811f3fb, + 0x980c0f780adadabb, + 0x9ba1f11320, + ])); + + /// COEFF_B = + const COEFF_B: Fq = Fq::new(BigInteger320([ + 0xa94cb16ed8e733b, + 0xe1ed15e8119bae6, + 0xae927592157c8121, + 0x990dbcbc6661cf95, + 0xecff0892ef, + ])); + + /// COFACTOR = 1 + const COFACTOR: &'static [u64] = &[1]; + + /// COFACTOR^(-1) mod r = + /// 1 + const COFACTOR_INV: Fr = Fr::new(BigInteger320([ + 1784298994435064924, + 16852041090100268533, + 14258261760832875328, + 2961187778261111191, + 1929014752195, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G1_GENERATOR_X, G1_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G1_GENERATOR_X, G1_GENERATOR_Y); +} + +/// G1_GENERATOR_X = +pub const G1_GENERATOR_X: Fq = Fq::new(BigInteger320([ + 0x1a663562f74e1d24, + 0xc1d1d583fccd1b79, + 0xda077538a9763df2, + 0x70c4a4ea36aa01d9, + 0x86537578a8, +])); + +/// G1_GENERATOR_Y = +pub const G1_GENERATOR_Y: Fq = Fq::new(BigInteger320([ + 0x7ad5bfd16dcfffb2, + 0x88dd739252215070, + 0x43f137a8b517b339, + 0x9a7fac709a8c463c, + 0x3140fbc3593, +])); + +#[derive(Eq, PartialEq, Copy, Clone, Debug)] +pub struct G1Prepared { + pub x: Fq, + pub y: Fq, + pub x_twist: Fq3, + pub y_twist: Fq3, +} + +impl ToBytes for G1Prepared { + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer)?; + self.x_twist.write(&mut writer)?; + self.y_twist.write(&mut writer) + } +} + +impl G1Prepared { + pub fn from_affine(point: &G1Affine) -> Self { + MNT6::ate_precompute_g1(&point.into_projective()) + } +} + +impl Default for G1Prepared { + fn default() -> Self { + Self::from_affine(&G1Affine::prime_subgroup_generator()) + } +} diff --git a/algebra/src/curves/mnt6/g2.rs b/algebra/src/curves/mnt6/g2.rs new file mode 100644 index 000000000..af13da23c --- /dev/null +++ b/algebra/src/curves/mnt6/g2.rs @@ -0,0 +1,214 @@ +use crate::{ + biginteger::BigInteger320, + bytes::ToBytes, + curves::{ + mnt6::{g1::MNT6G1Parameters, G1Affine, MNT6, TWIST_COEFF_A}, + models::{ModelParameters, SWModelParameters}, + short_weierstrass_projective::{GroupAffine, GroupProjective}, + AffineCurve, PairingCurve, PairingEngine, + }, + fields::mnt6::{Fq, Fq3, Fq6, Fr}, +}; +use std::io::{Result as IoResult, Write}; + +pub type G2Affine = GroupAffine; +pub type G2Projective = GroupProjective; + +impl PairingCurve for G2Affine { + type Engine = MNT6; + type Prepared = G2Prepared; + type PairWith = G1Affine; + type PairingResult = Fq6; + + #[inline(always)] + fn prepare(&self) -> Self::Prepared { + Self::Prepared::from_affine(self) + } + + #[inline(always)] + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + MNT6::pairing(*other, *self) + } +} + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct MNT6G2Parameters; + +impl ModelParameters for MNT6G2Parameters { + type BaseField = Fq3; + type ScalarField = Fr; +} + +/// MUL_BY_A_C0 = NONRESIDUE * COEFF_A +pub const MUL_BY_A_C0: Fq = Fq::new(BigInteger320([ + 0xa07b458bf1496fab, + 0xde8254e6541f9fb4, + 0xb1b5cc7bf859c3ea, + 0xf83c4d58364645a9, + 0x30a29b55fa2, +])); + +/// MUL_BY_A_C1 = NONRESIDUE * COEFF_A +pub const MUL_BY_A_C1: Fq = Fq::new(BigInteger320([ + 0xa07b458bf1496fab, + 0xde8254e6541f9fb4, + 0xb1b5cc7bf859c3ea, + 0xf83c4d58364645a9, + 0x30a29b55fa2, +])); + +/// MUL_BY_A_C2 = COEFF_A +pub const MUL_BY_A_C2: Fq = MNT6G1Parameters::COEFF_A; + +impl SWModelParameters for MNT6G2Parameters { + const COEFF_A: Fq3 = TWIST_COEFF_A; + const COEFF_B: Fq3 = Fq3::new( + Fq::new(BigInteger320([ + 0x79a4c2cea3c84026, + 0x4b50cad0f3233baa, + 0x9ded82770e7a4410, + 0x5ade8b105838b95d, + 0xe4036e0a3a, + ])), + Fq::new(BigInteger320([0, 0, 0, 0, 0])), + Fq::new(BigInteger320([0, 0, 0, 0, 0])), + ); + + /// COFACTOR = + /// 226502022472576270196498690498308461791828762732602586162207535351960270082712694977333372361549082214519252261735048131889018501404377856786623430385820659037970876666767495659520 + const COFACTOR: &'static [u64] = &[ + 15308190245346869248, + 10669098443577192943, + 4561413759929581409, + 3680089780298582849, + 17336300687782721465, + 10745756320947240891, + 17479264233688728128, + 16828697388537672097, + 4184034152442024798, + 915787, + ]; + + /// COFACTOR^(-1) mod r = + /// 79320381028210220958891541608841408590854146655427655872973753568875979721417185067925504 + const COFACTOR_INV: Fr = Fr::new(BigInteger320([ + 5837598184463018016, + 7845868194417674836, + 12170332588914158076, + 6950611683754678431, + 102280178745, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G2_GENERATOR_X, G2_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G2_GENERATOR_X, G2_GENERATOR_Y); + + #[inline(always)] + fn mul_by_a(elt: &Fq3) -> Fq3 { + Fq3::new( + MUL_BY_A_C0 * &elt.c1, + MUL_BY_A_C1 * &elt.c2, + MUL_BY_A_C2 * &elt.c0, + ) + } +} + +const G2_GENERATOR_X: Fq3 = Fq3::new(G2_GENERATOR_X_C0, G2_GENERATOR_X_C1, G2_GENERATOR_X_C2); +const G2_GENERATOR_Y: Fq3 = Fq3::new(G2_GENERATOR_Y_C0, G2_GENERATOR_Y_C1, G2_GENERATOR_Y_C2); + +pub const G2_GENERATOR_X_C0: Fq = Fq::new(BigInteger320([ + 0x15ca12fc5d551ea7, + 0x9e0b2b2b2bb8b979, + 0xe6e66283ad5a786a, + 0x46ba0aedcc383c07, + 0x243853463ed, +])); + +pub const G2_GENERATOR_X_C1: Fq = Fq::new(BigInteger320([ + 0x2c0e3dd7be176130, + 0x27a15d879495904b, + 0x6f1f0d2dd1502a82, + 0x9782ee3c70834da, + 0x2c28bb71862, +])); + +pub const G2_GENERATOR_X_C2: Fq = Fq::new(BigInteger320([ + 0xf3e5f4eb9631e1f1, + 0x657801e80c50778, + 0x2d2abb128fee90f3, + 0x72e58e4c3aa3598c, + 0x100b8026b9d, +])); + +pub const G2_GENERATOR_Y_C0: Fq = Fq::new(BigInteger320([ + 0xb1cddd6c64a67c5f, + 0xa01e90d89aa5d2ba, + 0x39e9a733be49ed1, + 0x9438f46f63d3264f, + 0x12cc928ef10, +])); + +pub const G2_GENERATOR_Y_C1: Fq = Fq::new(BigInteger320([ + 0xa1529b7265ad4be7, + 0x21c5e827cf309306, + 0x9b3d647bd8c70b22, + 0x42835bf373e4b213, + 0xd3c77c9ff9, +])); + +pub const G2_GENERATOR_Y_C2: Fq = Fq::new(BigInteger320([ + 0x610557ec4b58b8df, + 0x51a23865b52045f1, + 0x9dcfd915a09da608, + 0x6d65c95f69adb700, + 0x2d3c3d195a1, +])); + +#[derive(Eq, PartialEq, Clone, Debug)] +pub struct G2Prepared { + pub x: Fq3, + pub y: Fq3, + pub x_over_twist: Fq3, + pub y_over_twist: Fq3, + pub double_coefficients: Vec, + pub addition_coefficients: Vec, +} + +impl ToBytes for G2Prepared { + fn write(&self, _writer: W) -> IoResult<()> { + unimplemented!() + } +} + +impl G2Prepared { + pub fn from_affine(point: &G2Affine) -> Self { + MNT6::ate_precompute_g2(&point.into_projective()) + } +} + +impl Default for G2Prepared { + fn default() -> Self { + Self::from_affine(&G2Affine::prime_subgroup_generator()) + } +} + +pub(super) struct G2ProjectiveExtended { + pub(crate) x: Fq3, + pub(crate) y: Fq3, + pub(crate) z: Fq3, + pub(crate) t: Fq3, +} + +#[derive(Eq, PartialEq, Copy, Clone, Debug)] +pub struct AteDoubleCoefficients { + pub(crate) c_h: Fq3, + pub(crate) c_4c: Fq3, + pub(crate) c_j: Fq3, + pub(crate) c_l: Fq3, +} + +#[derive(Eq, PartialEq, Copy, Clone, Debug)] +pub struct AteAdditionCoefficients { + pub(crate) c_l1: Fq3, + pub(crate) c_rz: Fq3, +} diff --git a/algebra/src/curves/mnt6/mod.rs b/algebra/src/curves/mnt6/mod.rs new file mode 100644 index 000000000..49320a68b --- /dev/null +++ b/algebra/src/curves/mnt6/mod.rs @@ -0,0 +1,325 @@ +use crate::{ + biginteger::BigInteger320, + curves::{PairingCurve, PairingEngine, ProjectiveCurve}, + fields::{ + mnt6::{ + fq::{Fq, FqParameters}, + Fq3, Fq6, Fr, + }, + BitIterator, Field, FpParameters, + }, +}; + +pub mod g1; +pub mod g2; +#[cfg(test)] +mod tests; + +use self::g2::{AteAdditionCoefficients, AteDoubleCoefficients, G2ProjectiveExtended}; +pub use self::{ + g1::{G1Affine, G1Prepared, G1Projective}, + g2::{G2Affine, G2Prepared, G2Projective}, +}; + +pub type GT = Fq6; + +#[derive(Copy, Clone, Debug)] +pub struct MNT6; + +impl PairingEngine for MNT6 { + type Fr = Fr; + type G1Projective = G1Projective; + type G1Affine = G1Affine; + type G2Projective = G2Projective; + type G2Affine = G2Affine; + type Fq = Fq; + type Fqe = Fq3; + type Fqk = Fq6; + + fn miller_loop<'a, I>(i: I) -> Self::Fqk + where + I: IntoIterator< + Item = &'a ( + &'a ::Prepared, + &'a ::Prepared, + ), + >, + { + let mut result = Self::Fqk::one(); + for &(ref p, ref q) in i { + result *= &MNT6::ate_miller_loop(p, q); + } + result + } + + fn final_exponentiation(r: &Self::Fqk) -> Option { + Some(MNT6::final_exponentiation(r)) + } +} + +impl MNT6 { + /// Takes as input a point in G1 in projective coordinates, and outputs a + /// precomputed version of it for pairing purposes. + fn ate_precompute_g1(value: &G1Projective) -> G1Prepared { + let g1 = value.into_affine(); + + let mut x_twist = TWIST.clone(); + x_twist.mul_assign_by_fp(&g1.x); + + let mut y_twist = TWIST.clone(); + y_twist.mul_assign_by_fp(&g1.y); + + G1Prepared { + x: g1.x, + y: g1.y, + x_twist, + y_twist, + } + } + + /// Takes as input a point in `G2` in projective coordinates, and outputs a + /// precomputed version of it for pairing purposes. + fn ate_precompute_g2(value: &G2Projective) -> G2Prepared { + let g2 = value.into_affine(); + + let twist_inv = TWIST.inverse().unwrap(); + + let mut g2p = G2Prepared { + x: g2.x, + y: g2.y, + x_over_twist: g2.x * &twist_inv, + y_over_twist: g2.y * &twist_inv, + double_coefficients: vec![], + addition_coefficients: vec![], + }; + + let mut r = G2ProjectiveExtended { + x: g2.x, + y: g2.y, + z: Fq3::one(), + t: Fq3::one(), + }; + + for (idx, value) in ATE_LOOP_COUNT.iter().rev().enumerate() { + let mut tmp = *value; + let skip_extraneous_bits = 64 - value.leading_zeros(); + let mut v = Vec::with_capacity(16); + for i in 0..64 { + if idx == 0 && (i == 0 || i >= skip_extraneous_bits) { + continue; + } + v.push(tmp & 1 == 1); + tmp >>= 1; + } + + for bit in v.iter().rev() { + let (r2, coeff) = MNT6::doubling_step_for_flipped_miller_loop(&r); + g2p.double_coefficients.push(coeff); + r = r2; + + if *bit { + let (r2, coeff) = + MNT6::mixed_addition_step_for_flipped_miller_loop(&g2.x, &g2.y, &r); + g2p.addition_coefficients.push(coeff); + r = r2; + } + + tmp >>= 1; + } + } + + if ATE_IS_LOOP_COUNT_NEG { + let rz_inv = r.z.inverse().unwrap(); + let rz2_inv = rz_inv.square(); + let rz3_inv = rz_inv * &rz2_inv; + + let minus_r_affine_x = r.x * &rz2_inv; + let minus_r_affine_y = -r.y * &rz3_inv; + + let add_result = MNT6::mixed_addition_step_for_flipped_miller_loop( + &minus_r_affine_x, + &minus_r_affine_y, + &r, + ); + g2p.addition_coefficients.push(add_result.1); + } + + g2p + } + + fn doubling_step_for_flipped_miller_loop( + r: &G2ProjectiveExtended, + ) -> (G2ProjectiveExtended, AteDoubleCoefficients) { + let a = r.t.square(); + let b = r.x.square(); + let c = r.y.square(); + let d = c.square(); + let e = (r.x + &c).square() - &b - &d; + let f = (b + &b + &b) + &(TWIST_COEFF_A * &a); + let g = f.square(); + + let d_eight = d.double().double().double(); + + let x = -(e + &e + &e + &e) + &g; + let y = -d_eight + &(f * &(e + &e - &x)); + let z = (r.y + &r.z).square() - &c - &r.z.square(); + let t = z.square(); + + let r2 = G2ProjectiveExtended { x, y, z, t }; + let coeff = AteDoubleCoefficients { + c_h: (r2.z + &r.t).square() - &r2.t - &a, + c_4c: c + &c + &c + &c, + c_j: (f + &r.t).square() - &g - &a, + c_l: (f + &r.x).square() - &g - &b, + }; + + (r2, coeff) + } + + fn mixed_addition_step_for_flipped_miller_loop( + x: &Fq3, + y: &Fq3, + r: &G2ProjectiveExtended, + ) -> (G2ProjectiveExtended, AteAdditionCoefficients) { + let a = y.square(); + let b = r.t * x; + let d = ((r.z + y).square() - &a - &r.t) * &r.t; + let h = b - &r.x; + let i = h.square(); + let e = i + &i + &i + &i; + let j = h * &e; + let v = r.x * &e; + let l1 = d - &(r.y + &r.y); + + let x = l1.square() - &j - &(v + &v); + let y = l1 * &(v - &x) - &(j * &(r.y + &r.y)); + let z = (r.z + &h).square() - &r.t - &i; + let t = z.square(); + + let r2 = G2ProjectiveExtended { x, y, z, t }; + let coeff = AteAdditionCoefficients { c_l1: l1, c_rz: z }; + + (r2, coeff) + } + + pub fn ate_miller_loop(p: &G1Prepared, q: &G2Prepared) -> Fq6 { + let l1_coeff = Fq3::new(p.x, Fq::zero(), Fq::zero()) - &q.x_over_twist; + + let mut f = Fq6::one(); + + let mut dbl_idx: usize = 0; + let mut add_idx: usize = 0; + + let mut found_one = false; + + for bit in BitIterator::new(ATE_LOOP_COUNT) { + // code below gets executed for all bits (EXCEPT the MSB itself) of + // mnt6_param_p (skipping leading zeros) in MSB to LSB order + if !found_one && bit { + found_one = true; + continue; + } else if !found_one { + continue; + } + + let dc = &q.double_coefficients[dbl_idx]; + dbl_idx += 1; + + let g_rr_at_p = Fq6::new( + -dc.c_4c - &(dc.c_j * &p.x_twist) + &dc.c_l, + dc.c_h * &p.y_twist, + ); + + f = f.square() * &g_rr_at_p; + + if bit { + let ac = &q.addition_coefficients[add_idx]; + add_idx += 1; + + let g_rq_at_p = Fq6::new( + ac.c_rz * &p.y_twist, + -(q.y_over_twist * &ac.c_rz + &(l1_coeff * &ac.c_l1)), + ); + f = f * &g_rq_at_p; + } + } + + if ATE_IS_LOOP_COUNT_NEG { + let ac = &q.addition_coefficients[add_idx]; + + let g_rnegr_at_p = Fq6::new( + ac.c_rz * &p.y_twist, + -(q.y_over_twist * &ac.c_rz + &(l1_coeff * &ac.c_l1)), + ); + f = (f * &g_rnegr_at_p).inverse().unwrap(); + } + + f + } + + pub fn final_exponentiation(value: &Fq6) -> GT { + let value_inv = value.inverse().unwrap(); + let value_to_first_chunk = MNT6::final_exponentiation_first_chunk(value, &value_inv); + let value_inv_to_first_chunk = MNT6::final_exponentiation_first_chunk(&value_inv, value); + MNT6::final_exponentiation_last_chunk(&value_to_first_chunk, &value_inv_to_first_chunk) + } + + fn final_exponentiation_first_chunk(elt: &Fq6, elt_inv: &Fq6) -> Fq6 { + // (q^3-1)*(q+1) + + // elt_q3 = elt^(q^3) + let mut elt_q3 = elt.clone(); + elt_q3.frobenius_map(3); + // elt_q3_over_elt = elt^(q^3-1) + let elt_q3_over_elt = elt_q3 * &elt_inv; + // alpha = elt^((q^3-1) * q) + let mut alpha = elt_q3_over_elt.clone(); + alpha.frobenius_map(1); + // beta = elt^((q^3-1)*(q+1) + alpha * &elt_q3_over_elt + } + + fn final_exponentiation_last_chunk(elt: &Fq6, elt_inv: &Fq6) -> Fq6 { + let elt_clone = elt.clone(); + let elt_inv_clone = elt_inv.clone(); + + let mut elt_q = elt.clone(); + elt_q.frobenius_map(1); + + let w1_part = elt_q.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_1); + let w0_part; + if FINAL_EXPONENT_LAST_CHUNK_W0_IS_NEG { + w0_part = elt_inv_clone.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0); + } else { + w0_part = elt_clone.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0); + } + + w1_part * &w0_part + } +} + +pub const TWIST: Fq3 = Fq3::new(FQ_ZERO, FQ_ONE, FQ_ZERO); +pub const FQ_ZERO: Fq = Fq::new(BigInteger320([0, 0, 0, 0, 0])); +pub const FQ_ONE: Fq = Fq::new(FqParameters::R); +pub const TWIST_COEFF_A: Fq3 = Fq3::new( + FQ_ZERO, + FQ_ZERO, + Fq::new(BigInteger320([ + 0xb9b2411bfd0eafef, + 0xc61a10fadd9fecbd, + 0x89f128e59811f3fb, + 0x980c0f780adadabb, + 0x9ba1f11320, + ])), +); + +pub const ATE_LOOP_COUNT: [u64; 3] = [0xdc9a1b671660000, 0x46609756bec2a33f, 0x1eef55]; + +pub const ATE_IS_LOOP_COUNT_NEG: bool = true; + +pub const FINAL_EXPONENT_LAST_CHUNK_1: BigInteger320 = BigInteger320([0x1, 0x0, 0x0, 0x0, 0x0]); + +pub const FINAL_EXPONENT_LAST_CHUNK_W0_IS_NEG: bool = true; + +pub const FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0: BigInteger320 = + BigInteger320([0xdc9a1b671660000, 0x46609756bec2a33f, 0x1eef55, 0x0, 0x0]); diff --git a/algebra/src/curves/mnt6/tests.rs b/algebra/src/curves/mnt6/tests.rs new file mode 100644 index 000000000..7138ada2c --- /dev/null +++ b/algebra/src/curves/mnt6/tests.rs @@ -0,0 +1,75 @@ +use crate::{ + curves::{ + mnt6::{G1Affine, G1Projective, G2Affine, G2Projective, MNT6}, + tests::curve_tests, + AffineCurve, PairingEngine, + }, + fields::mnt6::fr::Fr, + groups::tests::group_test, +}; +use rand; + +#[test] +fn test_g1_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g1_projective_group() { + let a: G1Projective = rand::random(); + let b: G1Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g1_generator() { + let generator = G1Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_g2_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g2_projective_group() { + let a: G2Projective = rand::random(); + let b: G2Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g2_generator() { + let generator = G2Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_bilinearity() { + use crate::fields::{mnt6::fq6::Fq6, Field, PrimeField}; + + let a: G1Projective = rand::random(); + let b: G2Projective = rand::random(); + let s: Fr = rand::random(); + + let sa = a * &s; + let sb = b * &s; + + let ans1 = MNT6::pairing(sa, b); + let ans2 = MNT6::pairing(a, sb); + let ans3 = MNT6::pairing(a, b).pow(s.into_repr()); + + assert_eq!(ans1, ans2); + assert_eq!(ans2, ans3); + + assert_ne!(ans1, Fq6::one()); + assert_ne!(ans2, Fq6::one()); + assert_ne!(ans3, Fq6::one()); + + assert_eq!(ans1.pow(Fr::characteristic()), Fq6::one()); + assert_eq!(ans2.pow(Fr::characteristic()), Fq6::one()); + assert_eq!(ans3.pow(Fr::characteristic()), Fq6::one()); +} diff --git a/algebra/src/curves/mod.rs b/algebra/src/curves/mod.rs new file mode 100644 index 000000000..6cb09cace --- /dev/null +++ b/algebra/src/curves/mod.rs @@ -0,0 +1,286 @@ +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::{Field, PrimeField, SquareRootField}, + groups::Group, +}; +use rand::Rand; +use std::{ + fmt::{Debug, Display}, + hash::Hash, + ops::{Add, AddAssign, Neg, Sub, SubAssign}, +}; + +pub mod bls12_377; +pub mod bls12_381; +pub mod edwards_bls12; +pub mod edwards_sw6; +pub mod jubjub; +pub mod mnt6; +pub mod models; +pub mod sw6; + +#[cfg(test)] +pub mod tests; + +pub use self::models::*; + +pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send { + /// This is the scalar field of the G1/G2 groups. + type Fr: PrimeField + SquareRootField + Into<::BigInt>; + + /// The projective representation of an element in G1. + type G1Projective: ProjectiveCurve< + BaseField = Self::Fq, + ScalarField = Self::Fr, + Affine = Self::G1Affine, + > + From; + + /// The affine representation of an element in G1. + type G1Affine: AffineCurve< + BaseField = Self::Fq, + ScalarField = Self::Fr, + Projective = Self::G1Projective, + > + PairingCurve + + From; + + /// The projective representation of an element in G2. + type G2Projective: ProjectiveCurve< + BaseField = Self::Fqe, + ScalarField = Self::Fr, + Affine = Self::G2Affine, + > + From; + + /// The affine representation of an element in G2. + type G2Affine: AffineCurve< + BaseField = Self::Fqe, + ScalarField = Self::Fr, + Projective = Self::G2Projective, + > + PairingCurve + + From; + + /// The base field that hosts G1. + type Fq: PrimeField + SquareRootField; + + /// The extension field that hosts G2. + type Fqe: SquareRootField; + + /// The extension field that hosts the target group of the pairing. + type Fqk: Field; + + /// Perform a miller loop with some number of (G1, G2) pairs. + #[must_use] + fn miller_loop<'a, I>(i: I) -> Self::Fqk + where + I: IntoIterator< + Item = &'a ( + &'a ::Prepared, + &'a ::Prepared, + ), + >; + + /// Perform final exponentiation of the result of a miller loop. + #[must_use] + fn final_exponentiation(_: &Self::Fqk) -> Option; + + /// Computes a product of pairings. + #[must_use] + fn product_of_pairings<'a, I>(i: I) -> Self::Fqk + where + I: IntoIterator< + Item = &'a ( + &'a ::Prepared, + &'a ::Prepared, + ), + >, + { + Self::final_exponentiation(&Self::miller_loop(i)).unwrap() + } + + /// Performs multiple pairing operations + #[must_use] + fn pairing(p: G1, q: G2) -> Self::Fqk + where + G1: Into, + G2: Into, + { + Self::final_exponentiation(&Self::miller_loop( + [(&(p.into().prepare()), &(q.into().prepare()))].into_iter(), + )) + .unwrap() + } +} + +/// Projective representation of an elliptic curve point guaranteed to be +/// in the correct prime order subgroup. +pub trait ProjectiveCurve: + Eq + + Sized + + ToBytes + + FromBytes + + Copy + + Clone + + Default + + Send + + Sync + + Hash + + Debug + + Display + + Rand + + 'static + + Neg + + for<'a> Add<&'a Self, Output = Self> + + for<'a> Sub<&'a Self, Output = Self> + + for<'a> AddAssign<&'a Self> + + for<'a> SubAssign<&'a Self> +{ + type ScalarField: PrimeField + SquareRootField + Into<::BigInt>; + type BaseField: Field; + type Affine: AffineCurve; + + /// Returns the additive identity. + #[must_use] + fn zero() -> Self; + + /// Returns a fixed generator of unknown exponent. + #[must_use] + fn prime_subgroup_generator() -> Self; + + /// Determines if this point is the point at infinity. + #[must_use] + fn is_zero(&self) -> bool; + + /// Normalizes a slice of projective elements so that + /// conversion to affine is cheap. + fn batch_normalization(v: &mut [Self]); + + /// Checks if the point is already "normalized" so that + /// cheap affine conversion is possible. + #[must_use] + fn is_normalized(&self) -> bool; + + /// Doubles this element. + #[must_use] + fn double(&self) -> Self { + let mut copy = *self; + copy.double_in_place(); + copy + } + + fn double_in_place(&mut self) -> &mut Self; + + /// Adds an affine element to this element. + fn add_assign_mixed(&mut self, other: &Self::Affine); + + /// Performs scalar multiplication of this element. + fn mul_assign::BigInt>>(&mut self, other: S); + + /// Converts this element into its affine representation. + #[must_use] + fn into_affine(&self) -> Self::Affine; + + /// Recommends a wNAF window table size given a scalar. Always returns a + /// number between 2 and 22, inclusive. + #[must_use] + fn recommended_wnaf_for_scalar(scalar: ::BigInt) -> usize; + + /// Recommends a wNAF window size given the number of scalars you intend to + /// multiply a base by. Always returns a number between 2 and 22, + /// inclusive. + #[must_use] + fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize; +} + +/// Affine representation of an elliptic curve point guaranteed to be +/// in the correct prime order subgroup. +pub trait AffineCurve: + Eq + + Sized + + ToBytes + + FromBytes + + Copy + + Clone + + Default + + Send + + Sync + + Hash + + Debug + + Display + + Neg + + 'static +{ + type ScalarField: PrimeField + SquareRootField + Into<::BigInt>; + type BaseField: Field; + type Projective: ProjectiveCurve; + + /// Returns the additive identity. + #[must_use] + fn zero() -> Self; + + /// Returns a fixed generator of unknown exponent. + #[must_use] + fn prime_subgroup_generator() -> Self; + + /// Determines if this point represents the point at infinity; the + /// additive identity. + #[must_use] + fn is_zero(&self) -> bool; + + /// Performs scalar multiplication of this element with mixed addition. + #[must_use] + fn mul::BigInt>>(&self, other: S) + -> Self::Projective; + + /// Converts this element into its projective representation. + #[must_use] + fn into_projective(&self) -> Self::Projective; + + /// Multiply this element by the cofactor. + #[must_use] + fn mul_by_cofactor(&self) -> Self; + + /// Multiply this element by the inverse of the cofactor modulo the size of + /// `Self::ScalarField`. + #[must_use] + fn mul_by_cofactor_inv(&self) -> Self; +} + +pub trait PairingCurve: AffineCurve { + type Engine: PairingEngine; + type Prepared: ToBytes + Default + Clone + Send + Sync + Debug + 'static; + type PairWith: PairingCurve; + type PairingResult: Field; + + /// Prepares this element for pairing purposes. + #[must_use] + fn prepare(&self) -> Self::Prepared; + + /// Perform a pairing + #[must_use] + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult; +} + +impl Group for C { + type ScalarField = C::ScalarField; + #[must_use] + fn zero() -> Self { + ::zero() + } + + #[must_use] + fn is_zero(&self) -> bool { + ::is_zero(&self) + } + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp += self; + tmp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + ::double_in_place(self) + } +} diff --git a/algebra/src/curves/models/bls12/g1.rs b/algebra/src/curves/models/bls12/g1.rs new file mode 100644 index 000000000..d8bed2456 --- /dev/null +++ b/algebra/src/curves/models/bls12/g1.rs @@ -0,0 +1,43 @@ +use crate::{ + bytes::ToBytes, + curves::{ + bls12::Bls12Parameters, + short_weierstrass_jacobian::{GroupAffine, GroupProjective}, + AffineCurve, + }, +}; +use std::io::{Result as IoResult, Write}; + +pub type G1Affine

= GroupAffine<

::G1Parameters>; +pub type G1Projective

= GroupProjective<

::G1Parameters>; + +#[derive(Derivative)] +#[derivative( + Clone(bound = "P: Bls12Parameters"), + Debug(bound = "P: Bls12Parameters"), + PartialEq(bound = "P: Bls12Parameters"), + Eq(bound = "P: Bls12Parameters") +)] +pub struct G1Prepared(pub G1Affine

); + +impl G1Prepared

{ + pub fn is_zero(&self) -> bool { + self.0.is_zero() + } + + pub fn from_affine(p: G1Affine

) -> Self { + G1Prepared(p) + } +} + +impl Default for G1Prepared

{ + fn default() -> Self { + G1Prepared(G1Affine::

::prime_subgroup_generator()) + } +} + +impl ToBytes for G1Prepared

{ + fn write(&self, writer: W) -> IoResult<()> { + self.0.write(writer) + } +} diff --git a/algebra/src/curves/models/bls12/g2.rs b/algebra/src/curves/models/bls12/g2.rs new file mode 100644 index 000000000..3c4235f0c --- /dev/null +++ b/algebra/src/curves/models/bls12/g2.rs @@ -0,0 +1,147 @@ +use crate::{ + bytes::ToBytes, + curves::{ + bls12::{Bls12Parameters, TwistType}, + models::SWModelParameters, + short_weierstrass_jacobian::{GroupAffine, GroupProjective}, + AffineCurve, + }, + fields::{BitIterator, Field, Fp2}, +}; +use std::io::{Result as IoResult, Write}; + +pub type G2Affine

= GroupAffine<

::G2Parameters>; +pub type G2Projective

= GroupProjective<

::G2Parameters>; + +#[derive(Derivative)] +#[derivative( + Clone(bound = "P: Bls12Parameters"), + Debug(bound = "P: Bls12Parameters"), + PartialEq(bound = "P: Bls12Parameters"), + Eq(bound = "P: Bls12Parameters") +)] +pub struct G2Prepared { + // Stores the coefficients of the line evaluations as calculated in + // https://eprint.iacr.org/2013/722.pdf + pub ell_coeffs: Vec<(Fp2, Fp2, Fp2)>, + pub infinity: bool, +} + +#[derive(Derivative)] +#[derivative( + Clone(bound = "P: Bls12Parameters"), + Copy(bound = "P: Bls12Parameters"), + Debug(bound = "P: Bls12Parameters") +)] +struct G2HomProjective { + x: Fp2, + y: Fp2, + z: Fp2, +} + +impl Default for G2Prepared

{ + fn default() -> Self { + Self::from_affine(G2Affine::

::prime_subgroup_generator()) + } +} + +impl ToBytes for G2Prepared

{ + fn write(&self, mut writer: W) -> IoResult<()> { + for coeff in &self.ell_coeffs { + coeff.0.write(&mut writer)?; + coeff.1.write(&mut writer)?; + coeff.2.write(&mut writer)?; + } + self.infinity.write(writer) + } +} + +impl G2Prepared

{ + pub fn is_zero(&self) -> bool { + self.infinity + } + + pub fn from_affine(q: G2Affine

) -> Self { + let two_inv = P::Fp::one().double().inverse().unwrap(); + if q.is_zero() { + return Self { + ell_coeffs: vec![], + infinity: true, + }; + } + + let mut ell_coeffs = vec![]; + let mut r = G2HomProjective { + x: q.x, + y: q.y, + z: Fp2::one(), + }; + + for i in BitIterator::new(P::X).skip(1) { + ell_coeffs.push(doubling_step::

(&mut r, &two_inv)); + + if i { + ell_coeffs.push(addition_step::

(&mut r, &q)); + } + } + + Self { + ell_coeffs, + infinity: false, + } + } +} + +fn doubling_step( + r: &mut G2HomProjective, + two_inv: &B::Fp, +) -> (Fp2, Fp2, Fp2) { + // Formula for line function when working with + // homogeneous projective coordinates. + + let mut a = r.x * &r.y; + a.mul_by_fp(two_inv); + let b = r.y.square(); + let c = r.z.square(); + let e = B::G2Parameters::COEFF_B * &(c.double() + &c); + let f = e.double() + &e; + let mut g = b + &f; + g.mul_by_fp(two_inv); + let h = (r.y + &r.z).square() - &(b + &c); + let i = e - &b; + let j = r.x.square(); + let e_square = e.square(); + + r.x = a * &(b - &f); + r.y = g.square() - &(e_square.double() + &e_square); + r.z = b * &h; + match B::TWIST_TYPE { + TwistType::M => (i, j.double() + &j, -h), + TwistType::D => (-h, j.double() + &j, i), + } +} + +fn addition_step( + r: &mut G2HomProjective, + q: &G2Affine, +) -> (Fp2, Fp2, Fp2) { + // Formula for line function when working with + // homogeneous projective coordinates. + let theta = r.y - &(q.y * &r.z); + let lambda = r.x - &(q.x * &r.z); + let c = theta.square(); + let d = lambda.square(); + let e = lambda * &d; + let f = r.z * &c; + let g = r.x * &d; + let h = e + &f - &g.double(); + r.x = lambda * &h; + r.y = theta * &(g - &h) - &(e * &r.y); + r.z *= &e; + let j = theta * &q.x - &(lambda * &q.y); + + match B::TWIST_TYPE { + TwistType::M => (j, -theta, lambda), + TwistType::D => (lambda, -theta, j), + } +} diff --git a/algebra/src/curves/models/bls12/mod.rs b/algebra/src/curves/models/bls12/mod.rs new file mode 100644 index 000000000..e653d26c6 --- /dev/null +++ b/algebra/src/curves/models/bls12/mod.rs @@ -0,0 +1,208 @@ +use crate::{ + curves::{ + models::{ModelParameters, SWModelParameters}, + PairingCurve, PairingEngine, + }, + fields::{ + fp12_2over3over2::{Fp12, Fp12Parameters}, + fp2::Fp2Parameters, + fp6_3over2::Fp6Parameters, + BitIterator, Field, Fp2, PrimeField, SquareRootField, + }, +}; + +use std::marker::PhantomData; + +pub enum TwistType { + M, + D, +} + +pub trait Bls12Parameters: 'static { + const X: &'static [u64]; + const X_IS_NEGATIVE: bool; + const TWIST_TYPE: TwistType; + type Fp: PrimeField + SquareRootField + Into<::BigInt>; + type Fp2Params: Fp2Parameters; + type Fp6Params: Fp6Parameters; + type Fp12Params: Fp12Parameters; + type G1Parameters: SWModelParameters; + type G2Parameters: SWModelParameters< + BaseField = Fp2, + ScalarField = ::ScalarField, + >; +} + +pub mod g1; +pub mod g2; + +pub use self::{ + g1::{G1Affine, G1Prepared, G1Projective}, + g2::{G2Affine, G2Prepared, G2Projective}, +}; + +#[derive(Derivative)] +#[derivative(Copy, Clone, PartialEq, Eq, Debug, Hash)] +pub struct Bls12(PhantomData P>); + +impl Bls12

{ + // Evaluate the line function at point p. + fn ell( + f: &mut Fp12, + coeffs: &(Fp2, Fp2, Fp2), + p: &G1Affine

, + ) { + let mut c0 = coeffs.0; + let mut c1 = coeffs.1; + let mut c2 = coeffs.2; + + match P::TWIST_TYPE { + TwistType::M => { + c2.mul_by_fp(&p.y); + c1.mul_by_fp(&p.x); + f.mul_by_014(&c0, &c1, &c2); + }, + TwistType::D => { + c0.mul_by_fp(&p.y); + c1.mul_by_fp(&p.x); + f.mul_by_034(&c0, &c1, &c2); + }, + } + } + + fn exp_by_x(mut f: Fp12) -> Fp12 { + f = f.cyclotomic_exp(P::X); + if P::X_IS_NEGATIVE { + f.conjugate(); + } + f + } +} + +impl PairingEngine for Bls12

+where + G1Affine

: PairingCurve< + BaseField = ::BaseField, + ScalarField = ::ScalarField, + Projective = G1Projective

, + PairWith = G2Affine

, + Prepared = G1Prepared

, + PairingResult = Fp12, + >, + G2Affine

: PairingCurve< + BaseField = ::BaseField, + ScalarField = ::ScalarField, + Projective = G2Projective

, + PairWith = G1Affine

, + Prepared = G2Prepared

, + PairingResult = Fp12, + >, +{ + type Fr = ::ScalarField; + type G1Projective = G1Projective

; + type G1Affine = G1Affine

; + type G2Projective = G2Projective

; + type G2Affine = G2Affine

; + type Fq = P::Fp; + type Fqe = Fp2; + type Fqk = Fp12; + + fn miller_loop<'a, I>(i: I) -> Self::Fqk + where + I: IntoIterator< + Item = &'a ( + &'a ::Prepared, + &'a ::Prepared, + ), + >, + { + let mut pairs = vec![]; + for &(p, q) in i { + if !p.is_zero() && !q.is_zero() { + pairs.push((p, q.ell_coeffs.iter())); + } + } + + let mut f = Self::Fqk::one(); + + for i in BitIterator::new(P::X).skip(1) { + f.square_in_place(); + + for &mut (p, ref mut coeffs) in &mut pairs { + Self::ell(&mut f, coeffs.next().unwrap(), &p.0); + } + + if i { + for &mut (p, ref mut coeffs) in &mut pairs { + Self::ell(&mut f, coeffs.next().unwrap(), &p.0); + } + } + } + + if P::X_IS_NEGATIVE { + f.conjugate(); + } + + f + } + + fn final_exponentiation(f: &Self::Fqk) -> Option { + // Computing the final exponentation following + // https://eprint.iacr.org/2016/130.pdf. + // We don't use their "faster" formula because it is difficult to make + // it work for curves with odd `P::X`. + // Hence we implement the algorithm from Table 1 below. + + // f1 = r.conjugate() = f^(p^6) + let mut f1 = *f; + f1.frobenius_map(6); + + match f.inverse() { + Some(mut f2) => { + // f2 = f^(-1); + // r = f^(p^6 - 1) + let mut r = f1 * &f2; + + // f2 = f^(p^6 - 1) + f2 = r; + // r = f^((p^6 - 1)(p^2)) + r.frobenius_map(2); + + // r = f^((p^6 - 1)(p^2) + (p^6 - 1)) + // r = f^((p^6 - 1)(p^2 + 1)) + r *= &f2; + + // Hard part of the final exponentation is below: + // From https://eprint.iacr.org/2016/130.pdf, Table 1 + let mut y0 = r.cyclotomic_square(); + y0.conjugate(); + + let mut y5 = Self::exp_by_x(r); + + let mut y1 = y5.cyclotomic_square(); + let mut y3 = y0 * &y5; + y0 = Self::exp_by_x(y3); + let y2 = Self::exp_by_x(y0); + let mut y4 = Self::exp_by_x(y2); + y4 *= &y1; + y1 = Self::exp_by_x(y4); + y3.conjugate(); + y1 *= &y3; + y1 *= &r; + y3 = r; + y3.conjugate(); + y0 *= &r; + y0.frobenius_map(3); + y4 *= &y3; + y4.frobenius_map(1); + y5 *= &y2; + y5.frobenius_map(2); + y5 *= &y0; + y5 *= &y4; + y5 *= &y1; + Some(y5) + }, + None => None, + } + } +} diff --git a/algebra/src/curves/models/mod.rs b/algebra/src/curves/models/mod.rs new file mode 100644 index 000000000..26639e5a9 --- /dev/null +++ b/algebra/src/curves/models/mod.rs @@ -0,0 +1,112 @@ +use crate::{ + biginteger::BigInteger, + fields::{Field, PrimeField, SquareRootField}, +}; + +pub mod bls12; +pub mod short_weierstrass_jacobian; +pub mod short_weierstrass_projective; +pub mod twisted_edwards_extended; + +pub trait ModelParameters: Send + Sync + 'static { + type BaseField: Field + SquareRootField; + type ScalarField: PrimeField + SquareRootField + Into<::BigInt>; +} + +pub trait SWModelParameters: ModelParameters { + const COEFF_A: Self::BaseField; + const COEFF_B: Self::BaseField; + const COFACTOR: &'static [u64]; + const COFACTOR_INV: Self::ScalarField; + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField); + + #[inline(always)] + fn mul_by_a(elem: &Self::BaseField) -> Self::BaseField { + let mut copy = *elem; + copy *= &Self::COEFF_A; + copy + } + + #[inline(always)] + fn add_b(elem: &Self::BaseField) -> Self::BaseField { + let mut copy = *elem; + copy += &Self::COEFF_B; + copy + } + + #[inline(always)] + fn empirical_recommended_wnaf_for_scalar( + scalar: ::BigInt, + ) -> usize { + let num_bits = scalar.num_bits() as usize; + + if num_bits >= 103 { + 4 + } else if num_bits >= 37 { + 3 + } else { + 2 + } + } + + #[inline(always)] + fn empirical_recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize { + const RECOMMENDATIONS: [usize; 11] = [1, 3, 8, 20, 47, 126, 260, 826, 1501, 4555, 84071]; + + let mut result = 4; + for r in &RECOMMENDATIONS { + match num_scalars > *r { + true => result += 1, + false => break, + } + } + result + } +} + +pub trait TEModelParameters: ModelParameters { + const COEFF_A: Self::BaseField; + const COEFF_D: Self::BaseField; + const COFACTOR: &'static [u64]; + const COFACTOR_INV: Self::ScalarField; + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField); + + #[inline(always)] + fn mul_by_a(elem: &Self::BaseField) -> Self::BaseField { + let mut copy = *elem; + copy *= &Self::COEFF_A; + copy + } + + #[inline(always)] + fn empirical_recommended_wnaf_for_scalar( + scalar: ::BigInt, + ) -> usize { + let num_bits = scalar.num_bits() as usize; + + if num_bits >= 130 { + 4 + } else if num_bits >= 34 { + 3 + } else { + 2 + } + } + + #[inline(always)] + fn empirical_recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize { + const RECOMMENDATIONS: [usize; 12] = + [1, 3, 7, 20, 43, 120, 273, 563, 1630, 3128, 7933, 62569]; + + let mut ret = 4; + for r in &RECOMMENDATIONS { + if num_scalars > *r { + ret += 1; + } else { + break; + } + } + + ret + } +} diff --git a/algebra/src/curves/models/short_weierstrass_jacobian.rs b/algebra/src/curves/models/short_weierstrass_jacobian.rs new file mode 100644 index 000000000..17ceb071e --- /dev/null +++ b/algebra/src/curves/models/short_weierstrass_jacobian.rs @@ -0,0 +1,706 @@ +use crate::curves::models::SWModelParameters as Parameters; +use rand::{Rand, Rng}; +use std::{ + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + curves::{AffineCurve, ProjectiveCurve}, + fields::{BitIterator, Field, PrimeField, SquareRootField}, +}; +use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; + +#[derive(Derivative)] +#[derivative( + Copy(bound = "P: Parameters"), + Clone(bound = "P: Parameters"), + PartialEq(bound = "P: Parameters"), + Eq(bound = "P: Parameters"), + Debug(bound = "P: Parameters"), + Hash(bound = "P: Parameters") +)] +pub struct GroupAffine { + pub x: P::BaseField, + pub y: P::BaseField, + pub infinity: bool, + #[derivative(Debug = "ignore")] + _params: PhantomData

, +} + +impl Display for GroupAffine

{ + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + if self.infinity { + write!(f, "GroupAffine(Infinity)") + } else { + write!(f, "GroupAffine(x={}, y={})", self.x, self.y) + } + } +} + +impl GroupAffine

{ + pub const fn new(x: P::BaseField, y: P::BaseField, infinity: bool) -> Self { + Self { + x, + y, + infinity, + _params: PhantomData, + } + } + + pub fn scale_by_cofactor(&self) -> GroupProjective

{ + let cofactor = BitIterator::new(P::COFACTOR); + self.mul_bits(cofactor) + } + + pub(crate) fn mul_bits>(&self, bits: BitIterator) -> GroupProjective

{ + let mut res = GroupProjective::zero(); + for i in bits { + res.double_in_place(); + if i { + res.add_assign_mixed(self) + } + } + res + } + + /// Attempts to construct an affine point given an x-coordinate. The + /// point is not guaranteed to be in the prime order subgroup. + /// + /// If and only if `greatest` is set will the lexicographically + /// largest y-coordinate be selected. + #[allow(dead_code)] + pub(crate) fn get_point_from_x(x: P::BaseField, greatest: bool) -> Option { + // Compute x^3 + ax + b + let x3b = P::add_b(&((x.square() * &x) + &P::mul_by_a(&x))); + + x3b.sqrt().map(|y| { + let negy = -y; + + let y = if (y < negy) ^ greatest { y } else { negy }; + Self::new(x, y, false) + }) + } + + pub fn is_on_curve(&self) -> bool { + if self.is_zero() { + true + } else { + // Check that the point is on the curve + let y2 = self.y.square(); + let x3b = P::add_b(&((self.x.square() * &self.x) + &P::mul_by_a(&self.x))); + y2 == x3b + } + } + + pub fn is_in_correct_subgroup_assuming_on_curve(&self) -> bool { + self.mul_bits(BitIterator::new(P::ScalarField::characteristic())) + .is_zero() + } +} + +impl AffineCurve for GroupAffine

{ + type BaseField = P::BaseField; + type ScalarField = P::ScalarField; + type Projective = GroupProjective

; + + #[inline] + fn zero() -> Self { + Self::new(Self::BaseField::zero(), Self::BaseField::one(), true) + } + + #[inline] + fn prime_subgroup_generator() -> Self { + Self::new( + P::AFFINE_GENERATOR_COEFFS.0, + P::AFFINE_GENERATOR_COEFFS.1, + false, + ) + } + + #[inline] + fn is_zero(&self) -> bool { + self.infinity + } + + #[inline] + fn mul::BigInt>>(&self, by: S) -> GroupProjective

{ + let bits = BitIterator::new(by.into()); + self.mul_bits(bits) + } + + fn mul_by_cofactor(&self) -> Self { + self.scale_by_cofactor().into() + } + + fn mul_by_cofactor_inv(&self) -> Self { + self.mul(P::COFACTOR_INV).into() + } + + #[inline] + fn into_projective(&self) -> GroupProjective

{ + (*self).into() + } +} + +impl Neg for GroupAffine

{ + type Output = Self; + + #[inline] + fn neg(self) -> Self { + if !self.is_zero() { + Self::new(self.x, -self.y, false) + } else { + self + } + } +} + +impl ToBytes for GroupAffine

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer) + } +} + +impl FromBytes for GroupAffine

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let x = P::BaseField::read(&mut reader)?; + let y = P::BaseField::read(&mut reader)?; + let infinity = x.is_zero() && y.is_one(); + Ok(Self::new(x, y, infinity)) + } +} + +impl Default for GroupAffine

{ + #[inline] + fn default() -> Self { + Self::zero() + } +} + +#[derive(Derivative)] +#[derivative( + Copy(bound = "P: Parameters"), + Clone(bound = "P: Parameters"), + Eq(bound = "P: Parameters"), + Debug(bound = "P: Parameters"), + Hash(bound = "P: Parameters") +)] +pub struct GroupProjective { + pub x: P::BaseField, + pub y: P::BaseField, + pub z: P::BaseField, + _params: PhantomData

, +} + +impl Display for GroupProjective

{ + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "{}", self.into_affine()) + } +} + +impl PartialEq for GroupProjective

{ + fn eq(&self, other: &Self) -> bool { + if self.is_zero() { + return other.is_zero(); + } + + if other.is_zero() { + return false; + } + + // The points (X, Y, Z) and (X', Y', Z') + // are equal when (X * Z^2) = (X' * Z'^2) + // and (Y * Z^3) = (Y' * Z'^3). + let z1 = self.z.square(); + let z2 = other.z.square(); + + if self.x * &z2 != other.x * &z1 { + false + } else if self.y * &(z2 * &other.z) != other.y * &(z1 * &self.z) { + false + } else { + true + } + } +} + +impl Rand for GroupProjective

{ + fn rand(rng: &mut R) -> Self { + let res = Self::prime_subgroup_generator() * &P::ScalarField::rand(rng); + debug_assert!(res.into_affine().is_in_correct_subgroup_assuming_on_curve()); + res + } +} + +impl ToBytes for GroupProjective

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer)?; + self.z.write(writer) + } +} + +impl FromBytes for GroupProjective

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let x = P::BaseField::read(&mut reader)?; + let y = P::BaseField::read(&mut reader)?; + let z = P::BaseField::read(reader)?; + Ok(Self::new(x, y, z)) + } +} + +impl Default for GroupProjective

{ + #[inline] + fn default() -> Self { + Self::zero() + } +} + +impl GroupProjective

{ + pub const fn new(x: P::BaseField, y: P::BaseField, z: P::BaseField) -> Self { + Self { + x, + y, + z, + _params: PhantomData, + } + } +} + +impl ProjectiveCurve for GroupProjective

{ + type BaseField = P::BaseField; + type ScalarField = P::ScalarField; + type Affine = GroupAffine

; + + // The point at infinity is always represented by + // Z = 0. + #[inline] + fn zero() -> Self { + Self::new( + P::BaseField::zero(), + P::BaseField::one(), + P::BaseField::zero(), + ) + } + + #[inline] + fn prime_subgroup_generator() -> Self { + GroupAffine::prime_subgroup_generator().into() + } + + // The point at infinity is always represented by + // Z = 0. + #[inline] + fn is_zero(&self) -> bool { + self.z.is_zero() + } + + #[inline] + fn is_normalized(&self) -> bool { + self.is_zero() || self.z.is_one() + } + + #[inline] + fn batch_normalization(v: &mut [Self]) { + // Montgomery’s Trick and Fast Implementation of Masked AES + // Genelle, Prouff and Quisquater + // Section 3.2 + + // First pass: compute [a, ab, abc, ...] + let mut prod = Vec::with_capacity(v.len()); + let mut tmp = P::BaseField::one(); + for g in v.iter_mut() + // Ignore normalized elements + .filter(|g| !g.is_normalized()) + { + tmp.mul_assign(&g.z); + prod.push(tmp); + } + + // Invert `tmp`. + tmp = tmp.inverse().unwrap(); // Guaranteed to be nonzero. + + // Second pass: iterate backwards to compute inverses + for (g, s) in v.iter_mut() + // Backwards + .rev() + // Ignore normalized elements + .filter(|g| !g.is_normalized()) + // Backwards, skip last element, fill in one for last term. + .zip(prod.into_iter().rev().skip(1).chain(Some(P::BaseField::one()))) + { + // tmp := tmp * g.z; g.z := tmp * s = 1/z + let newtmp = tmp * &g.z; + g.z = tmp * &s; + tmp = newtmp; + } + #[cfg(not(feature = "parallel"))] + { + // Perform affine transformations + for g in v.iter_mut().filter(|g| !g.is_normalized()) { + let z2 = g.z.square(); // 1/z + g.x *= &z2; // x/z^2 + g.y *= &(z2 * &g.z); // y/z^3 + g.z = P::BaseField::one(); // z = 1 + } + } + + #[cfg(feature = "parallel")] + { + use rayon::prelude::*; + // Perform affine transformations + v.par_iter_mut() + .filter(|g| !g.is_normalized()) + .for_each(|g| { + let z2 = g.z.square(); // 1/z + g.x *= &z2; // x/z^2 + g.y *= &(z2 * &g.z); // y/z^3 + g.z = P::BaseField::one(); // z = 1 + }); + } + } + + fn double_in_place(&mut self) -> &mut Self { + if self.is_zero() { + return self; + } + + if P::COEFF_A.is_zero() { + // A = X1^2 + let mut a = self.x.square(); + + // B = Y1^2 + let b = self.y.square(); + + // C = B^2 + let mut c = b.square(); + + // D = 2*((X1+B)2-A-C) + let d = ((self.x + &b).square() - &a - &c).double(); + + // E = 3*A + let e = a + a.double_in_place(); + + // F = E^2 + let f = e.square(); + + // Z3 = 2*Y1*Z1 + self.z.mul_assign(&self.y); + self.z.double_in_place(); + + // X3 = F-2*D + self.x = f - &d - &d; + + // Y3 = E*(D-X3)-8*C + self.y = (d - &self.x) * &e - c.double_in_place().double_in_place().double_in_place(); + self + } else { + // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + // XX = X1^2 + let xx = self.x.square(); + + // YY = Y1^2 + let yy = self.y.square(); + + // YYYY = YY^2 + let mut yyyy = yy.square(); + + // ZZ = Z1^2 + let zz = self.z.square(); + + // S = 2*((X1+YY)^2-XX-YYYY) + let s = ((self.x + &yy).square() - &xx - &yyyy).double(); + + // M = 3*XX+a*ZZ^2 + let m = xx + &xx + &xx + &P::mul_by_a(&zz.square()); + + // T = M^2-2*S + let t = m.square() - &s.double(); + + // X3 = T + self.x = t; + // Y3 = M*(S-T)-8*YYYY + let old_y = self.y; + self.y = m * &(s - &t) - yyyy.double_in_place().double_in_place().double_in_place(); + // Z3 = (Y1+Z1)^2-YY-ZZ + self.z = (old_y + &self.z).square() - &yy - &zz; + self + } + } + + fn add_assign_mixed(&mut self, other: &Self::Affine) { + if other.is_zero() { + return; + } + + if self.is_zero() { + self.x = other.x; + self.y = other.y; + self.z = P::BaseField::one(); + return; + } + + // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl + // Works for all curves. + + // Z1Z1 = Z1^2 + let z1z1 = self.z.square(); + + // U2 = X2*Z1Z1 + let u2 = other.x * &z1z1; + + // S2 = Y2*Z1*Z1Z1 + let s2 = (other.y * &self.z) * &z1z1; + + if self.x == u2 && self.y == s2 { + // The two points are equal, so we double. + self.double_in_place(); + } else { + // If we're adding -a and a together, self.z becomes zero as H becomes zero. + + // H = U2-X1 + let h = u2 - &self.x; + + // HH = H^2 + let hh = h.square(); + + // I = 4*HH + let mut i = hh; + i.double_in_place().double_in_place(); + + // J = H*I + let mut j = h * &i; + + // r = 2*(S2-Y1) + let r = (s2 - &self.y).double(); + + // V = X1*I + let v = self.x * &i; + + // X3 = r^2 - J - 2*V + self.x = r.square(); + self.x -= &j; + self.x -= &v; + self.x -= &v; + + // Y3 = r*(V-X3)-2*Y1*J + j *= &self.y; // J = 2*Y1*J + j.double_in_place(); + self.y = v - &self.x; + self.y *= &r; + self.y -= &j; + + // Z3 = (Z1+H)^2-Z1Z1-HH + self.z += &h; + self.z.square_in_place(); + self.z -= &z1z1; + self.z -= &hh; + } + } + + fn mul_assign::BigInt>>(&mut self, other: S) { + let mut res = Self::zero(); + + let mut found_one = false; + + for i in BitIterator::new(other.into()) { + if found_one { + res.double_in_place(); + } else { + found_one = i; + } + + if i { + res.add_assign(self); + } + } + + *self = res; + } + + #[inline] + fn into_affine(&self) -> GroupAffine

{ + (*self).into() + } + + #[inline] + fn recommended_wnaf_for_scalar(scalar: ::BigInt) -> usize { + P::empirical_recommended_wnaf_for_scalar(scalar) + } + + #[inline] + fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize { + P::empirical_recommended_wnaf_for_num_scalars(num_scalars) + } +} + +impl Neg for GroupProjective

{ + type Output = Self; + + #[inline] + fn neg(self) -> Self { + if !self.is_zero() { + Self::new(self.x, -self.y, self.z) + } else { + self + } + } +} + +impl<'a, P: Parameters> Add<&'a Self> for GroupProjective

{ + type Output = Self; + + #[inline] + fn add(self, other: &'a Self) -> Self { + let mut copy = self; + copy += other; + copy + } +} + +impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ + fn add_assign(&mut self, other: &'a Self) { + if self.is_zero() { + *self = *other; + return; + } + + if other.is_zero() { + return; + } + + // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl + // Works for all curves. + + // Z1Z1 = Z1^2 + let z1z1 = self.z.square(); + + // Z2Z2 = Z2^2 + let z2z2 = other.z.square(); + + // U1 = X1*Z2Z2 + let u1 = self.x * &z2z2; + + // U2 = X2*Z1Z1 + let u2 = other.x * &z1z1; + + // S1 = Y1*Z2*Z2Z2 + let s1 = self.y * &other.z * &z2z2; + + // S2 = Y2*Z1*Z1Z1 + let s2 = other.y * &self.z * &z1z1; + + if u1 == u2 && s1 == s2 { + // The two points are equal, so we double. + self.double_in_place(); + } else { + // If we're adding -a and a together, self.z becomes zero as H becomes zero. + + // H = U2-U1 + let h = u2 - &u1; + + // I = (2*H)^2 + let i = (h.double()).square(); + + // J = H*I + let j = h * &i; + + // r = 2*(S2-S1) + let r = (s2 - &s1).double(); + + // V = U1*I + let v = u1 * &i; + + // X3 = r^2 - J - 2*V + self.x = r.square() - &j - &(v.double()); + + // Y3 = r*(V - X3) - 2*S1*J + self.y = r * &(v - &self.x) - (s1 * &j).double_in_place(); + + // Z3 = ((Z1+Z2)^2 - Z1Z1 - Z2Z2)*H + self.z = ((self.z + &other.z).square() - &z1z1 - &z2z2) * &h; + } + } +} + +impl<'a, P: Parameters> Sub<&'a Self> for GroupProjective

{ + type Output = Self; + + #[inline] + fn sub(self, other: &'a Self) -> Self { + let mut copy = self; + copy -= other; + copy + } +} + +impl<'a, P: Parameters> SubAssign<&'a Self> for GroupProjective

{ + fn sub_assign(&mut self, other: &'a Self) { + *self += &(-(*other)); + } +} + +impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupProjective

{ + type Output = Self; + + #[inline] + fn mul(self, other: &'a P::ScalarField) -> Self { + let mut copy = self; + copy *= other; + copy + } +} + +impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupProjective

{ + #[inline] + fn mul_assign(&mut self, other: &'a P::ScalarField) { + as ProjectiveCurve>::mul_assign(self, *other); + } +} + +// The affine point X, Y is represented in the Jacobian +// coordinates with Z = 1. +impl From> for GroupProjective

{ + #[inline] + fn from(p: GroupAffine

) -> GroupProjective

{ + if p.is_zero() { + Self::zero() + } else { + Self::new(p.x, p.y, P::BaseField::one()) + } + } +} + +// The projective point X, Y, Z is represented in the affine +// coordinates as X/Z^2, Y/Z^3. +impl From> for GroupAffine

{ + #[inline] + fn from(p: GroupProjective

) -> GroupAffine

{ + if p.is_zero() { + GroupAffine::zero() + } else if p.z.is_one() { + // If Z is one, the point is already normalized. + GroupAffine::new(p.x, p.y, false) + } else { + // Z is nonzero, so it must have an inverse in a field. + let zinv = p.z.inverse().unwrap(); + let zinv_squared = zinv.square(); + + // X/Z^2 + let x = p.x * &zinv_squared; + + // Y/Z^3 + let y = p.y * &(zinv_squared * &zinv); + + GroupAffine::new(x, y, false) + } + } +} diff --git a/algebra/src/curves/models/short_weierstrass_projective.rs b/algebra/src/curves/models/short_weierstrass_projective.rs new file mode 100644 index 000000000..f7ad1f356 --- /dev/null +++ b/algebra/src/curves/models/short_weierstrass_projective.rs @@ -0,0 +1,581 @@ +use crate::curves::models::SWModelParameters as Parameters; +use rand::{Rand, Rng}; +use std::{ + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + curves::{AffineCurve, ProjectiveCurve}, + fields::{BitIterator, Field, PrimeField, SquareRootField}, +}; +use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; + +#[derive(Derivative)] +#[derivative( + Copy(bound = "P: Parameters"), + Clone(bound = "P: Parameters"), + PartialEq(bound = "P: Parameters"), + Eq(bound = "P: Parameters"), + Debug(bound = "P: Parameters"), + Hash(bound = "P: Parameters") +)] +pub struct GroupAffine { + pub x: P::BaseField, + pub y: P::BaseField, + pub infinity: bool, + #[derivative(Debug = "ignore")] + _params: PhantomData

, +} + +impl Display for GroupAffine

{ + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + if self.infinity { + write!(f, "GroupAffine(Infinity)") + } else { + write!(f, "GroupAffine(x={}, y={})", self.x, self.y) + } + } +} + +impl GroupAffine

{ + pub const fn new(x: P::BaseField, y: P::BaseField, infinity: bool) -> Self { + Self { + x, + y, + infinity, + _params: PhantomData, + } + } + + pub fn scale_by_cofactor(&self) -> ::Projective { + self.mul_bits(BitIterator::new(P::COFACTOR)) + } + + pub(crate) fn mul_bits>( + &self, + bits: BitIterator, + ) -> ::Projective { + let mut res = GroupProjective::zero(); + for i in bits { + res.double_in_place(); + if i { + res.add_assign_mixed(self) + } + } + res + } + + /// Attempts to construct an affine point given an x-coordinate. The + /// point is not guaranteed to be in the prime order subgroup. + /// + /// If and only if `greatest` is set will the lexicographically + /// largest y-coordinate be selected. + #[allow(dead_code)] + pub(crate) fn get_point_from_x(x: P::BaseField, greatest: bool) -> Option { + // Compute x^3 + ax + b + let x3b = P::add_b(&((x.square() * &x) + &P::mul_by_a(&x))); + + x3b.sqrt().map(|y| { + let negy = -y; + + let y = if (y < negy) ^ greatest { y } else { negy }; + Self::new(x, y, false) + }) + } + + /// Checks that the current point is on the elliptic curve. + pub fn is_on_curve(&self) -> bool { + if self.is_zero() { + true + } else { + // Check that the point is on the curve + let y2 = self.y.square(); + let x3b = P::add_b(&((self.x.square() * &self.x) + &P::mul_by_a(&self.x))); + y2 == x3b + } + } + + /// Checks that the current point is in the prime order subgroup given + /// the point on the curve. + pub fn is_in_correct_subgroup_assuming_on_curve(&self) -> bool { + self.mul_bits(BitIterator::new(P::ScalarField::characteristic())) + .is_zero() + } +} + +impl AffineCurve for GroupAffine

{ + type BaseField = P::BaseField; + type ScalarField = P::ScalarField; + type Projective = GroupProjective

; + + fn zero() -> Self { + Self::new(Self::BaseField::zero(), Self::BaseField::one(), true) + } + + fn prime_subgroup_generator() -> Self { + Self::new( + P::AFFINE_GENERATOR_COEFFS.0, + P::AFFINE_GENERATOR_COEFFS.1, + false, + ) + } + + fn is_zero(&self) -> bool { + self.infinity + } + + fn mul::BigInt>>(&self, by: S) -> GroupProjective

{ + let bits = BitIterator::new(by.into()); + self.mul_bits(bits) + } + + fn mul_by_cofactor(&self) -> Self { + self.scale_by_cofactor().into() + } + + fn mul_by_cofactor_inv(&self) -> Self { + self.mul(P::COFACTOR_INV).into() + } + + fn into_projective(&self) -> GroupProjective

{ + (*self).into() + } +} + +impl Neg for GroupAffine

{ + type Output = Self; + + fn neg(self) -> Self { + if !self.is_zero() { + Self::new(self.x, -self.y, false) + } else { + self + } + } +} + +impl ToBytes for GroupAffine

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer)?; + self.infinity.write(writer) + } +} + +impl FromBytes for GroupAffine

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let x = P::BaseField::read(&mut reader)?; + let y = P::BaseField::read(&mut reader)?; + let infinity = bool::read(reader)?; + Ok(Self::new(x, y, infinity)) + } +} + +impl Default for GroupAffine

{ + #[inline] + fn default() -> Self { + Self::zero() + } +} + +#[derive(Derivative)] +#[derivative( + Copy(bound = "P: Parameters"), + Clone(bound = "P: Parameters"), + Eq(bound = "P: Parameters"), + Debug(bound = "P: Parameters"), + Hash(bound = "P: Parameters") +)] +pub struct GroupProjective { + pub x: P::BaseField, + pub y: P::BaseField, + pub z: P::BaseField, + _params: PhantomData

, +} + +impl Display for GroupProjective

{ + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "{}", self.into_affine()) + } +} + +impl PartialEq for GroupProjective

{ + fn eq(&self, other: &Self) -> bool { + if self.is_zero() { + return other.is_zero(); + } + + if other.is_zero() { + return false; + } + + // x1/z1 == x2/z2 <==> x1 * z2 == x2 * z1 + if (self.x * &other.z) != (other.x * &self.z) { + false + } else if (self.y * &other.z) != (other.y * &self.z) { + false + } else { + true + } + } +} + +impl Rand for GroupProjective

{ + fn rand(rng: &mut R) -> Self { + let res = Self::prime_subgroup_generator() * &P::ScalarField::rand(rng); + debug_assert!(res.into_affine().is_in_correct_subgroup_assuming_on_curve()); + res + } +} + +impl ToBytes for GroupProjective

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer)?; + self.z.write(writer) + } +} + +impl FromBytes for GroupProjective

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let x = P::BaseField::read(&mut reader)?; + let y = P::BaseField::read(&mut reader)?; + let z = P::BaseField::read(reader)?; + Ok(Self::new(x, y, z)) + } +} + +impl Default for GroupProjective

{ + #[inline] + fn default() -> Self { + Self::zero() + } +} + +impl GroupProjective

{ + pub const fn new(x: P::BaseField, y: P::BaseField, z: P::BaseField) -> Self { + Self { + x, + y, + z, + _params: PhantomData, + } + } +} + +impl ProjectiveCurve for GroupProjective

{ + type BaseField = P::BaseField; + type ScalarField = P::ScalarField; + type Affine = GroupAffine

; + + // The point at infinity is always represented by Z = 0. + #[inline] + fn zero() -> Self { + Self::new( + P::BaseField::zero(), + P::BaseField::one(), + P::BaseField::zero(), + ) + } + + #[inline] + fn prime_subgroup_generator() -> Self { + GroupAffine::prime_subgroup_generator().into() + } + + // The point at infinity is always represented by + // Z = 0. + #[inline] + fn is_zero(&self) -> bool { + self.z.is_zero() + } + + #[inline] + fn is_normalized(&self) -> bool { + self.is_zero() || self.z.is_one() + } + + fn batch_normalization(v: &mut [Self]) { + // Montgomery’s Trick and Fast Implementation of Masked AES + // Genelle, Prouff and Quisquater + // Section 3.2 + + // First pass: compute [a, ab, abc, ...] + let mut prod = Vec::with_capacity(v.len()); + let mut tmp = P::BaseField::one(); + for g in v.iter_mut() + // Ignore normalized elements + .filter(|g| !g.is_normalized()) + { + tmp.mul_assign(&g.z); + prod.push(tmp); + } + + // Invert `tmp`. + tmp = tmp.inverse().unwrap(); // Guaranteed to be nonzero. + + // Second pass: iterate backwards to compute inverses + for (g, s) in v.iter_mut() + // Backwards + .rev() + // Ignore normalized elements + .filter(|g| !g.is_normalized()) + // Backwards, skip last element, fill in one for last term. + .zip(prod.into_iter().rev().skip(1).chain(Some(P::BaseField::one()))) + { + // tmp := tmp * g.z; g.z := tmp * s = 1/z + let newtmp = tmp * &g.z; + g.z = tmp * &s; + tmp = newtmp; + } + + // Perform affine transformations + for g in v.iter_mut().filter(|g| !g.is_normalized()) { + g.x *= &g.z; // x/z^2 + g.y *= &g.z; + g.z = P::BaseField::one(); // z = 1 + } + } + + fn double_in_place(&mut self) -> &mut Self { + if self.is_zero() { + self + } else { + // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#doubling-dbl-2007-bl + + // XX = X1^2 + let xx = self.x.square(); + // ZZ = Z1^2 + let zz = self.z.square(); + // w = a*ZZ + 3*XX + let w = P::mul_by_a(&zz) + &(xx + &xx.double()); + // s = 2*Y1*Z1 + let mut s = self.y * &(self.z); + s.double_in_place(); + // sss = s^3 + let mut sss = s.square(); + sss *= &s; + // R = Y1*s + let r = self.y * &s; + // RR = R2 + let rr = r.square(); + // B = (X1+R)^2-XX-RR + let b = (self.x + &r).square() - &xx - &rr; + // h = w2-2*B + let h = w.square() - &(b + &b); + // X3 = h*s + self.x = h * &s; + // Y3 = w*(B-h)-2*RR + self.y = w * &(b - &h) - &(rr + &rr); + // Z3 = sss + self.z = sss; + + self + } + } + + fn add_assign_mixed(&mut self, other: &Self::Affine) { + if other.is_zero() { + return; + } else if self.is_zero() { + self.x = other.x; + self.y = other.y; + self.z = P::BaseField::one(); + return; + } + let mut v = other.x * &self.z; + let mut u = other.y * &self.z; + if u == self.y && v == self.x { + // x1 / z1 == x2 / z2 <==> x1 * z2 == x2 * z1; + // Here, z2 = 1, so we have x1 == x2 * z1; + self.double_in_place(); + } else { + // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#addition-madd-1998-cmo + // u = Y2*Z1-Y1 + u -= &self.y; + // uu = u^2 + let uu = u.square(); + // v = X2*Z1-X1 + v -= &self.x; + // vv = v2 + let vv = v.square(); + // vvv = v*vv + let vvv = v * &vv; + // r = vv*X1 + let r = vv * &self.x; + // a = uu*Z1-vvv-2*r + let a = uu * &self.z - &vvv - &r.double(); + // X3 = v*a + self.x = v * &a; + // Y3 = u*(R-A)-vvv*Y1 + self.y = u * &(r - &a) - &(vvv * &self.y); + // Z3 = vvv*Z1 + self.z = vvv * &self.z; + } + } + + fn mul_assign::BigInt>>(&mut self, other: S) { + let mut res = Self::zero(); + + let mut found_one = false; + + for i in BitIterator::new(other.into()) { + if found_one { + res.double_in_place(); + } else { + found_one = i; + } + + if i { + res.add_assign(self); + } + } + + *self = res; + } + + fn into_affine(&self) -> GroupAffine

{ + (*self).into() + } + + fn recommended_wnaf_for_scalar(scalar: ::BigInt) -> usize { + P::empirical_recommended_wnaf_for_scalar(scalar) + } + + fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize { + P::empirical_recommended_wnaf_for_num_scalars(num_scalars) + } +} + +impl Neg for GroupProjective

{ + type Output = Self; + fn neg(self) -> Self { + if !self.is_zero() { + Self::new(self.x, -self.y, self.z) + } else { + self + } + } +} + +impl<'a, P: Parameters> Add<&'a Self> for GroupProjective

{ + type Output = Self; + fn add(self, other: &'a Self) -> Self { + let mut copy = self; + copy += other; + copy + } +} + +impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ + fn add_assign(&mut self, other: &'a Self) { + if self.is_zero() { + *self = *other; + return; + } + + if other.is_zero() { + return; + } + // https://www.hyperelliptic.org/EFD/g1p/data/shortw/projective/addition/add-1998-cmo-2 + + if self == other { + self.double_in_place(); + } else { + // Y1Z2 = Y1*Z2 + let y1z2 = self.y * &other.z; + // X1Z2 = X1*Z2 + let x1z2 = self.x * &other.z; + // Z1Z2 = Z1*Z2 + let z1z2 = self.z * &other.z; + // u = Y2*Z1-Y1Z2 + let u = (self.z * &other.y) - &y1z2; + // uu = u^2 + let uu = u.square(); + // v = X2*Z1-X1Z2 + let v = (self.z * &other.x) - &x1z2; + // vv = v^2 + let vv = v.square(); + // vvv = v*vv + let vvv = v * &vv; + // R = vv*X1Z2 + let r = vv * &x1z2; + // A = uu*Z1Z2-vvv-2*R + let a = (uu * &z1z2) - &(vvv + &r + &r); + // X3 = v*A + self.x = v * &a; + // Y3 = u*(R-A)-vvv*Y1Z2 + self.y = ((r - &a) * &u) - &(vvv * &y1z2); + // Z3 = vvv*Z1Z2 + self.z = vvv * &z1z2; + } + } +} + +impl<'a, P: Parameters> Sub<&'a Self> for GroupProjective

{ + type Output = Self; + fn sub(self, other: &'a Self) -> Self { + let mut copy = self; + copy -= other; + copy + } +} + +impl<'a, P: Parameters> SubAssign<&'a Self> for GroupProjective

{ + fn sub_assign(&mut self, other: &'a Self) { + *self += &(-(*other)); + } +} + +impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupProjective

{ + type Output = Self; + fn mul(self, other: &'a P::ScalarField) -> Self { + let mut copy = self; + copy *= other; + copy + } +} + +impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupProjective

{ + fn mul_assign(&mut self, other: &'a P::ScalarField) { + as ProjectiveCurve>::mul_assign(self, other.into_repr()); + } +} + +// The affine point X, Y is represented in the jacobian +// coordinates with Z = 1. +impl From> for GroupProjective

{ + fn from(p: GroupAffine

) -> GroupProjective

{ + if p.is_zero() { + Self::zero() + } else { + Self::new(p.x, p.y, P::BaseField::one()) + } + } +} + +// The projective point X, Y, Z is represented in the affine +// coordinates as X/Z^2, Y/Z^3. +impl From> for GroupAffine

{ + fn from(p: GroupProjective

) -> GroupAffine

{ + if p.is_zero() { + GroupAffine::zero() + } else if p.z.is_one() { + // If Z is one, the point is already normalized. + GroupAffine::new(p.x, p.y, false) + } else { + // Z is nonzero, so it must have an inverse in a field. + let z_inv = p.z.inverse().unwrap(); + let x = p.x * &z_inv; + let y = p.y * &z_inv; + GroupAffine::new(x, y, false) + } + } +} diff --git a/algebra/src/curves/models/twisted_edwards_extended.rs b/algebra/src/curves/models/twisted_edwards_extended.rs new file mode 100644 index 000000000..28fed97d2 --- /dev/null +++ b/algebra/src/curves/models/twisted_edwards_extended.rs @@ -0,0 +1,616 @@ +use rand::{Rand, Rng}; +use std::{ + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + curves::{models::TEModelParameters as Parameters, AffineCurve, ProjectiveCurve}, + fields::{BitIterator, Field, PrimeField, SquareRootField}, +}; + +#[derive(Derivative)] +#[derivative( + Copy(bound = "P: Parameters"), + Clone(bound = "P: Parameters"), + PartialEq(bound = "P: Parameters"), + Eq(bound = "P: Parameters"), + Debug(bound = "P: Parameters"), + Hash(bound = "P: Parameters") +)] +pub struct GroupAffine { + pub x: P::BaseField, + pub y: P::BaseField, + #[derivative(Debug = "ignore")] + _params: PhantomData

, +} + +impl Display for GroupAffine

{ + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "GroupAffine(x={}, y={})", self.x, self.y) + } +} + +impl GroupAffine

{ + pub const fn new(x: P::BaseField, y: P::BaseField) -> Self { + Self { + x, + y, + _params: PhantomData, + } + } + + #[must_use] + pub fn scale_by_cofactor(&self) -> ::Projective { + self.mul_bits(BitIterator::new(P::COFACTOR)) + } + + #[must_use] + pub(crate) fn mul_bits>( + &self, + bits: BitIterator, + ) -> ::Projective { + let mut res = GroupProjective::zero(); + for i in bits { + res.double_in_place(); + if i { + res.add_assign_mixed(self) + } + } + res + } + + /// Attempts to construct an affine point given an x-coordinate. The + /// point is not guaranteed to be in the prime order subgroup. + /// + /// If and only if `greatest` is set will the lexicographically + /// largest y-coordinate be selected. + #[allow(dead_code)] + pub(crate) fn get_point_from_x(x: P::BaseField, greatest: bool) -> Option { + let x2 = x.square(); + let one = P::BaseField::one(); + let numerator = P::mul_by_a(&x2) - &one; + let denominator = P::COEFF_D * &x2 - &one; + let y2 = denominator.inverse().map(|denom| denom * &numerator); + y2.and_then(|y2| y2.sqrt()).map(|y| { + let negy = -y; + let y = if (y < negy) ^ greatest { y } else { negy }; + Self::new(x, y) + }) + } + + /// Checks that the current point is on the elliptic curve. + pub fn is_on_curve(&self) -> bool { + let x2 = self.x.square(); + let y2 = self.y.square(); + + let lhs = y2 + &P::mul_by_a(&x2); + let rhs = P::BaseField::one() + &(P::COEFF_D * &(x2 * &y2)); + + lhs == rhs + } + + /// Checks that the current point is in the prime order subgroup given + /// the point on the curve. + pub fn is_in_correct_subgroup_assuming_on_curve(&self) -> bool { + self.mul_bits(BitIterator::new(P::ScalarField::characteristic())) + .is_zero() + } +} + +impl AffineCurve for GroupAffine

{ + type BaseField = P::BaseField; + type ScalarField = P::ScalarField; + type Projective = GroupProjective

; + + fn zero() -> Self { + Self::new(Self::BaseField::zero(), Self::BaseField::one()) + } + + fn prime_subgroup_generator() -> Self { + Self::new(P::AFFINE_GENERATOR_COEFFS.0, P::AFFINE_GENERATOR_COEFFS.1) + } + + fn is_zero(&self) -> bool { + self.x.is_zero() & self.y.is_one() + } + + fn mul::BigInt>>(&self, by: S) -> GroupProjective

{ + self.mul_bits(BitIterator::new(by.into())) + } + + fn mul_by_cofactor(&self) -> Self { + self.scale_by_cofactor().into() + } + + fn mul_by_cofactor_inv(&self) -> Self { + self.mul(P::COFACTOR_INV).into() + } + + fn into_projective(&self) -> GroupProjective

{ + (*self).into() + } +} + +impl Neg for GroupAffine

{ + type Output = Self; + + fn neg(self) -> Self { + Self::new(-self.x, self.y) + } +} + +impl<'a, P: Parameters> Add<&'a Self> for GroupAffine

{ + type Output = Self; + fn add(self, other: &'a Self) -> Self { + let mut copy = self; + copy += other; + copy + } +} + +impl<'a, P: Parameters> AddAssign<&'a Self> for GroupAffine

{ + fn add_assign(&mut self, other: &'a Self) { + let y1y2 = self.y * &other.y; + let x1x2 = self.x * &other.x; + let dx1x2y1y2 = P::COEFF_D * &y1y2 * &x1x2; + + let d1 = P::BaseField::one() + &dx1x2y1y2; + let d2 = P::BaseField::one() - &dx1x2y1y2; + + let x1y2 = self.x * &other.y; + let y1x2 = self.y * &other.x; + + self.x = (x1y2 + &y1x2) / &d1; + self.y = (y1y2 - &P::mul_by_a(&x1x2)) / &d2; + } +} + +impl<'a, P: Parameters> Sub<&'a Self> for GroupAffine

{ + type Output = Self; + fn sub(self, other: &'a Self) -> Self { + let mut copy = self; + copy -= other; + copy + } +} + +impl<'a, P: Parameters> SubAssign<&'a Self> for GroupAffine

{ + fn sub_assign(&mut self, other: &'a Self) { + *self += &(-(*other)); + } +} + +impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupAffine

{ + type Output = Self; + fn mul(self, other: &'a P::ScalarField) -> Self { + let mut copy = self; + copy *= other; + copy + } +} + +impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupAffine

{ + fn mul_assign(&mut self, other: &'a P::ScalarField) { + *self = ::mul(self, other.into_repr()).into_affine(); + } +} + +impl ToBytes for GroupAffine

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer) + } +} + +impl FromBytes for GroupAffine

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let x = P::BaseField::read(&mut reader)?; + let y = P::BaseField::read(&mut reader)?; + Ok(Self::new(x, y)) + } +} + +impl Default for GroupAffine

{ + #[inline] + fn default() -> Self { + Self::zero() + } +} + +impl Rand for GroupAffine

{ + fn rand(rng: &mut R) -> Self { + loop { + let x = rng.gen(); + let greatest = rng.gen(); + + if let Some(p) = Self::get_point_from_x(x, greatest) { + return p.scale_by_cofactor().into(); + } + } + } +} + +mod group_impl { + use super::*; + use crate::groups::Group; + + impl Group for GroupAffine

{ + type ScalarField = P::ScalarField; + fn zero() -> Self { + ::zero() + } + + fn is_zero(&self) -> bool { + ::is_zero(&self) + } + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp += self; + tmp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + let mut tmp = *self; + tmp += self; + *self = tmp; + self + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +#[derive(Derivative)] +#[derivative( + Copy(bound = "P: Parameters"), + Clone(bound = "P: Parameters"), + Eq(bound = "P: Parameters"), + Debug(bound = "P: Parameters"), + Hash(bound = "P: Parameters") +)] +pub struct GroupProjective { + pub x: P::BaseField, + pub y: P::BaseField, + pub t: P::BaseField, + pub z: P::BaseField, + #[derivative(Debug = "ignore")] + _params: PhantomData

, +} + +impl Display for GroupProjective

{ + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "{}", self.into_affine()) + } +} + +impl PartialEq for GroupProjective

{ + fn eq(&self, other: &Self) -> bool { + if self.is_zero() { + return other.is_zero(); + } + + if other.is_zero() { + return false; + } + + // x1/z1 == x2/z2 <==> x1 * z2 == x2 * z1 + (self.x * &other.z) == (other.x * &self.z) && (self.y * &other.z) == (other.y * &self.z) + } +} + +impl Rand for GroupProjective

{ + fn rand(rng: &mut R) -> Self { + loop { + let x = rng.gen(); + let greatest = rng.gen(); + + if let Some(p) = GroupAffine::get_point_from_x(x, greatest) { + return p.scale_by_cofactor(); + } + } + } +} + +impl ToBytes for GroupProjective

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.x.write(&mut writer)?; + self.y.write(&mut writer)?; + self.t.write(&mut writer)?; + self.z.write(writer) + } +} + +impl FromBytes for GroupProjective

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let x = P::BaseField::read(&mut reader)?; + let y = P::BaseField::read(&mut reader)?; + let t = P::BaseField::read(&mut reader)?; + let z = P::BaseField::read(reader)?; + Ok(Self::new(x, y, t, z)) + } +} + +impl Default for GroupProjective

{ + #[inline] + fn default() -> Self { + Self::zero() + } +} + +impl GroupProjective

{ + pub const fn new(x: P::BaseField, y: P::BaseField, t: P::BaseField, z: P::BaseField) -> Self { + Self { + x, + y, + t, + z, + _params: PhantomData, + } + } +} + +impl ProjectiveCurve for GroupProjective

{ + type BaseField = P::BaseField; + type ScalarField = P::ScalarField; + type Affine = GroupAffine

; + + fn zero() -> Self { + Self::new( + P::BaseField::zero(), + P::BaseField::one(), + P::BaseField::zero(), + P::BaseField::one(), + ) + } + + fn prime_subgroup_generator() -> Self { + GroupAffine::prime_subgroup_generator().into() + } + + fn is_zero(&self) -> bool { + self.x.is_zero() && self.y == self.z && !self.y.is_zero() && self.t.is_zero() + } + + fn is_normalized(&self) -> bool { + self.z.is_one() + } + + fn batch_normalization(v: &mut [Self]) { + // Montgomery’s Trick and Fast Implementation of Masked AES + // Genelle, Prouff and Quisquater + // Section 3.2 + + // First pass: compute [a, ab, abc, ...] + let mut prod = Vec::with_capacity(v.len()); + let mut tmp = P::BaseField::one(); + for g in v.iter_mut() + // Ignore normalized elements + .filter(|g| !g.is_normalized()) + { + tmp.mul_assign(&g.z); + prod.push(tmp); + } + + // Invert `tmp`. + tmp = tmp.inverse().unwrap(); // Guaranteed to be nonzero. + + // Second pass: iterate backwards to compute inverses + for (g, s) in v.iter_mut() + // Backwards + .rev() + // Ignore normalized elements + .filter(|g| !g.is_normalized()) + // Backwards, skip last element, fill in one for last term. + .zip(prod.into_iter().rev().skip(1).chain(Some(P::BaseField::one()))) + { + // tmp := tmp * g.z; g.z := tmp * s = 1/z + let newtmp = tmp * &g.z; + g.z = tmp * &s; + tmp = newtmp; + } + + // Perform affine transformations + for g in v.iter_mut().filter(|g| !g.is_normalized()) { + g.x *= &g.z; // x/z + g.y *= &g.z; + g.t *= &g.z; + g.z = P::BaseField::one(); // z = 1 + } + } + + fn double_in_place(&mut self) -> &mut Self { + let tmp = *self; + *self += &tmp; + self + } + + fn add_assign_mixed(&mut self, other: &Self::Affine) { + // A = X1*X2 + let a = self.x * &other.x; + // B = Y1*Y2 + let b = self.y * &other.y; + // C = T1*d*T2 + let c = P::COEFF_D * &self.t * &other.x * &other.y; + // D = Z1 + let d = self.z; + // E = (X1+Y1)*(X2+Y2)-A-B + let e = (self.x + &self.y) * &(other.x + &other.y) - &a - &b; + // F = D-C + let f = d - &c; + // G = D+C + let g = d + &c; + // H = B-a*A + let h = b - &P::mul_by_a(&a); + // X3 = E*F + self.x = e * &f; + // Y3 = G*H + self.y = g * &h; + // T3 = E*H + self.t = e * &h; + // Z3 = F*G + self.z = f * &g; + } + + fn mul_assign::BigInt>>(&mut self, other: S) { + let mut res = Self::zero(); + + let mut found_one = false; + + for i in BitIterator::new(other.into()) { + if found_one { + res.double_in_place(); + } else { + found_one = i; + } + + if i { + res.add_assign(self); + } + } + + *self = res; + } + + fn into_affine(&self) -> GroupAffine

{ + (*self).into() + } + + fn recommended_wnaf_for_scalar(scalar: ::BigInt) -> usize { + P::empirical_recommended_wnaf_for_scalar(scalar) + } + + fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize { + P::empirical_recommended_wnaf_for_num_scalars(num_scalars) + } +} + +impl Neg for GroupProjective

{ + type Output = Self; + fn neg(mut self) -> Self { + self.x = -self.x; + self.t = -self.t; + self + } +} + +impl<'a, P: Parameters> Add<&'a Self> for GroupProjective

{ + type Output = Self; + fn add(self, other: &'a Self) -> Self { + let mut copy = self; + copy += other; + copy + } +} + +impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ + fn add_assign(&mut self, other: &'a Self) { + // See "Twisted Edwards Curves Revisited" + // Huseyin Hisil, Kenneth Koon-Ho Wong, Gary Carter, and Ed Dawson + // 3.1 Unified Addition in E^e + + // A = x1 * x2 + let a = self.x * &other.x; + + // B = y1 * y2 + let b = self.y * &other.y; + + // C = d * t1 * t2 + let c = P::COEFF_D * &self.t * &other.t; + + // D = z1 * z2 + let d = self.z * &other.z; + + // H = B - aA + let h = b - &P::mul_by_a(&a); + + // E = (x1 + y1) * (x2 + y2) - A - B + let e = (self.x + &self.y) * &(other.x + &other.y) - &a - &b; + + // F = D - C + let f = d - &c; + + // G = D + C + let g = d + &c; + + // x3 = E * F + self.x = e * &f; + + // y3 = G * H + self.y = g * &h; + + // t3 = E * H + self.t = e * &h; + + // z3 = F * G + self.z = f * &g; + } +} + +impl<'a, P: Parameters> Sub<&'a Self> for GroupProjective

{ + type Output = Self; + fn sub(self, other: &'a Self) -> Self { + let mut copy = self; + copy -= other; + copy + } +} + +impl<'a, P: Parameters> SubAssign<&'a Self> for GroupProjective

{ + fn sub_assign(&mut self, other: &'a Self) { + *self += &(-(*other)); + } +} + +impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupProjective

{ + type Output = Self; + fn mul(self, other: &'a P::ScalarField) -> Self { + let mut copy = self; + copy *= other; + copy + } +} + +impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupProjective

{ + fn mul_assign(&mut self, other: &'a P::ScalarField) { + ::mul_assign(self, other.into_repr()); + } +} + +// The affine point (X, Y) is represented in the Extended Projective coordinates +// with Z = 1. +impl From> for GroupProjective

{ + fn from(p: GroupAffine

) -> GroupProjective

{ + Self::new(p.x, p.y, p.x * &p.y, P::BaseField::one()) + } +} + +// The projective point X, Y, T, Z is represented in the affine +// coordinates as X/Z, Y/Z. +impl From> for GroupAffine

{ + fn from(p: GroupProjective

) -> GroupAffine

{ + if p.is_zero() { + GroupAffine::zero() + } else if p.z.is_one() { + // If Z is one, the point is already normalized. + GroupAffine::new(p.x, p.y) + } else { + // Z is nonzero, so it must have an inverse in a field. + let z_inv = p.z.inverse().unwrap(); + let x = p.x * &z_inv; + let y = p.y * &z_inv; + GroupAffine::new(x, y) + } + } +} diff --git a/algebra/src/curves/sw6/g1.rs b/algebra/src/curves/sw6/g1.rs new file mode 100644 index 000000000..c44177cdd --- /dev/null +++ b/algebra/src/curves/sw6/g1.rs @@ -0,0 +1,135 @@ +use super::{G2Affine, SW6}; +use crate::{ + biginteger::{BigInteger384, BigInteger832}, + curves::{ + models::{ModelParameters, SWModelParameters}, + short_weierstrass_jacobian::{GroupAffine, GroupProjective}, + PairingCurve, PairingEngine, + }, + fields::sw6::{Fq, Fq6, Fr}, +}; + +pub type G1Affine = GroupAffine; +pub type G1Projective = GroupProjective; + +impl PairingCurve for G1Affine { + type Engine = SW6; + type Prepared = Self; + type PairWith = G2Affine; + type PairingResult = Fq6; + + fn prepare(&self) -> Self::Prepared { + self.clone() + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + SW6::pairing(*self, *other) + } +} + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct SW6G1Parameters; + +impl ModelParameters for SW6G1Parameters { + type BaseField = Fq; + type ScalarField = Fr; +} + +impl SWModelParameters for SW6G1Parameters { + /// COEFF_A = 5 + const COEFF_A: Fq = Fq::new(BigInteger832([ + 0x781c76643018bd7a, + 0x64f3a5a4f1d1ad48, + 0xd2f8a1eb4f72692d, + 0xc35eb123c6ed72ca, + 0xb58d6bcfd32de058, + 0x841eab13b02a492c, + 0x4b70dc5a54c487e7, + 0x2f231a8808a74c59, + 0x5e2915154d70b050, + 0x8a40fa16f37a6b37, + 0xd01980093a72c54b, + 0xef6845c25398004c, + 0x48, + ])); + + /// COEFF_B = 17764315118651679038286329069295091506801468118146712649886336045535808055361274148466772191243305528312843236347777260247138934336850548243151534538734724191505953341403463040067571652261229308333392040104884438208594329793895206056414 + const COEFF_B: Fq = Fq::new(BigInteger832([ + 0xec5bd271ad37429, + 0x9db8ac843ecca28a, + 0x94f29bcb7e01bc74, + 0x1b0bebb77bb5af0, + 0x75b8cef4aa27ee17, + 0xb5767ae80812cf6b, + 0x592fa41e377a0d8c, + 0xb6c6deedbb52df3e, + 0xcb1343e488737fd4, + 0x878020734d05b5a9, + 0x2f51354eddfa069a, + 0x498e2ecdc545243e, + 0x2c2, + ])); + + /// COFACTOR = + /// 86482221941698704497288378992285180119495364068003923046442785886272123124361700722982503222189455144364945735564951561028 + const COFACTOR: &'static [u64] = &[ + 0x5657b9b57b942344, + 0x84f9a65f3bd54eaf, + 0x5ea4214e35cd127, + 0xe3cbcbc14ec1501d, + 0xf196cb845a3092ab, + 0x7e14627ad0e19017, + 0x217db4, + ]; + + /// COFACTOR^(-1) mod r = + /// 163276846538158998893990986356139314746223949404500031940624325017036397274793417940375498603127780919653358641788 + const COFACTOR_INV: Fr = Fr::new(BigInteger384([ + 4179837108212676264, + 15545810469293120493, + 13202863094424182470, + 9506285060796071546, + 9248558385029790142, + 87030208545296111, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G1_GENERATOR_X, G1_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G1_GENERATOR_X, G1_GENERATOR_Y); +} + +/// G1_GENERATOR_X = +/// 5511163824921585887915590525772884263960974614921003940645351443740084257508990841338974915037175497689287870585840954231884082785026301437744745393958283053278991955159266640440849940136976927372133743626748847559939620888818486853646 +pub const G1_GENERATOR_X: Fq = Fq::new(BigInteger832([ + 0x5901480e5bc22290, + 0x20024afcdb9bd3a9, + 0x12dc18ff416e8138, + 0x28c69aa0ea223e18, + 0xafb1524a1eb7efe6, + 0x3d5c34edc3764ca2, + 0x736c2230c8466ce9, + 0xacfaa04e051014f1, + 0x5d5ff82f00ff2964, + 0x64c13ba270a26eaf, + 0x50e9864b56ab172e, + 0xd8370826a322499e, + 0x00000000000006f1, +])); + +/// G1_GENERATOR_Y = +/// 7913123550914612057135582061699117755797758113868200992327595317370485234417808273674357776714522052694559358668442301647906991623400754234679697332299689255516547752391831738454121261248793568285885897998257357202903170202349380518443 +pub const G1_GENERATOR_Y: Fq = Fq::new(BigInteger832([ + 0x8af8b64b402e1953, + 0xd1bbceb3a258ea51, + 0xdca9efa3140aaa0d, + 0x807a610058ddedb2, + 0xeb898562fe88076c, + 0x0e4342ca56dd8ce2, + 0x4f5528d29f1bde9a, + 0xf18b0c6c19feb372, + 0x94503ac2fac9199c, + 0xffc86a8aff08ea34, + 0xf7b1295214735d8c, + 0x44eda9e0f55edd10, + 0x0000000000000ef3, +])); diff --git a/algebra/src/curves/sw6/g2.rs b/algebra/src/curves/sw6/g2.rs new file mode 100644 index 000000000..78efecaef --- /dev/null +++ b/algebra/src/curves/sw6/g2.rs @@ -0,0 +1,244 @@ +use super::{G1Affine, FQ_ZERO, SW6}; +use crate::{ + biginteger::{BigInteger384, BigInteger832}, + curves::{ + models::{ModelParameters, SWModelParameters}, + short_weierstrass_jacobian::{GroupAffine, GroupProjective}, + PairingCurve, PairingEngine, + }, + fields::sw6::{Fq, Fq3, Fq6, Fr}, +}; + +pub type G2Affine = GroupAffine; +pub type G2Projective = GroupProjective; + +impl PairingCurve for G2Affine { + type Engine = SW6; + type Prepared = Self; + type PairWith = G1Affine; + type PairingResult = Fq6; + + fn prepare(&self) -> Self::Prepared { + self.clone() + } + + fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult { + SW6::pairing(*other, *self) + } +} + +#[derive(Copy, Clone, Default, PartialEq, Eq)] +pub struct SW6G2Parameters; + +impl ModelParameters for SW6G2Parameters { + type BaseField = Fq3; + type ScalarField = Fr; +} + +impl SWModelParameters for SW6G2Parameters { + /// COEFF_A = (0, 0, COEFF_A * TWIST^2) = (0, 0, 5) + const COEFF_A: Fq3 = Fq3::new( + FQ_ZERO, + FQ_ZERO, + Fq::new(BigInteger832([ + 0x781c76643018bd7a, + 0x64f3a5a4f1d1ad48, + 0xd2f8a1eb4f72692d, + 0xc35eb123c6ed72ca, + 0xb58d6bcfd32de058, + 0x841eab13b02a492c, + 0x4b70dc5a54c487e7, + 0x2f231a8808a74c59, + 0x5e2915154d70b050, + 0x8a40fa16f37a6b37, + 0xd01980093a72c54b, + 0xef6845c25398004c, + 0x48, + ])), + ); + + /// COEFF_B = (G1::COEFF_B * TWIST^3, 0, 0) = + /// (7237353553714858194254855835825640240663090882935418626687402315497764195116318527743248304684159666286416318482685337633828994152723793439622384740540789612754127688659139509552568164770448654259255628317166934203899992395064470477612, + /// 0, 0) + const COEFF_B: Fq3 = Fq3::new( + Fq::new(BigInteger832([ + 0xc00a9afc5cbce615, + 0x0260c2b730644102, + 0x9051e955661691ec, + 0x15f9af8514839e37, + 0xfa62826ca407172b, + 0x37043dc868f48874, + 0x876b5588d132b025, + 0x481952128335562a, + 0x4ffa729aeddd7dcd, + 0xe181a5dae94a399f, + 0x671fb50145b255d8, + 0xbc3860730482d728, + 0x00000000000023dd, + ])), + FQ_ZERO, + FQ_ZERO, + ); + + /// COFACTOR = + /// 43276679045916726782882096851503554444292580777869919574700824986947162516693702667493938255647666346010819253090121562084993205202476199057555142869892665220155573207800985012241638987472334344174208389303164492698303448192856551557283997344470334833850065978668184377503856699635686872344035470027430053642178229054516302338812152178131995800255516474185251732445975837621097393375441662426280154371264547168198834382681059556891327702516519955053315674076980350109237328216856859758931256208439575383786363605925879337208599843910819433766160937121108797819223653884174994325142959644019600 + const COFACTOR: &'static [u64] = &[ + 0x4b77fca151d50b90, + 0x8c98a12bd486d2fb, + 0x1f0c9a51593693f8, + 0x1d6f388069c063c1, + 0x556e918748f06793, + 0x2cea7dc01aae2140, + 0x4216f0595cee44d0, + 0x7a5e400154f633cf, + 0xbb74eb9b6630846b, + 0x8eb48c92998f3358, + 0xbedd37f629e8e634, + 0xc541018fe4d10cc7, + 0x574956a099ace2c3, + 0xa597504275948226, + 0x7ecaaf050acb91f3, + 0x0f25b044f4e9c932, + 0xf8c39cbf0df97780, + 0xd8f9eda95d6abf3e, + 0xd1d80da227dd39c1, + 0x8b589c61531dbce7, + 0xfee4439281455474, + 0x9eea59baa2aeb4a1, + 0xa3b8a42c4e1e6f5a, + 0xc4b99b0d9b077d21, + 0xd09033887d09b4d2, + 0x4a86d8ebb7fdf52a, + 0xbe7ce44dd084e05d, + 0x4ed25f7ebe6c44b3, + 0xd7f8e3ef00255961, + 0xa1ad2ad61580ef78, + 0x19e70d3618ca3, + ]; + + /// COFACTOR^(-1) mod r = + /// 45586359457219724873147353901735745013467692594291916855200979604570630929674383405372210802279573887880950375598 + const COFACTOR_INV: Fr = Fr::new(BigInteger384([ + 7373687189387546408, + 11284009518041539892, + 301575489693670883, + 13203058298476577559, + 18441611830097862156, + 4115759498196698, + ])); + + /// AFFINE_GENERATOR_COEFFS = (G2_GENERATOR_X, G2_GENERATOR_Y) + const AFFINE_GENERATOR_COEFFS: (Self::BaseField, Self::BaseField) = + (G2_GENERATOR_X, G2_GENERATOR_Y); +} + +const G2_GENERATOR_X: Fq3 = Fq3::new(G2_GENERATOR_X_C0, G2_GENERATOR_X_C1, G2_GENERATOR_X_C2); +const G2_GENERATOR_Y: Fq3 = Fq3::new(G2_GENERATOR_Y_C0, G2_GENERATOR_Y_C1, G2_GENERATOR_Y_C2); + +/// G2_GENERATOR_X_C0 = +/// 13426761183630949215425595811885033211332897733228446437546263564078445562454176776915160094418980045665397361295624472103734543457352048745726512354895954850428989867542989474136256025045975283415690491751906307188562464175510373683338 +pub const G2_GENERATOR_X_C0: Fq = Fq::new(BigInteger832([ + 0x03b3fe4c8d4ecac7, + 0x9568212677524d1e, + 0xf5de3f2228d187c1, + 0x7bac772e31a420ef, + 0x0255cf59968a612b, + 0x991d4676f6b5d605, + 0x02dd2ae4831d29ea, + 0xbeca7c9a62e392c2, + 0xfc1d0633d48d2fc5, + 0x7867813be5f7d2a1, + 0x6f567b6617030028, + 0xf08c9fa6ca6809df, + 0x0000000000000de9, +])); + +/// G2_GENERATOR_X_C1 = +/// 20471601555918880743198170952645906008198510944268658573129351735028343217532386920456705632337352161031960990613816401042894531220068552819818037605513359562118363589199569321421558696125646867661360498323171027455638052943806292028610 +pub const G2_GENERATOR_X_C1: Fq = Fq::new(BigInteger832([ + 0xefd1b506e5fbe05f, + 0xad27d47a4975140c, + 0xfa11540132dbc27a, + 0x8dca42b6da7c4717, + 0x66d30fd7fd76207a, + 0xb8e4f65c68932b1d, + 0x3b7f971e93ad14be, + 0xf860a89f4e582f9f, + 0x7d438aaa3986f73b, + 0xa37ec0c18c6e106a, + 0x9f2dfb98b5185b54, + 0x19995e421ca939bc, + 0x0000000000002f4f, +])); + +/// G2_GENERATOR_X_C2 = +/// 3905053196875761830053608605277158152930144841844497593936739534395003062685449846381431331169369910535935138116320442345524758217411779027270883193856999691582831339845600938304719916501940381093815781408183227875600753651697934495980 +pub const G2_GENERATOR_X_C2: Fq = Fq::new(BigInteger832([ + 0xc081ed832bdf911e, + 0xb85ff7aeebdfe7b3, + 0x96dce6bb307b14eb, + 0x578f7ded84bd824c, + 0xb799305a9971d184, + 0x0116ad33c2874b90, + 0x862dce68efdca245, + 0x4190947c70534c1d, + 0x1b1aa80334248d03, + 0xb13b07aff63fcf27, + 0x5727687b73ab4fff, + 0xf559a7f4eb8d180a, + 0x0000000000002d37, +])); + +/// G2_GENERATOR_Y_C0 = +/// 8567517639523571619872938228644013584947463594196306323477160496987712111576624702939472765993995586889532559039169098780892505598589581147768095093536988446010255611523736706017580686335404469207486594272103717837888228343074699140243 +pub const G2_GENERATOR_Y_C0: Fq = Fq::new(BigInteger832([ + 0x3f680b59e26b33d1, + 0x720fdf65b9e15b17, + 0x0f0b56def11247b1, + 0x5ea05417c8a4a52c, + 0x4ad59dc4f7c47a09, + 0xf393e0db62107115, + 0xde3b16404a53d2bb, + 0xeaa74961636280e0, + 0x2d16ccd14cf5a88c, + 0x5667565a06187d0e, + 0xb446fdc7565d0261, + 0xd3ad395d6fd0faab, + 0x0000000000000655, +])); + +/// G2_GENERATOR_Y_C1 = +/// 3890537069205870914984502594450293167889863914413852788876350245583932846980126025043974070704295857226211547108005650399870458089721518559480870503159804530091559886149680718531004778697982910253701559194337987238111062202037698927752 +pub const G2_GENERATOR_Y_C1: Fq = Fq::new(BigInteger832([ + 0x9e86cc63207679dd, + 0x4e16d9a9d87c3e47, + 0xdbee3524db80627d, + 0x137322b87d93befc, + 0x24a7ca2f9aae90a0, + 0x44abea538df3e854, + 0xc01d176c6e042eee, + 0xf5fcc4caabc75699, + 0x1f99972699a38960, + 0x30d4cc8256bf963d, + 0xa3634826edcfefff, + 0x34f3bd0c8e5a4b38, + 0x0000000000001d28, +])); + +/// G2_GENERATOR_Y_C2 = +/// 10936269922612615564271188303104593362724754284143779051599749016735041389483971486958818324356025479751246744831831158558101688599198721653921723013062333636402617118847009085485166284126970598561393411916461254016145116183331671450721 +pub const G2_GENERATOR_Y_C2: Fq = Fq::new(BigInteger832([ + 0xfc478105dedf3654, + 0xa6fcfcfdd2710d6a, + 0x05a68c283d5d4c65, + 0x9fab8d94c667a679, + 0x009b0a616ea54ff9, + 0xf0df517bc7bc6382, + 0xdb44338e7491f5b7, + 0xcd192a7e53453f45, + 0xa041a7a60982d92c, + 0x4dd01c62bae4c7ff, + 0x79a69a54e6b66178, + 0xd47b0bfe832b05f8, + 0x00000000000000ef, +])); diff --git a/algebra/src/curves/sw6/mod.rs b/algebra/src/curves/sw6/mod.rs new file mode 100644 index 000000000..6ec01ddd5 --- /dev/null +++ b/algebra/src/curves/sw6/mod.rs @@ -0,0 +1,237 @@ +use crate::{ + biginteger::BigInteger832, + curves::{PairingCurve, PairingEngine}, + fields::{ + sw6::{ + fq::{Fq, FqParameters}, + Fq3, Fq6, Fr, + }, + BitIterator, Field, FpParameters, + }, +}; + +pub mod g1; +pub use self::g1::{G1Affine, G1Projective}; + +pub mod g2; +pub use self::g2::{G2Affine, G2Projective}; + +#[cfg(test)] +mod tests; + +pub type GT = Fq6; + +#[derive(Copy, Clone, Debug)] +pub struct SW6; + +impl PairingEngine for SW6 { + type Fr = Fr; + type G1Projective = G1Projective; + type G1Affine = G1Affine; + type G2Projective = G2Projective; + type G2Affine = G2Affine; + type Fq = Fq; + type Fqe = Fq3; + type Fqk = Fq6; + + fn miller_loop<'a, I>(i: I) -> Self::Fqk + where + I: IntoIterator< + Item = &'a ( + &'a ::Prepared, + &'a ::Prepared, + ), + >, + { + let mut result = Self::Fqk::one(); + for &(ref p, ref q) in i { + result *= &SW6::ate_miller_loop(p, q); + } + result + } + + fn final_exponentiation(r: &Self::Fqk) -> Option { + Some(SW6::final_exponentiation(r)) + } +} + +impl SW6 { + pub fn ate_pairing(p: &G1Affine, q: &G2Affine) -> GT { + SW6::final_exponentiation(&SW6::ate_miller_loop(p, q)) + } + + fn ate_miller_loop(p: &G1Affine, q: &G2Affine) -> Fq6 { + use crate::curves::{models::SWModelParameters, sw6::g2::SW6G2Parameters}; + + let px = p.x; + let py = p.y; + let qx = q.x; + let qy = q.y; + let mut py_twist_squared = TWIST.square(); + py_twist_squared.mul_assign_by_fp(&py); + + let mut old_rx; + let mut old_ry; + let mut rx = qx; + let mut ry = qy; + let mut f = Fq6::one(); + + // The for loop is executed for all bits (EXCEPT the MSB itself) of + // sw6_param_p (skipping leading zeros) in MSB to LSB order + let mut found_one = false; + for bit in BitIterator::new(ATE_LOOP_COUNT) { + if !found_one && bit { + found_one = true; + continue; + } else if !found_one { + continue; + } + + old_rx = rx; + old_ry = ry; + + let old_rx_square = old_rx.square(); + let old_rx_square_3 = old_rx_square.double() + &old_rx_square; + let old_rx_square_3_a = old_rx_square_3 + &SW6G2Parameters::COEFF_A; + let old_ry_double_inverse = old_ry.double().inverse().unwrap(); + + let gamma = old_rx_square_3_a * &old_ry_double_inverse; + let gamma_twist = gamma * &TWIST; + let gamma_old_rx = gamma * &old_rx; + let mut gamma_twist_px = gamma_twist; + gamma_twist_px.mul_assign_by_fp(&px); + + let x = py_twist_squared; + let y = gamma_old_rx - &old_ry - &gamma_twist_px; + let ell_rr_at_p = Fq6::new(x, y); + + rx = gamma.square() - &old_rx.double(); + ry = gamma * &(old_rx - &rx) - &old_ry; + f = f.square() * &ell_rr_at_p; + + if bit { + old_rx = rx; + old_ry = ry; + + let gamma = (old_ry - &qy) * &((old_rx - &qx).inverse().unwrap()); + let gamma_twist = gamma * &TWIST; + let gamma_qx = gamma * &qx; + let mut gamma_twist_px = gamma_twist; + gamma_twist_px.mul_assign_by_fp(&px); + + let x = py_twist_squared; + let y = gamma_qx - &qy - &gamma_twist_px; + let ell_rq_at_p = Fq6::new(x, y); + + rx = gamma.square() - &old_rx - &qx; + ry = gamma * &(old_rx - &rx) - &old_ry; + f = f * &ell_rq_at_p; + } + } + f + } + + fn final_exponentiation(value: &Fq6) -> GT { + let value_inv = value.inverse().unwrap(); + let value_to_first_chunk = SW6::final_exponentiation_first(value, &value_inv); + let value_inv_to_first_chunk = SW6::final_exponentiation_first(&value_inv, value); + SW6::final_exponentiation_last(&value_to_first_chunk, &value_inv_to_first_chunk) + } + + fn final_exponentiation_first(elt: &Fq6, elt_inv: &Fq6) -> Fq6 { + // (q^3-1)*(q+1) + + // elt_q3 = elt^(q^3) + let mut elt_q3 = elt.clone(); + elt_q3.frobenius_map(3); + // elt_q3_over_elt = elt^(q^3-1) + let elt_q3_over_elt = elt_q3 * &elt_inv; + // alpha = elt^((q^3-1) * q) + let mut alpha = elt_q3_over_elt.clone(); + alpha.frobenius_map(1); + // beta = elt^((q^3-1)*(q+1) + alpha * &elt_q3_over_elt + } + + fn final_exponentiation_last(elt: &Fq6, elt_inv: &Fq6) -> Fq6 { + let mut elt_q = elt.clone(); + elt_q.frobenius_map(1); + + let w1_part = elt_q.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_W1); + let w0_part = match FINAL_EXPONENT_LAST_CHUNK_W0_IS_NEG { + true => elt_inv.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0), + false => elt.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0), + }; + + w1_part * &w0_part + } +} + +/// FQ_ZERO = 0 +pub const FQ_ZERO: Fq = Fq::new(BigInteger832([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); + +/// FQ_ONE = 1 +pub const FQ_ONE: Fq = Fq::new(FqParameters::R); + +/// TWIST = (0, 1, 0) +pub const TWIST: Fq3 = Fq3::new(FQ_ZERO, FQ_ONE, FQ_ZERO); + +/// ATE_IS_LOOP_COUNT_NEG = false +pub const ATE_IS_LOOP_COUNT_NEG: bool = false; + +/// ATE_LOOP_COUNT = +/// 506464946133393486072777102926336625944849939610982267859828541006717966526573193706126370441346337661774335955699621 +pub const ATE_LOOP_COUNT: [u64; 13] = [ + 0x55c5b9b57b942ae8, + 0x3d52287d3dfd424a, + 0xcf1ff9d6a543deb7, + 0x820c9c5711ceeebc, + 0x549a2d44305d20fe, + 0x50f5c131afd70235, + 0xab3596c8617c5792, + 0x830c728d80f9d78b, + 0x6a7223ee72023d07, + 0xbc5d176b746af026, + 0xe959283d8f526663, + 0xc4d2263babf8941f, + 0x3848, +]; + +/// FINAL_EXPONENT_LAST_CHUNK_W0_IS_NEG = true +pub const FINAL_EXPONENT_LAST_CHUNK_W0_IS_NEG: bool = true; + +/// FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0 = +/// 7000705447348627246181409558336018323010329260726930841638672011287206690002601216854775649561085256265269640040570922609783227469279331691880282815325569032149343779036142830666859805506518426649197067288711084398033 +pub const FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0: BigInteger832 = BigInteger832([ + 0xb62ef36af72855d1, + 0x676b5cef49d290fa, + 0xd17fcf3c60947427, + 0x5b93d992bc1b2849, + 0x2171887cecd072cb, + 0x879a2873f1516f4a, + 0x8cc6856bd2cdf24e, + 0xbff4fb6644d01993, + 0x5dcbeea3e31ea667, + 0x5f256f47681649f3, + 0x2355a2b0839967fe, + 0x144ed, + 0x0, +]); + +/// FINAL_EXPONENT_LAST_CHUNK_W1 = +/// 86482221941698704497288378992285180119495364068003923046442785886272123124361700722982503222189455144364945735564951562986 +pub const FINAL_EXPONENT_LAST_CHUNK_W1: BigInteger832 = BigInteger832([ + 0x5657b9b57b942aea, + 0x84f9a65f3bd54eaf, + 0x5ea4214e35cd127, + 0xe3cbcbc14ec1501d, + 0xf196cb845a3092ab, + 0x7e14627ad0e19017, + 0x217db4, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, +]); diff --git a/algebra/src/curves/sw6/tests.rs b/algebra/src/curves/sw6/tests.rs new file mode 100644 index 000000000..ad15d74cc --- /dev/null +++ b/algebra/src/curves/sw6/tests.rs @@ -0,0 +1,111 @@ +use crate::{ + curves::{ + sw6::{G1Affine, G1Projective, G2Affine, G2Projective, SW6}, + tests::curve_tests, + AffineCurve, PairingEngine, + }, + groups::tests::group_test, +}; + +#[test] +fn test_g1_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g1_projective_group() { + let a: G1Projective = rand::random(); + let b: G1Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g1_generator() { + let generator = G1Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_g2_projective_curve() { + curve_tests::(); +} + +#[test] +fn test_g2_projective_group() { + let a: G2Projective = rand::random(); + let b: G2Projective = rand::random(); + group_test(a, b); +} + +#[test] +fn test_g2_generator() { + let generator = G2Affine::prime_subgroup_generator(); + assert!(generator.is_on_curve()); + assert!(generator.is_in_correct_subgroup_assuming_on_curve()); +} + +#[test] +fn test_bilinearity() { + use crate::fields::{ + sw6::{fq6::Fq6, fr::Fr}, + Field, PrimeField, + }; + use rand; + + let a: G1Projective = rand::random(); + let b: G2Projective = rand::random(); + let s: Fr = rand::random(); + + let sa = a * &s; + let sb = b * &s; + + let ans1 = SW6::pairing(sa, b); + let ans2 = SW6::pairing(a, sb); + let ans3 = SW6::pairing(a, b).pow(s.into_repr()); + + assert_eq!(ans1, ans2); + assert_eq!(ans2, ans3); + + assert_ne!(ans1, Fq6::one()); + assert_ne!(ans2, Fq6::one()); + assert_ne!(ans3, Fq6::one()); + + assert_eq!(ans1.pow(Fr::characteristic()), Fq6::one()); + assert_eq!(ans2.pow(Fr::characteristic()), Fq6::one()); + assert_eq!(ans3.pow(Fr::characteristic()), Fq6::one()); +} + +#[test] +#[ignore] +fn print_g1_generator() { + use crate::fields::sw6::fq::Fq; + + let x: Fq = "5511163824921585887915590525772884263960974614921003940645351443740084257508990841338974915037175497689287870585840954231884082785026301437744745393958283053278991955159266640440849940136976927372133743626748847559939620888818486853646".parse().unwrap(); + let y: Fq = "7913123550914612057135582061699117755797758113868200992327595317370485234417808273674357776714522052694559358668442301647906991623400754234679697332299689255516547752391831738454121261248793568285885897998257357202903170202349380518443".parse().unwrap(); + + println!("pub const G1_GENERATOR_X: Fq = Fq::new({});", x.0); + println!("pub const G1_GENERATOR_Y: Fq = Fq::new({});", y.0); +} + +#[test] +#[ignore] +fn print_g2_generator() { + use crate::fields::sw6::fq::Fq; + + let x_c0: Fq = "13426761183630949215425595811885033211332897733228446437546263564078445562454176776915160094418980045665397361295624472103734543457352048745726512354895954850428989867542989474136256025045975283415690491751906307188562464175510373683338".parse().unwrap(); + let x_c1: Fq = "20471601555918880743198170952645906008198510944268658573129351735028343217532386920456705632337352161031960990613816401042894531220068552819818037605513359562118363589199569321421558696125646867661360498323171027455638052943806292028610".parse().unwrap(); + let x_c2: Fq = "3905053196875761830053608605277158152930144841844497593936739534395003062685449846381431331169369910535935138116320442345524758217411779027270883193856999691582831339845600938304719916501940381093815781408183227875600753651697934495980".parse().unwrap(); + + let y_c0: Fq = "8567517639523571619872938228644013584947463594196306323477160496987712111576624702939472765993995586889532559039169098780892505598589581147768095093536988446010255611523736706017580686335404469207486594272103717837888228343074699140243".parse().unwrap(); + let y_c1: Fq = "3890537069205870914984502594450293167889863914413852788876350245583932846980126025043974070704295857226211547108005650399870458089721518559480870503159804530091559886149680718531004778697982910253701559194337987238111062202037698927752".parse().unwrap(); + let y_c2: Fq = "10936269922612615564271188303104593362724754284143779051599749016735041389483971486958818324356025479751246744831831158558101688599198721653921723013062333636402617118847009085485166284126970598561393411916461254016145116183331671450721".parse().unwrap(); + + println!("pub const G2_GENERATOR_X_C0: Fq = Fq::new({});", x_c0.0); + println!("pub const G2_GENERATOR_X_C1: Fq = Fq::new({});", x_c1.0); + println!("pub const G2_GENERATOR_X_C2: Fq = Fq::new({});", x_c2.0); + + println!("pub const G2_GENERATOR_Y_C0: Fq = Fq::new({});", y_c0.0); + println!("pub const G2_GENERATOR_Y_C1: Fq = Fq::new({});", y_c1.0); + println!("pub const G2_GENERATOR_Y_C2: Fq = Fq::new({});", y_c2.0); +} diff --git a/algebra/src/curves/tests.rs b/algebra/src/curves/tests.rs new file mode 100644 index 000000000..064982228 --- /dev/null +++ b/algebra/src/curves/tests.rs @@ -0,0 +1,280 @@ +use crate::{ + curves::{AffineCurve, ProjectiveCurve}, + fields::{Field, PrimeField}, +}; +use rand::{Rand, SeedableRng, XorShiftRng}; + +pub const ITERATIONS: usize = 10; + +fn random_addition_test() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let a = G::rand(&mut rng); + let b = G::rand(&mut rng); + let c = G::rand(&mut rng); + let a_affine = a.into_affine(); + let b_affine = b.into_affine(); + let c_affine = c.into_affine(); + + // a + a should equal the doubling + { + let mut aplusa = a; + aplusa.add_assign(&a); + + let mut aplusamixed = a; + aplusamixed.add_assign_mixed(&a.into_affine()); + + let mut adouble = a; + adouble.double_in_place(); + + assert_eq!(aplusa, adouble); + assert_eq!(aplusa, aplusamixed); + } + + let mut tmp = vec![G::zero(); 6]; + + // (a + b) + c + tmp[0] = (a + &b) + &c; + + // a + (b + c) + tmp[1] = a + &(b + &c); + + // (a + c) + b + tmp[2] = (a + &c) + &b; + + // Mixed addition + + // (a + b) + c + tmp[3] = a_affine.into_projective(); + tmp[3].add_assign_mixed(&b_affine); + tmp[3].add_assign_mixed(&c_affine); + + // a + (b + c) + tmp[4] = b_affine.into_projective(); + tmp[4].add_assign_mixed(&c_affine); + tmp[4].add_assign_mixed(&a_affine); + + // (a + c) + b + tmp[5] = a_affine.into_projective(); + tmp[5].add_assign_mixed(&c_affine); + tmp[5].add_assign_mixed(&b_affine); + + // Comparisons + for i in 0..6 { + for j in 0..6 { + if tmp[i] != tmp[j] { + println!("{} \n{}", tmp[i], tmp[j]); + } + assert_eq!(tmp[i], tmp[j], "Associativity failed {} {}", i, j); + assert_eq!( + tmp[i].into_affine(), + tmp[j].into_affine(), + "Associativity failed" + ); + } + + assert!(tmp[i] != a); + assert!(tmp[i] != b); + assert!(tmp[i] != c); + + assert!(a != tmp[i]); + assert!(b != tmp[i]); + assert!(c != tmp[i]); + } + } +} + +fn random_multiplication_test() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let mut a = G::rand(&mut rng); + let mut b = G::rand(&mut rng); + let a_affine = a.into_affine(); + let b_affine = b.into_affine(); + + let s = G::ScalarField::rand(&mut rng); + + // s ( a + b ) + let mut tmp1 = a; + tmp1.add_assign(&b); + tmp1.mul_assign(s.into_repr()); + + // sa + sb + a.mul_assign(s.into_repr()); + b.mul_assign(s.into_repr()); + + let mut tmp2 = a; + tmp2.add_assign(&b); + + // Affine multiplication + let mut tmp3 = a_affine.mul(s.into_repr()); + tmp3.add_assign(&b_affine.mul(s.into_repr())); + + assert_eq!(tmp1, tmp2); + assert_eq!(tmp1, tmp3); + } +} + +fn random_doubling_test() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let mut a = G::rand(&mut rng); + let mut b = G::rand(&mut rng); + + // 2(a + b) + let mut tmp1 = a; + tmp1.add_assign(&b); + tmp1.double_in_place(); + + // 2a + 2b + a.double_in_place(); + b.double_in_place(); + + let mut tmp2 = a; + tmp2.add_assign(&b); + + let mut tmp3 = a; + tmp3.add_assign_mixed(&b.into_affine()); + + assert_eq!(tmp1, tmp2); + assert_eq!(tmp1, tmp3); + } +} + +fn random_negation_test() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let r = G::rand(&mut rng); + + let s = G::ScalarField::rand(&mut rng); + let sneg = -s; + assert!((s + &sneg).is_zero()); + + let mut t1 = r; + t1.mul_assign(s); + + let mut t2 = r; + t2.mul_assign(sneg); + + let mut t3 = t1; + t3.add_assign(&t2); + println!("t3 = {}", t3); + assert!(t3.is_zero()); + + let mut t4 = t1; + t4.add_assign_mixed(&t2.into_affine()); + assert!(t4.is_zero()); + + t1 = -t1; + assert_eq!(t1, t2); + } +} + +fn random_transformation_test() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let g = G::rand(&mut rng); + let g_affine = g.into_affine(); + let g_projective = g_affine.into_projective(); + assert_eq!(g, g_projective); + } + + // Batch normalization + for _ in 0..10 { + let mut v = (0..ITERATIONS) + .map(|_| G::rand(&mut rng)) + .collect::>(); + + for i in &v { + assert!(!i.is_normalized()); + } + + use rand::distributions::{IndependentSample, Range}; + let between = Range::new(0, ITERATIONS); + // Sprinkle in some normalized points + for _ in 0..5 { + v[between.ind_sample(&mut rng)] = G::zero(); + } + for _ in 0..5 { + let s = between.ind_sample(&mut rng); + v[s] = v[s].into_affine().into_projective(); + } + + let expected_v = v + .iter() + .map(|v| v.into_affine().into_projective()) + .collect::>(); + G::batch_normalization(&mut v); + + for i in &v { + assert!(i.is_normalized()); + } + + assert_eq!(v, expected_v); + } +} + +pub fn curve_tests() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + // Negation edge case with zero. + { + let z = -G::zero(); + assert!(z.is_zero()); + } + + // Doubling edge case with zero. + { + let mut z = -G::zero(); + z.double_in_place(); + assert!(z.is_zero()); + } + + // Addition edge cases with zero + { + let mut r = G::rand(&mut rng); + let rcopy = r; + r.add_assign(&G::zero()); + assert_eq!(r, rcopy); + r.add_assign_mixed(&G::Affine::zero()); + assert_eq!(r, rcopy); + + let mut z = G::zero(); + z.add_assign(&G::zero()); + assert!(z.is_zero()); + z.add_assign_mixed(&G::Affine::zero()); + assert!(z.is_zero()); + + let mut z2 = z; + z2.add_assign(&r); + + z.add_assign_mixed(&r.into_affine()); + + assert_eq!(z, z2); + assert_eq!(z, r); + } + + // Transformations + { + let a = G::rand(&mut rng); + let b = a.into_affine().into_projective(); + let c = a + .into_affine() + .into_projective() + .into_affine() + .into_projective(); + assert_eq!(a, b); + assert_eq!(b, c); + } + + random_addition_test::(); + random_multiplication_test::(); + random_doubling_test::(); + random_negation_test::(); + random_transformation_test::(); +} diff --git a/algebra/src/fft/domain.rs b/algebra/src/fft/domain.rs new file mode 100644 index 000000000..59ea0c9bb --- /dev/null +++ b/algebra/src/fft/domain.rs @@ -0,0 +1,444 @@ +//! This module contains an `EvaluationDomain` abstraction for +//! performing various kinds of polynomial arithmetic on top of +//! the scalar field. +//! +//! In pairing-based SNARKs like GM17, we need to calculate +//! a quotient polynomial over a target polynomial with roots +//! at distinct points associated with each constraint of the +//! constraint system. In order to be efficient, we choose these +//! roots to be the powers of a 2^n root of unity in the field. +//! This allows us to perform polynomial operations in O(n) +//! by performing an O(n log n) FFT over such a domain. + +use crate::{Field, FpParameters, PairingEngine, PrimeField, ProjectiveCurve, SquareRootField}; + +use super::multicore::Worker; +use std::{ + marker::PhantomData, + ops::{AddAssign, MulAssign, SubAssign}, +}; + +pub struct EvaluationDomain, G: DomainGroup> { + pub(crate) coeffs: Vec, + pub(crate) exp: u32, + pub(crate) omega: G::ScalarField, + pub(crate) omega_inv: G::ScalarField, + pub(crate) geninv: G::ScalarField, + pub(crate) m_inv: G::ScalarField, + pub(crate) m: u64, + _engine: PhantomData, +} + +impl, G: DomainGroup> Clone for EvaluationDomain { + fn clone(&self) -> Self { + Self { + coeffs: self.coeffs.clone(), + ..*self + } + } +} + +impl, G: DomainGroup> EvaluationDomain { + pub fn compute_m_from_num_coeffs(num_coeffs: usize) -> Option { + let m = num_coeffs.next_power_of_two(); + let exp = m.trailing_zeros(); // exp = log_2(m) + if exp < ::Params::TWO_ADICITY { + Some(m) + } else { + None + } + } + + pub fn m(&self) -> usize { + self.m as usize + } + + pub fn as_ref(&self) -> &[G] { + &self.coeffs + } + + pub fn as_mut(&mut self) -> &mut [G] { + &mut self.coeffs + } + + pub fn into_coeffs(self) -> Vec { + self.coeffs + } + + pub fn from_coeffs(mut coeffs: Vec) -> Option> { + // Compute the size of our evaluation domain + let m = coeffs.len().next_power_of_two() as u64; + let exp = m.trailing_zeros(); // exp = log_2(m) + + if exp >= ::Params::TWO_ADICITY { + return None; + } + + // Compute omega, the 2^exp primitive root of unity + let mut omega = G::ScalarField::root_of_unity(); + for _ in exp..::Params::TWO_ADICITY { + omega.square_in_place(); + } + + // Extend the coeffs vector with zeroes if necessary + coeffs.resize(m as usize, G::group_zero()); + + let m_bigint = <::Fr as PrimeField>::BigInt::from(m); + let m_inv = G::ScalarField::from_repr(m_bigint).inverse().unwrap(); + + Some(EvaluationDomain { + coeffs, + exp, + omega, + omega_inv: omega.inverse().unwrap(), + geninv: G::ScalarField::multiplicative_generator() + .inverse() + .unwrap(), + m_inv, + m, + _engine: PhantomData, + }) + } + + pub fn fft(&mut self, worker: &Worker) { + best_fft(&mut self.coeffs, worker, &self.omega, self.exp); + } + + pub fn ifft(&mut self, worker: &Worker) { + best_fft(&mut self.coeffs, worker, &self.omega_inv, self.exp); + + worker.scope(self.coeffs.len(), |scope, chunk| { + let m_inv = self.m_inv; + + for v in self.coeffs.chunks_mut(chunk) { + scope.spawn(move |_| { + for v in v { + v.group_mul_assign(&m_inv); + } + }); + } + }); + } + + pub fn distribute_powers(&mut self, worker: &Worker, g: G::ScalarField) { + worker.scope(self.coeffs.len(), |scope, chunk| { + for (i, v) in self.coeffs.chunks_mut(chunk).enumerate() { + scope.spawn(move |_| { + let mut u = g.pow(&[(i * chunk) as u64]); + for v in v.iter_mut() { + v.group_mul_assign(&u); + u.mul_assign(&g); + } + }); + } + }); + } + + pub fn coset_fft(&mut self, worker: &Worker) { + self.distribute_powers(worker, G::ScalarField::multiplicative_generator()); + self.fft(worker); + } + + pub fn icoset_fft(&mut self, worker: &Worker) { + let geninv = self.geninv; + + self.ifft(worker); + self.distribute_powers(worker, geninv); + } + + pub fn evaluate_all_lagrange_coefficients(&self, tau: &G::ScalarField) -> Vec { + // Evaluate all Lagrange polynomials + let m = self.m as usize; + let t_m = tau.pow(&[self.m]); + let one = G::ScalarField::one(); + if t_m == one { + let mut u = vec![G::ScalarField::zero(); m]; + let mut omega_i = one; + for i in 0..m { + if omega_i == *tau { + u[i] = one; + break; + } + omega_i.mul_assign(&self.omega); + } + u + } else { + use crate::fields::batch_inversion; + use rayon::prelude::*; + + let mut l = (t_m - &one) * &self.m_inv; + let mut r = one; + let mut u = vec![G::ScalarField::zero(); m]; + let mut ls = vec![G::ScalarField::zero(); m]; + for i in 0..m { + u[i] = *tau - &r; + ls[i] = l; + l.mul_assign(&self.omega); + r.mul_assign(&self.omega); + } + + batch_inversion(u.as_mut_slice()); + u.par_iter_mut().zip(ls).for_each(|(tau_minus_r, l)| { + *tau_minus_r = l * tau_minus_r; + }); + u + } + } + + /// This evaluates t(tau) for this domain, which is + /// tau^m - 1 for these radix-2 domains. + pub fn z(&self, tau: &G::ScalarField) -> G::ScalarField { + let mut tmp = tau.pow(&[self.coeffs.len() as u64]); + tmp.sub_assign(&G::ScalarField::one()); + + tmp + } + + /// The target polynomial is the zero polynomial in our + /// evaluation domain, so we must perform division over + /// a coset. + pub fn divide_by_z_on_coset(&mut self, worker: &Worker) { + let i = self + .z(&G::ScalarField::multiplicative_generator()) + .inverse() + .unwrap(); + + worker.scope(self.coeffs.len(), |scope, chunk| { + for v in self.coeffs.chunks_mut(chunk) { + scope.spawn(move |_| { + for v in v { + v.group_mul_assign(&i); + } + }); + } + }); + } + + /// Perform O(n) multiplication of two polynomials in the domain. + pub fn mul_assign(&mut self, worker: &Worker, other: &EvaluationDomain>) { + assert_eq!(self.coeffs.len(), other.coeffs.len()); + + worker.scope(self.coeffs.len(), |scope, chunk| { + for (a, b) in self + .coeffs + .chunks_mut(chunk) + .zip(other.coeffs.chunks(chunk)) + { + scope.spawn(move |_| { + for (a, b) in a.iter_mut().zip(b.iter()) { + a.group_mul_assign(&b.0); + } + }); + } + }); + } + + /// Perform O(n) subtraction of one polynomial from another in the domain. + pub fn sub_assign(&mut self, worker: &Worker, other: &EvaluationDomain) { + assert_eq!(self.coeffs.len(), other.coeffs.len()); + + worker.scope(self.coeffs.len(), |scope, chunk| { + for (a, b) in self + .coeffs + .chunks_mut(chunk) + .zip(other.coeffs.chunks(chunk)) + { + scope.spawn(move |_| { + for (a, b) in a.iter_mut().zip(b.iter()) { + a.group_sub_assign(&b); + } + }); + } + }); + } +} + +pub trait DomainGroup: Sized + Copy + Clone + Send + Sync { + type ScalarField: PrimeField + SquareRootField + Into<::BigInt>; + fn group_zero() -> Self; + fn group_mul_assign(&mut self, by: &Self::ScalarField); + fn group_add_assign(&mut self, other: &Self); + fn group_sub_assign(&mut self, other: &Self); +} + +pub struct Point(pub G); + +impl PartialEq for Point { + fn eq(&self, other: &Point) -> bool { + self.0 == other.0 + } +} + +impl Copy for Point {} + +impl Clone for Point { + fn clone(&self) -> Point { + *self + } +} + +impl DomainGroup for Point { + type ScalarField = G::ScalarField; + + fn group_zero() -> Self { + Point(G::zero()) + } + + fn group_mul_assign(&mut self, by: &Self::ScalarField) { + self.0.mul_assign(by.into_repr()); + } + + fn group_add_assign(&mut self, other: &Self) { + self.0.add_assign(&other.0); + } + + fn group_sub_assign(&mut self, other: &Self) { + self.0.sub_assign(&other.0); + } +} + +pub struct Scalar(pub E::Fr); + +impl PartialEq for Scalar { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +impl Copy for Scalar {} + +impl Clone for Scalar { + fn clone(&self) -> Scalar { + *self + } +} + +impl DomainGroup for Scalar { + type ScalarField = E::Fr; + + fn group_zero() -> Self { + Scalar(E::Fr::zero()) + } + fn group_mul_assign(&mut self, by: &Self::ScalarField) { + self.0.mul_assign(by); + } + fn group_add_assign(&mut self, other: &Self) { + self.0.add_assign(&other.0); + } + fn group_sub_assign(&mut self, other: &Self) { + self.0.sub_assign(&other.0); + } +} + +fn best_fft(a: &mut [G], worker: &Worker, omega: &G::ScalarField, log_n: u32) { + let log_cpus = worker.log_num_cpus(); + + if log_n <= log_cpus { + serial_fft(a, omega, log_n); + } else { + parallel_fft(a, worker, omega, log_n, log_cpus); + } +} + +pub(crate) fn serial_fft(a: &mut [G], omega: &G::ScalarField, log_n: u32) { + #[inline] + fn bitreverse(mut n: u32, l: u32) -> u32 { + let mut r = 0; + for _ in 0..l { + r = (r << 1) | (n & 1); + n >>= 1; + } + r + } + + let n = a.len() as u32; + assert_eq!(n, 1 << log_n); + + for k in 0..n { + let rk = bitreverse(k, log_n); + if k < rk { + a.swap(rk as usize, k as usize); + } + } + + let mut m = 1; + for _ in 0..log_n { + let w_m = omega.pow(&[(n / (2 * m)) as u64]); + + let mut k = 0; + while k < n { + let mut w = G::ScalarField::one(); + for j in 0..m { + let mut t = a[(k + j + m) as usize]; + t.group_mul_assign(&w); + let mut tmp = a[(k + j) as usize]; + tmp.group_sub_assign(&t); + a[(k + j + m) as usize] = tmp; + a[(k + j) as usize].group_add_assign(&t); + w.mul_assign(&w_m); + } + + k += 2 * m; + } + + m *= 2; + } +} + +pub(crate) fn parallel_fft( + a: &mut [G], + worker: &Worker, + omega: &G::ScalarField, + log_n: u32, + log_cpus: u32, +) { + assert!(log_n >= log_cpus); + + let num_cpus = 1 << log_cpus; + let log_new_n = log_n - log_cpus; + let mut tmp = vec![vec![G::group_zero(); 1 << log_new_n]; num_cpus]; + let new_omega = omega.pow(&[num_cpus as u64]); + + worker.scope(0, |scope, _| { + let a = &*a; + + for (j, tmp) in tmp.iter_mut().enumerate() { + scope.spawn(move |_| { + // Shuffle into a sub-FFT + let omega_j = omega.pow(&[j as u64]); + let omega_step = omega.pow(&[(j as u64) << log_new_n]); + + let mut elt = G::ScalarField::one(); + for i in 0..(1 << log_new_n) { + for s in 0..num_cpus { + let idx = (i + (s << log_new_n)) % (1 << log_n); + let mut t = a[idx]; + t.group_mul_assign(&elt); + tmp[i].group_add_assign(&t); + elt.mul_assign(&omega_step); + } + elt.mul_assign(&omega_j); + } + + // Perform sub-FFT + serial_fft(tmp, &new_omega, log_new_n); + }); + } + }); + + // TODO: does this hurt or help? + worker.scope(a.len(), |scope, chunk| { + let tmp = &tmp; + + for (idx, a) in a.chunks_mut(chunk).enumerate() { + scope.spawn(move |_| { + let mut idx = idx * chunk; + let mask = (1 << log_cpus) - 1; + for a in a { + *a = tmp[idx & mask][idx >> log_cpus]; + idx += 1; + } + }); + } + }); +} diff --git a/algebra/src/fft/mod.rs b/algebra/src/fft/mod.rs new file mode 100644 index 000000000..55b8805f7 --- /dev/null +++ b/algebra/src/fft/mod.rs @@ -0,0 +1,5 @@ +pub mod domain; +pub mod multicore; + +#[cfg(test)] +mod test; diff --git a/algebra/src/fft/multicore.rs b/algebra/src/fft/multicore.rs new file mode 100644 index 000000000..71c8bf0b4 --- /dev/null +++ b/algebra/src/fft/multicore.rs @@ -0,0 +1,58 @@ +//! This is an interface for dealing with the kinds of +//! parallel computations involved in `snark`. It's +//! currently just a thin wrapper around `rayon`. +use rayon::{self, Scope}; + +#[derive(Clone)] +pub struct Worker { + cpus: usize, +} + +impl Worker { + pub fn new() -> Worker { + let cpus = rayon::current_num_threads(); + Self { cpus } + } + + pub fn log_num_cpus(&self) -> u32 { + log2_floor(self.cpus) + } + + pub fn scope<'a, F, R>(&self, elements: usize, f: F) -> R + where + F: 'a + Send + FnOnce(&Scope<'a>, usize) -> R, + R: Send, + { + let chunk_size = if elements < self.cpus { + 1 + } else { + elements / self.cpus + }; + + rayon::scope(move |scope| f(scope, chunk_size)) + } +} + +fn log2_floor(num: usize) -> u32 { + assert!(num > 0); + + let mut pow = 0; + + while (1 << (pow + 1)) <= num { + pow += 1; + } + + pow +} + +#[test] +fn test_log2_floor() { + assert_eq!(log2_floor(1), 0); + assert_eq!(log2_floor(2), 1); + assert_eq!(log2_floor(3), 1); + assert_eq!(log2_floor(4), 2); + assert_eq!(log2_floor(5), 2); + assert_eq!(log2_floor(6), 2); + assert_eq!(log2_floor(7), 2); + assert_eq!(log2_floor(8), 3); +} diff --git a/algebra/src/fft/test.rs b/algebra/src/fft/test.rs new file mode 100644 index 000000000..b0c2385b5 --- /dev/null +++ b/algebra/src/fft/test.rs @@ -0,0 +1,120 @@ +use crate::{ + curves::{bls12_381::Bls12_381, PairingEngine}, + fft::{domain::*, multicore::*}, + fields::Field, +}; +use rand::{self, Rand}; +use std::cmp::min; + +// Test multiplying various (low degree) polynomials together and +// comparing with naive evaluations. +#[test] +fn polynomial_arith() { + fn test_mul(rng: &mut R) { + let worker = Worker::new(); + + for coeffs_a in 0..70 { + for coeffs_b in 0..70 { + let mut a: Vec<_> = (0..coeffs_a) + .map(|_| Scalar::(E::Fr::rand(rng))) + .collect(); + let mut b: Vec<_> = (0..coeffs_b) + .map(|_| Scalar::(E::Fr::rand(rng))) + .collect(); + + // naive evaluation + let mut naive = vec![Scalar(E::Fr::zero()); coeffs_a + coeffs_b]; + for (i1, a) in a.iter().enumerate() { + for (i2, b) in b.iter().enumerate() { + let mut prod = *a; + prod.group_mul_assign(&b.0); + naive[i1 + i2].group_add_assign(&prod); + } + } + + a.resize(coeffs_a + coeffs_b, Scalar(E::Fr::zero())); + b.resize(coeffs_a + coeffs_b, Scalar(E::Fr::zero())); + + let mut a = EvaluationDomain::from_coeffs(a).unwrap(); + let mut b = EvaluationDomain::from_coeffs(b).unwrap(); + + a.fft(&worker); + b.fft(&worker); + a.mul_assign(&worker, &b); + a.ifft(&worker); + + for (naive, fft) in naive.iter().zip(a.coeffs.iter()) { + assert!(naive == fft); + } + } + } + } + + let rng = &mut rand::thread_rng(); + + test_mul::(rng); +} + +#[test] +fn fft_composition() { + fn test_comp(rng: &mut R) { + let worker = Worker::new(); + + for coeffs in 0..10 { + let coeffs = 1 << coeffs; + + let mut v = vec![]; + for _ in 0..coeffs { + v.push(Scalar::(rng.gen())); + } + + let mut domain = EvaluationDomain::::from_coeffs(v.clone()).unwrap(); + domain.ifft(&worker); + domain.fft(&worker); + assert!(v == domain.coeffs); + domain.fft(&worker); + domain.ifft(&worker); + assert!(v == domain.coeffs); + domain.icoset_fft(&worker); + domain.coset_fft(&worker); + assert!(v == domain.coeffs); + domain.coset_fft(&worker); + domain.icoset_fft(&worker); + assert!(v == domain.coeffs); + } + } + + let rng = &mut rand::thread_rng(); + + test_comp::(rng); +} + +#[test] +fn parallel_fft_consistency() { + fn test_consistency(rng: &mut R) { + let worker = Worker::new(); + + for _ in 0..5 { + for log_d in 0..10 { + let d = 1 << log_d; + + let v1 = (0..d) + .map(|_| Scalar::(E::Fr::rand(rng))) + .collect::>(); + let mut v1 = EvaluationDomain::::from_coeffs(v1).unwrap(); + let mut v2 = EvaluationDomain::::from_coeffs(v1.coeffs.clone()).unwrap(); + + for log_cpus in log_d..min(log_d + 1, 3) { + parallel_fft(&mut v1.coeffs, &worker, &v1.omega, log_d, log_cpus); + serial_fft(&mut v2.coeffs, &v2.omega, log_d); + + assert!(v1.coeffs == v2.coeffs); + } + } + } + } + + let rng = &mut rand::thread_rng(); + + test_consistency::(rng); +} diff --git a/algebra/src/fields/bls12_377/fq.rs b/algebra/src/fields/bls12_377/fq.rs new file mode 100644 index 000000000..a4c96d4df --- /dev/null +++ b/algebra/src/fields/bls12_377/fq.rs @@ -0,0 +1,103 @@ +use crate::{ + biginteger::BigInteger384 as BigInteger, + fields::{Fp384, Fp384Parameters, FpParameters}, +}; + +pub type Fq = Fp384; + +pub struct FqParameters; + +impl Fp384Parameters for FqParameters {} +impl FpParameters for FqParameters { + type BigInt = BigInteger; + + // MODULUS = 258664426012969094010652733694893533536393512754914660539884262666720468348340822774968888139573360124440321458177 + const MODULUS: BigInteger = BigInteger([ + 0x8508c00000000001, + 0x170b5d4430000000, + 0x1ef3622fba094800, + 0x1a22d9f300f5138f, + 0xc63b05c06ca1493b, + 0x1ae3a4617c510ea, + ]); + + const MODULUS_BITS: u32 = 377; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 7; + + const R: BigInteger = BigInteger([ + 202099033278250856u64, + 5854854902718660529u64, + 11492539364873682930u64, + 8885205928937022213u64, + 5545221690922665192u64, + 39800542322357402u64, + ]); + + const R2: BigInteger = BigInteger([ + 0xb786686c9400cd22, + 0x329fcaab00431b1, + 0x22a5f11162d6b46d, + 0xbfdf7d03827dc3ac, + 0x837e92f041790bf9, + 0x6dfccb1e914b88, + ]); + + const INV: u64 = 9586122913090633727u64; + + // GENERATOR = -5 + const GENERATOR: BigInteger = BigInteger([ + 0xfc0b8000000002fa, + 0x97d39cf6e000018b, + 0x2072420fbfa05044, + 0xcbbcbd50d97c3802, + 0xbaf1ec35813f9eb, + 0x9974a2c0945ad2, + ]); + + const TWO_ADICITY: u32 = 46u32; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 2022196864061697551u64, + 17419102863309525423u64, + 8564289679875062096u64, + 17152078065055548215u64, + 17966377291017729567u64, + 68610905582439508u64, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x4284600000000000, + 0xb85aea218000000, + 0x8f79b117dd04a400, + 0x8d116cf9807a89c7, + 0x631d82e03650a49d, + 0xd71d230be28875, + ]); + + // T and T_MINUS_ONE_DIV_TWO, where MODULUS - 1 = 2^S * T + + // T = (MODULUS - 1) // 2^S = + // 3675842578061421676390135839012792950148785745837396071634149488243117337281387659330802195819009059 + const T: BigInteger = BigInteger([ + 0x7510c00000021423, + 0x88bee82520005c2d, + 0x67cc03d44e3c7bcd, + 0x1701b28524ec688b, + 0xe9185f1443ab18ec, + 0x6b8, + ]); + + // (T - 1) // 2 = + // 1837921289030710838195067919506396475074392872918698035817074744121558668640693829665401097909504529 + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0xba88600000010a11, + 0xc45f741290002e16, + 0xb3e601ea271e3de6, + 0xb80d94292763445, + 0x748c2f8a21d58c76, + 0x35c, + ]); +} diff --git a/algebra/src/fields/bls12_377/fq12.rs b/algebra/src/fields/bls12_377/fq12.rs new file mode 100644 index 000000000..9e2e9b3f0 --- /dev/null +++ b/algebra/src/fields/bls12_377/fq12.rs @@ -0,0 +1,163 @@ +use crate::{ + biginteger::BigInteger384, + fields::{ + bls12_377::{fq::Fq, fq2::Fq2, fq6::Fq6Parameters}, + fp12_2over3over2::{Fp12, Fp12Parameters}, + }, +}; + +pub type Fq12 = Fp12; + +#[derive(Clone, Copy)] +pub struct Fq12Parameters; + +impl Fp12Parameters for Fq12Parameters { + type Fp6Params = Fq6Parameters; + + const FROBENIUS_COEFF_FP12_C1: [Fq2; 12] = [ + // Fp2::NONRESIDUE^(((q^0) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x2cdffffffffff68, + 0x51409f837fffffb1, + 0x9f7db3a98a7d3ff2, + 0x7b4e97b76e7c6305, + 0x4cf495bf803c84e8, + 0x8d6661e2fdf49a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^1) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x6ec47a04a3f7ca9e, + 0xa42e0cb968c1fa44, + 0x578d5187fbd2bd23, + 0x930eeb0ac79dd4bd, + 0xa24883de1e09a9ee, + 0xdaa7058067d46f, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^2) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x5892506da58478da, + 0x133366940ac2a74b, + 0x9b64a150cdf726cf, + 0x5cc426090a9c587e, + 0x5cf848adfdcd640c, + 0x4702bf3ac02380, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^3) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x982c13d9d084771f, + 0xfd49de0c6da34a32, + 0x61a530d183ab0e53, + 0xdf8fe44106dd9879, + 0x40f29b58d88472bc, + 0x158723199046d5d, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^4) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0xdacd106da5847973, + 0xd8fe2454bac2a79a, + 0x1ada4fd6fd832edc, + 0xfb9868449d150908, + 0xd63eb8aeea32285e, + 0x167d6a36f873fd0, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^5) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x296799d52c8cac81, + 0x591bd15304e14fee, + 0xa17df4987d85130, + 0x4c80f9363f3fc3bc, + 0x9eaa177aba7ac8ce, + 0x7dcb2c189c98ed, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^6) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x823ac00000000099, + 0xc5cabdc0b000004f, + 0x7f75ae862f8c080d, + 0x9ed4423b9278b089, + 0x79467000ec64c452, + 0x120d3e434c71c50, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^7) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x164445fb5c083563, + 0x72dd508ac73e05bc, + 0xc76610a7be368adc, + 0x8713eee839573ed1, + 0x23f281e24e979f4c, + 0xd39340975d3c7b, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^8) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x2c766f925a7b8727, + 0x3d7f6b0253d58b5, + 0x838ec0deec122131, + 0xbd5eb3e9f658bb10, + 0x6942bd126ed3e52e, + 0x1673786dd04ed6a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^9) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0xecdcac262f7b88e2, + 0x19c17f37c25cb5cd, + 0xbd4e315e365e39ac, + 0x3a92f5b1fa177b15, + 0x85486a67941cd67e, + 0x55c8147ec0a38d, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^10) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0xaa3baf925a7b868e, + 0x3e0d38ef753d5865, + 0x4191258bc861923, + 0x1e8a71ae63e00a87, + 0xeffc4d11826f20dc, + 0x4663a2a83dd119, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^11) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x5ba1262ad3735380, + 0xbdef8bf12b1eb012, + 0x14db82e63230f6cf, + 0xcda1e0bcc1b54fd3, + 0x2790ee45b226806c, + 0x1306f19ff2877fd, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + ]; +} diff --git a/algebra/src/fields/bls12_377/fq2.rs b/algebra/src/fields/bls12_377/fq2.rs new file mode 100644 index 000000000..9700a0572 --- /dev/null +++ b/algebra/src/fields/bls12_377/fq2.rs @@ -0,0 +1,69 @@ +use crate::{ + biginteger::BigInteger384 as BigInteger, + fields::{ + bls12_377::fq::Fq, + fp2::{Fp2, Fp2Parameters}, + Field, + }, +}; + +pub type Fq2 = Fp2; + +pub struct Fq2Parameters; + +impl Fp2Parameters for Fq2Parameters { + type Fp = Fq; + + /// NONRESIDUE = -5 + const NONRESIDUE: Fq = Fq::new(BigInteger([ + 0xfc0b8000000002fa, + 0x97d39cf6e000018b, + 0x2072420fbfa05044, + 0xcbbcbd50d97c3802, + 0xbaf1ec35813f9eb, + 0x9974a2c0945ad2, + ])); + + /// QUADRATIC_NONRESIDUE = U + const QUADRATIC_NONRESIDUE: (Fq, Fq) = ( + Fq::new(BigInteger([0, 0, 0, 0, 0, 0])), + Fq::new(BigInteger([ + 202099033278250856u64, + 5854854902718660529u64, + 11492539364873682930u64, + 8885205928937022213u64, + 5545221690922665192u64, + 39800542322357402u64, + ])), + ); + + /// Coefficients for the Frobenius automorphism. + const FROBENIUS_COEFF_FP2_C1: [Fq; 2] = [ + // NONRESIDUE**(((q^0) - 1) / 2) + Fq::new(BigInteger([ + 0x2cdffffffffff68, + 0x51409f837fffffb1, + 0x9f7db3a98a7d3ff2, + 0x7b4e97b76e7c6305, + 0x4cf495bf803c84e8, + 0x8d6661e2fdf49a, + ])), + // NONRESIDUE**(((q^1) - 1) / 2) + Fq::new(BigInteger([ + 0x823ac00000000099, + 0xc5cabdc0b000004f, + 0x7f75ae862f8c080d, + 0x9ed4423b9278b089, + 0x79467000ec64c452, + 0x120d3e434c71c50, + ])), + ]; + + #[inline(always)] + fn mul_fp_by_nonresidue(fe: &Self::Fp) -> Self::Fp { + let original = fe; + let mut fe = -fe.double(); + fe.double_in_place(); + fe - original + } +} diff --git a/algebra/src/fields/bls12_377/fq6.rs b/algebra/src/fields/bls12_377/fq6.rs new file mode 100644 index 000000000..d0e616beb --- /dev/null +++ b/algebra/src/fields/bls12_377/fq6.rs @@ -0,0 +1,214 @@ +use crate::biginteger::BigInteger384; + +use crate::fields::{ + fp2::Fp2Parameters, + fp6_3over2::{Fp6, Fp6Parameters}, +}; + +use crate::fields::bls12_377::{ + fq::Fq, + fq2::{Fq2, Fq2Parameters}, +}; + +pub type Fq6 = Fp6; + +#[derive(Clone, Copy)] +pub struct Fq6Parameters; + +impl Fp6Parameters for Fq6Parameters { + type Fp2Params = Fq2Parameters; + + /// NONRESIDUE = U + const NONRESIDUE: Fq2 = Fq2::new( + Fq::new(BigInteger384([0, 0, 0, 0, 0, 0])), + Fq::new(BigInteger384([ + 202099033278250856u64, + 5854854902718660529u64, + 11492539364873682930u64, + 8885205928937022213u64, + 5545221690922665192u64, + 39800542322357402u64, + ])), + ); + + const FROBENIUS_COEFF_FP6_C1: [Fq2; 6] = [ + // Fp2::NONRESIDUE^(((q^0) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x2cdffffffffff68, + 0x51409f837fffffb1, + 0x9f7db3a98a7d3ff2, + 0x7b4e97b76e7c6305, + 0x4cf495bf803c84e8, + 0x8d6661e2fdf49a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^1) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x5892506da58478da, + 0x133366940ac2a74b, + 0x9b64a150cdf726cf, + 0x5cc426090a9c587e, + 0x5cf848adfdcd640c, + 0x4702bf3ac02380, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^2) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xdacd106da5847973, + 0xd8fe2454bac2a79a, + 0x1ada4fd6fd832edc, + 0xfb9868449d150908, + 0xd63eb8aeea32285e, + 0x167d6a36f873fd0, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^3) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x823ac00000000099, + 0xc5cabdc0b000004f, + 0x7f75ae862f8c080d, + 0x9ed4423b9278b089, + 0x79467000ec64c452, + 0x120d3e434c71c50, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^4) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x2c766f925a7b8727, + 0x3d7f6b0253d58b5, + 0x838ec0deec122131, + 0xbd5eb3e9f658bb10, + 0x6942bd126ed3e52e, + 0x1673786dd04ed6a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^(((q^5) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xaa3baf925a7b868e, + 0x3e0d38ef753d5865, + 0x4191258bc861923, + 0x1e8a71ae63e00a87, + 0xeffc4d11826f20dc, + 0x4663a2a83dd119, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + ]; + const FROBENIUS_COEFF_FP6_C2: [Fq2; 6] = [ + // Fp2::NONRESIDUE^((2*(q^0) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x2cdffffffffff68, + 0x51409f837fffffb1, + 0x9f7db3a98a7d3ff2, + 0x7b4e97b76e7c6305, + 0x4cf495bf803c84e8, + 0x8d6661e2fdf49a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^((2*(q^1) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xdacd106da5847973, + 0xd8fe2454bac2a79a, + 0x1ada4fd6fd832edc, + 0xfb9868449d150908, + 0xd63eb8aeea32285e, + 0x167d6a36f873fd0, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^((2*(q^2) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x2c766f925a7b8727, + 0x3d7f6b0253d58b5, + 0x838ec0deec122131, + 0xbd5eb3e9f658bb10, + 0x6942bd126ed3e52e, + 0x1673786dd04ed6a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^((2*(q^3) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x2cdffffffffff68, + 0x51409f837fffffb1, + 0x9f7db3a98a7d3ff2, + 0x7b4e97b76e7c6305, + 0x4cf495bf803c84e8, + 0x8d6661e2fdf49a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^((2*(q^4) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xdacd106da5847973, + 0xd8fe2454bac2a79a, + 0x1ada4fd6fd832edc, + 0xfb9868449d150908, + 0xd63eb8aeea32285e, + 0x167d6a36f873fd0, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fp2::NONRESIDUE^((2*(q^5) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x2c766f925a7b8727, + 0x3d7f6b0253d58b5, + 0x838ec0deec122131, + 0xbd5eb3e9f658bb10, + 0x6942bd126ed3e52e, + 0x1673786dd04ed6a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + ]; + + #[inline(always)] + fn mul_fp2_by_nonresidue(fe: &Fq2) -> Fq2 { + // Karatsuba multiplication with constant other = u. + let c0 = Fq2Parameters::mul_fp_by_nonresidue(&fe.c1); + let c1 = fe.c0; + Fq2::new(c0, c1) + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::fields::Field; + use rand::{Rand, SeedableRng, XorShiftRng}; + + #[test] + fn test_fq2_mul_nonresidue() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let nqr = Fq2::new(Fq::zero(), Fq::one()); + println!("One: {:?}", Fq::one()); + + for _ in 0..1000 { + let mut a = Fq2::rand(&mut rng); + let mut b = a; + a = a * &Fq6Parameters::NONRESIDUE; + b *= &nqr; + + assert_eq!(a, b); + } + } +} diff --git a/algebra/src/fields/bls12_377/fr.rs b/algebra/src/fields/bls12_377/fr.rs new file mode 100644 index 000000000..36f9325ad --- /dev/null +++ b/algebra/src/fields/bls12_377/fr.rs @@ -0,0 +1,90 @@ +use crate::{ + biginteger::BigInteger256 as BigInteger, + fields::{Fp256, Fp256Parameters, FpParameters}, +}; + +pub type Fr = Fp256; + +pub struct FrParameters; + +impl Fp256Parameters for FrParameters {} + +impl FpParameters for FrParameters { + type BigInt = BigInteger; + + // MODULUS = 8444461749428370424248824938781546531375899335154063827935233455917409239041 + const MODULUS: BigInteger = BigInteger([ + 725501752471715841u64, + 6461107452199829505u64, + 6968279316240510977u64, + 1345280370688173398u64, + ]); + + const MODULUS_BITS: u32 = 253; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 3; + + const R: BigInteger = BigInteger([ + 9015221291577245683u64, + 8239323489949974514u64, + 1646089257421115374u64, + 958099254763297437u64, + ]); + + const R2: BigInteger = BigInteger([ + 2726216793283724667u64, + 14712177743343147295u64, + 12091039717619697043u64, + 81024008013859129u64, + ]); + + const INV: u64 = 725501752471715839u64; + + // GENERATOR = 11 + const GENERATOR: BigInteger = BigInteger([ + 1855201571499933546u64, + 8511318076631809892u64, + 6222514765367795509u64, + 1122129207579058019u64, + ]); + + const TWO_ADICITY: u32 = 47; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0x3c3d3ca739381fb2, + 0x9a14cda3ec99772b, + 0xd7aacc7c59724826, + 0xd1ba211c5cc349c, + ]); + + /// (r - 1)/2 = + /// 4222230874714185212124412469390773265687949667577031913967616727958704619520 + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x8508c00000000000, + 0xacd53b7f68000000, + 0x305a268f2e1bd800, + 0x955b2af4d1652ab, + ]); + + // T and T_MINUS_ONE_DIV_TWO, where r - 1 = 2^s * t + + /// t = (r - 1) / 2^s = + /// 60001509534603559531609739528203892656505753216962260608619555 + const T: BigInteger = BigInteger([ + 0xedfda00000021423, + 0x9a3cb86f6002b354, + 0xcabd34594aacc168, + 0x2556, + ]); + + /// (t - 1) / 2 = + /// 30000754767301779765804869764101946328252876608481130304309777 + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x76fed00000010a11, + 0x4d1e5c37b00159aa, + 0x655e9a2ca55660b4, + 0x12ab, + ]); +} diff --git a/algebra/src/fields/bls12_377/mod.rs b/algebra/src/fields/bls12_377/mod.rs new file mode 100644 index 000000000..8e271b8fc --- /dev/null +++ b/algebra/src/fields/bls12_377/mod.rs @@ -0,0 +1,17 @@ +pub mod fr; +pub use self::fr::*; + +pub mod fq; +pub use self::fq::*; + +pub mod fq2; +pub use self::fq2::*; + +pub mod fq6; +pub use self::fq6::*; + +pub mod fq12; +pub use self::fq12::*; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/bls12_377/tests.rs b/algebra/src/fields/bls12_377/tests.rs new file mode 100644 index 000000000..ac6bd7e26 --- /dev/null +++ b/algebra/src/fields/bls12_377/tests.rs @@ -0,0 +1,529 @@ +use crate::{ + biginteger::{BigInteger, BigInteger384}, + fields::{ + bls12_377::{Fq, Fq12, Fq2, Fq2Parameters, Fq6, Fq6Parameters, FqParameters}, + fp6_3over2::Fp6Parameters, + tests::{field_test, frobenius_test, primefield_test, sqrt_field_test}, + Field, Fp2Parameters, FpParameters, PrimeField, SquareRootField, + }, +}; +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::{ + cmp::Ordering, + ops::{AddAssign, MulAssign, SubAssign}, +}; + +pub(crate) const ITERATIONS: usize = 5; + +#[test] +fn test_bls12_377_fr() { + use crate::fields::bls12_377::Fr; + + for _ in 0..ITERATIONS { + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + primefield_test::(); + sqrt_field_test(b); + } +} + +#[test] +fn test_bls12_377_fq() { + use crate::fields::bls12_377::Fq; + + for _ in 0..ITERATIONS { + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + primefield_test::(); + sqrt_field_test(a); + } +} + +#[test] +fn test_bls12_377_fq2() { + use crate::fields::{ + bls12_377::{Fq, Fq2}, + PrimeField, + }; + + for _ in 0..ITERATIONS { + let a: Fq2 = rand::random(); + let b: Fq2 = rand::random(); + field_test(a, b); + sqrt_field_test(a); + } + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_bls12_377_fq6() { + use crate::fields::{ + bls12_377::{Fq, Fq6}, + PrimeField, + }; + + for _ in 0..ITERATIONS { + let g: Fq6 = rand::random(); + let h: Fq6 = rand::random(); + field_test(g, h); + } + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_bls12_377_fq12() { + use crate::fields::{ + bls12_377::{Fq, Fq12}, + PrimeField, + }; + + for _ in 0..ITERATIONS { + let g: Fq12 = rand::random(); + let h: Fq12 = rand::random(); + field_test(g, h); + } + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_fq_repr_from() { + assert_eq!( + BigInteger384::from(100), + BigInteger384([100, 0, 0, 0, 0, 0]) + ); +} + +#[test] +fn test_fq_repr_is_odd() { + assert!(!BigInteger384::from(0).is_odd()); + assert!(BigInteger384::from(0).is_even()); + assert!(BigInteger384::from(1).is_odd()); + assert!(!BigInteger384::from(1).is_even()); + assert!(!BigInteger384::from(324834872).is_odd()); + assert!(BigInteger384::from(324834872).is_even()); + assert!(BigInteger384::from(324834873).is_odd()); + assert!(!BigInteger384::from(324834873).is_even()); +} + +#[test] +fn test_fq_repr_is_zero() { + assert!(BigInteger384::from(0).is_zero()); + assert!(!BigInteger384::from(1).is_zero()); + assert!(!BigInteger384([0, 0, 0, 0, 1, 0]).is_zero()); +} + +#[test] +fn test_fq_repr_num_bits() { + let mut a = BigInteger384::from(0); + assert_eq!(0, a.num_bits()); + a = BigInteger384::from(1); + for i in 1..385 { + assert_eq!(i, a.num_bits()); + a.mul2(); + } + assert_eq!(0, a.num_bits()); +} + +#[test] +fn test_fq_add_assign() { + // Test associativity + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Generate a, b, c and ensure (a + b) + c == a + (b + c). + let a = Fq::rand(&mut rng); + let b = Fq::rand(&mut rng); + let c = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.add_assign(&b); + tmp1.add_assign(&c); + + let mut tmp2 = b; + tmp2.add_assign(&c); + tmp2.add_assign(&a); + + assert!(tmp1.is_valid()); + assert!(tmp2.is_valid()); + assert_eq!(tmp1, tmp2); + } +} + +#[test] +fn test_fq_sub_assign() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Ensure that (a - b) + (b - a) = 0. + let a = Fq::rand(&mut rng); + let b = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.sub_assign(&b); + + let mut tmp2 = b; + tmp2.sub_assign(&a); + + tmp1.add_assign(&tmp2); + assert!(tmp1.is_zero()); + } +} + +#[test] +fn test_fq_mul_assign() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000000 { + // Ensure that (a * b) * c = a * (b * c) + let a = Fq::rand(&mut rng); + let b = Fq::rand(&mut rng); + let c = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.mul_assign(&b); + tmp1.mul_assign(&c); + + let mut tmp2 = b; + tmp2.mul_assign(&c); + tmp2.mul_assign(&a); + + assert_eq!(tmp1, tmp2); + } + + for _ in 0..1000000 { + // Ensure that r * (a + b + c) = r*a + r*b + r*c + + let r = Fq::rand(&mut rng); + let mut a = Fq::rand(&mut rng); + let mut b = Fq::rand(&mut rng); + let mut c = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.add_assign(&b); + tmp1.add_assign(&c); + tmp1.mul_assign(&r); + + a.mul_assign(&r); + b.mul_assign(&r); + c.mul_assign(&r); + + a.add_assign(&b); + a.add_assign(&c); + + assert_eq!(tmp1, a); + } +} + +#[test] +fn test_fq_squaring() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000000 { + // Ensure that (a * a) = a^2 + let a = Fq::rand(&mut rng); + + let mut tmp = a; + tmp.square_in_place(); + + let mut tmp2 = a; + tmp2.mul_assign(&a); + + assert_eq!(tmp, tmp2); + } +} + +#[test] +fn test_fq_inverse() { + assert!(Fq::zero().inverse().is_none()); + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let one = Fq::one(); + + for _ in 0..1000 { + // Ensure that a * a^-1 = 1 + let mut a = Fq::rand(&mut rng); + let ainv = a.inverse().unwrap(); + a.mul_assign(&ainv); + assert_eq!(a, one); + } +} + +#[test] +fn test_fq_double_in_place() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Ensure doubling a is equivalent to adding a to itself. + let mut a = Fq::rand(&mut rng); + let mut b = a; + b.add_assign(&a); + a.double_in_place(); + assert_eq!(a, b); + } +} + +#[test] +fn test_fq_negate() { + { + let a = -Fq::zero(); + + assert!(a.is_zero()); + } + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Ensure (a - (-a)) = 0. + let mut a = Fq::rand(&mut rng); + let b = -a; + a.add_assign(&b); + + assert!(a.is_zero()); + } +} + +#[test] +fn test_fq_pow() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for i in 0..1000 { + // Exponentiate by various small numbers and ensure it consists with repeated + // multiplication. + let a = Fq::rand(&mut rng); + let target = a.pow(&[i]); + let mut c = Fq::one(); + for _ in 0..i { + c.mul_assign(&a); + } + assert_eq!(c, target); + } + + for _ in 0..1000 { + // Exponentiating by the modulus should have no effect in a prime field. + let a = Fq::rand(&mut rng); + + assert_eq!(a, a.pow(Fq::characteristic().0)); + } +} + +#[test] +fn test_fq_sqrt() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + assert_eq!(Fq::zero().sqrt().unwrap(), Fq::zero()); + + for _ in 0..1000 { + // Ensure sqrt(a^2) = a or -a + let a = Fq::rand(&mut rng); + let nega = -a; + let mut b = a; + b.square_in_place(); + + let b = b.sqrt().unwrap(); + + assert!(a == b || nega == b); + } + + for _ in 0..1000 { + // Ensure sqrt(a)^2 = a for random a + let a = Fq::rand(&mut rng); + + if let Some(mut tmp) = a.sqrt() { + tmp.square_in_place(); + + assert_eq!(a, tmp); + } + } +} + +#[test] +fn test_fq_num_bits() { + assert_eq!(FqParameters::MODULUS_BITS, 377); + assert_eq!(FqParameters::CAPACITY, 376); +} + +#[test] +fn test_fq_root_of_unity() { + assert_eq!(FqParameters::TWO_ADICITY, 46); + assert_eq!( + Fq::multiplicative_generator().pow([ + 0x7510c00000021423, + 0x88bee82520005c2d, + 0x67cc03d44e3c7bcd, + 0x1701b28524ec688b, + 0xe9185f1443ab18ec, + 0x6b8 + ]), + Fq::root_of_unity() + ); + assert_eq!( + Fq::root_of_unity().pow([1 << FqParameters::TWO_ADICITY]), + Fq::one() + ); + assert!(Fq::multiplicative_generator().sqrt().is_none()); +} + +#[test] +fn test_fq_ordering() { + // BigInteger384's ordering is well-tested, but we still need to make sure the + // Fq elements aren't being compared in Montgomery form. + for i in 0..100 { + assert!(Fq::from_repr(BigInteger384::from(i + 1)) > Fq::from_repr(BigInteger384::from(i))); + } +} + +#[test] +fn test_fq_legendre() { + use crate::fields::LegendreSymbol::*; + + assert_eq!(QuadraticResidue, Fq::one().legendre()); + assert_eq!(Zero, Fq::zero().legendre()); + assert_eq!( + QuadraticResidue, + Fq::from_repr(BigInteger384::from(4)).legendre() + ); + assert_eq!( + QuadraticNonResidue, + Fq::from_repr(BigInteger384::from(5)).legendre() + ); +} + +#[test] +fn test_fq2_ordering() { + let mut a = Fq2::new(Fq::zero(), Fq::zero()); + let mut b = a.clone(); + + assert!(a.cmp(&b) == Ordering::Equal); + b.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Less); + a.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Equal); + b.c1.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Less); + a.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Less); + a.c1.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Greater); + b.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Equal); +} + +#[test] +fn test_fq2_basics() { + assert_eq!(Fq2::new(Fq::zero(), Fq::zero(),), Fq2::zero()); + assert_eq!(Fq2::new(Fq::one(), Fq::zero(),), Fq2::one()); + assert!(Fq2::zero().is_zero()); + assert!(!Fq2::one().is_zero()); + assert!(!Fq2::new(Fq::zero(), Fq::one(),).is_zero()); +} + +#[test] +fn test_fq2_legendre() { + use crate::fields::LegendreSymbol::*; + + assert_eq!(Zero, Fq2::zero().legendre()); + // i^2 = -1 + let mut m1 = -Fq2::one(); + assert_eq!(QuadraticResidue, m1.legendre()); + m1 = Fq6Parameters::mul_fp2_by_nonresidue(&m1); + assert_eq!(QuadraticNonResidue, m1.legendre()); +} + +#[test] +fn test_fq2_mul_nonresidue() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let nqr = Fq2::new(Fq::zero(), Fq::one()); + + let quadratic_non_residue = Fq2::new( + Fq2Parameters::QUADRATIC_NONRESIDUE.0, + Fq2Parameters::QUADRATIC_NONRESIDUE.1, + ); + for _ in 0..1000 { + let mut a = Fq2::rand(&mut rng); + let mut b = a; + a = quadratic_non_residue * &a; + b.mul_assign(&nqr); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq6_mul_by_1() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c1 = Fq2::rand(&mut rng); + let mut a = Fq6::rand(&mut rng); + let mut b = a; + + a.mul_by_1(&c1); + b.mul_assign(&Fq6::new(Fq2::zero(), c1, Fq2::zero())); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq6_mul_by_01() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c0 = Fq2::rand(&mut rng); + let c1 = Fq2::rand(&mut rng); + let mut a = Fq6::rand(&mut rng); + let mut b = a; + + a.mul_by_01(&c0, &c1); + b.mul_assign(&Fq6::new(c0, c1, Fq2::zero())); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq12_mul_by_014() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c0 = Fq2::rand(&mut rng); + let c1 = Fq2::rand(&mut rng); + let c5 = Fq2::rand(&mut rng); + let mut a = Fq12::rand(&mut rng); + let mut b = a; + + a.mul_by_014(&c0, &c1, &c5); + b.mul_assign(&Fq12::new( + Fq6::new(c0, c1, Fq2::zero()), + Fq6::new(Fq2::zero(), c5, Fq2::zero()), + )); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq12_mul_by_034() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c0 = Fq2::rand(&mut rng); + let c3 = Fq2::rand(&mut rng); + let c4 = Fq2::rand(&mut rng); + let mut a = Fq12::rand(&mut rng); + let mut b = a; + + a.mul_by_034(&c0, &c3, &c4); + b.mul_assign(&Fq12::new( + Fq6::new(c0, Fq2::zero(), Fq2::zero()), + Fq6::new(c3, c4, Fq2::zero()), + )); + + assert_eq!(a, b); + } +} diff --git a/algebra/src/fields/bls12_381/fq.rs b/algebra/src/fields/bls12_381/fq.rs new file mode 100644 index 000000000..be9685248 --- /dev/null +++ b/algebra/src/fields/bls12_381/fq.rs @@ -0,0 +1,99 @@ +use crate::{ + biginteger::BigInteger384 as BigInteger, + fields::{Fp384, Fp384Parameters, FpParameters}, +}; + +pub type Fq = Fp384; + +pub struct FqParameters; + +impl Fp384Parameters for FqParameters {} +impl FpParameters for FqParameters { + type BigInt = BigInteger; + + // MODULUS = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787 + const MODULUS: BigInteger = BigInteger([ + 0xb9feffffffffaaab, + 0x1eabfffeb153ffff, + 0x6730d2a0f6b0f624, + 0x64774b84f38512bf, + 0x4b1ba7b6434bacd7, + 0x1a0111ea397fe69a, + ]); + + const MODULUS_BITS: u32 = 381; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 3; + + const R: BigInteger = BigInteger([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ]); + + const R2: BigInteger = BigInteger([ + 0xf4df1f341c341746, + 0xa76e6a609d104f1, + 0x8de5476c4c95b6d5, + 0x67eb88a9939d83c0, + 0x9a793e85b519952d, + 0x11988fe592cae3aa, + ]); + + const INV: u64 = 0x89f3fffcfffcfffd; + + // GENERATOR = 2 + const GENERATOR: BigInteger = BigInteger([ + 0x321300000006554f, + 0xb93c0018d6c40005, + 0x57605e0db0ddbb51, + 0x8b256521ed1f9bcb, + 0x6cf28d7901622c03, + 0x11ebab9dbb81e28c, + ]); + + const TWO_ADICITY: u32 = 1; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0xdcff7fffffffd555, + 0xf55ffff58a9ffff, + 0xb39869507b587b12, + 0xb23ba5c279c2895f, + 0x258dd3db21a5d66b, + 0xd0088f51cbff34d, + ]); + + // T and T_MINUS_ONE_DIV_TWO, where MODULUS - 1 = 2^S * T + + const T: BigInteger = BigInteger([ + 0xdcff7fffffffd555, + 0xf55ffff58a9ffff, + 0xb39869507b587b12, + 0xb23ba5c279c2895f, + 0x258dd3db21a5d66b, + 0xd0088f51cbff34d, + ]); + + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0xee7fbfffffffeaaa, + 0x7aaffffac54ffff, + 0xd9cc34a83dac3d89, + 0xd91dd2e13ce144af, + 0x92c6e9ed90d2eb35, + 0x680447a8e5ff9a6, + ]); +} diff --git a/algebra/src/fields/bls12_381/fq12.rs b/algebra/src/fields/bls12_381/fq12.rs new file mode 100644 index 000000000..0b9bb3aa4 --- /dev/null +++ b/algebra/src/fields/bls12_381/fq12.rs @@ -0,0 +1,231 @@ +use crate::{ + biginteger::BigInteger384, + fields::{ + bls12_381::{fq::Fq, fq2::Fq2, fq6::Fq6Parameters}, + fp12_2over3over2::{Fp12, Fp12Parameters}, + }, +}; + +pub type Fq12 = Fp12; + +#[derive(Clone, Copy)] +pub struct Fq12Parameters; + +impl Fp12Parameters for Fq12Parameters { + type Fp6Params = Fq6Parameters; + + const FROBENIUS_COEFF_FP12_C1: [Fq2; 12] = [ + // Fq2(u + 1)**(((q^0) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^1) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x7089552b319d465, + 0xc6695f92b50a8313, + 0x97e83cccd117228f, + 0xa35baecab2dc29ee, + 0x1ce393ea5daace4d, + 0x8f2220fb0fb66eb, + ])), + Fq::new(BigInteger384([ + 0xb2f66aad4ce5d646, + 0x5842a06bfc497cec, + 0xcf4895d42599d394, + 0xc11b9cba40a8e8d0, + 0x2e3813cbe5a0de89, + 0x110eefda88847faf, + ])), + ), + // Fq2(u + 1)**(((q^2) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0xecfb361b798dba3a, + 0xc100ddb891865a2c, + 0xec08ff1232bda8e, + 0xd5c13cc6f1ca4721, + 0x47222a47bf7b5c04, + 0x110f184e51c5f59, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^3) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x3e2f585da55c9ad1, + 0x4294213d86c18183, + 0x382844c88b623732, + 0x92ad2afd19103e18, + 0x1d794e4fac7cf0b9, + 0xbd592fc7d825ec8, + ])), + Fq::new(BigInteger384([ + 0x7bcfa7a25aa30fda, + 0xdc17dec12a927e7c, + 0x2f088dd86b4ebef1, + 0xd1ca2087da74d4a7, + 0x2da2596696cebc1d, + 0xe2b7eedbbfd87d2, + ])), + ), + // Fq2(u + 1)**(((q^4) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x30f1361b798a64e8, + 0xf3b8ddab7ece5a2a, + 0x16a8ca3ac61577f7, + 0xc26a2ff874fd029b, + 0x3636b76660701c6e, + 0x51ba4ab241b6160, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^5) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x3726c30af242c66c, + 0x7c2ac1aad1b6fe70, + 0xa04007fbba4b14a2, + 0xef517c3266341429, + 0x95ba654ed2226b, + 0x2e370eccc86f7dd, + ])), + Fq::new(BigInteger384([ + 0x82d83cf50dbce43f, + 0xa2813e53df9d018f, + 0xc6f0caa53c65e181, + 0x7525cf528d50fe95, + 0x4a85ed50f4798a6b, + 0x171da0fd6cf8eebd, + ])), + ), + // Fq2(u + 1)**(((q^6) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^7) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0xb2f66aad4ce5d646, + 0x5842a06bfc497cec, + 0xcf4895d42599d394, + 0xc11b9cba40a8e8d0, + 0x2e3813cbe5a0de89, + 0x110eefda88847faf, + ])), + Fq::new(BigInteger384([ + 0x7089552b319d465, + 0xc6695f92b50a8313, + 0x97e83cccd117228f, + 0xa35baecab2dc29ee, + 0x1ce393ea5daace4d, + 0x8f2220fb0fb66eb, + ])), + ), + // Fq2(u + 1)**(((q^8) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0xcd03c9e48671f071, + 0x5dab22461fcda5d2, + 0x587042afd3851b95, + 0x8eb60ebe01bacb9e, + 0x3f97d6e83d050d2, + 0x18f0206554638741, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^9) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x7bcfa7a25aa30fda, + 0xdc17dec12a927e7c, + 0x2f088dd86b4ebef1, + 0xd1ca2087da74d4a7, + 0x2da2596696cebc1d, + 0xe2b7eedbbfd87d2, + ])), + Fq::new(BigInteger384([ + 0x3e2f585da55c9ad1, + 0x4294213d86c18183, + 0x382844c88b623732, + 0x92ad2afd19103e18, + 0x1d794e4fac7cf0b9, + 0xbd592fc7d825ec8, + ])), + ), + // Fq2(u + 1)**(((q^10) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x890dc9e4867545c3, + 0x2af322533285a5d5, + 0x50880866309b7e2c, + 0xa20d1b8c7e881024, + 0x14e4f04fe2db9068, + 0x14e56d3f1564853a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^11) - 1) / 6) + Fq2::new( + Fq::new(BigInteger384([ + 0x82d83cf50dbce43f, + 0xa2813e53df9d018f, + 0xc6f0caa53c65e181, + 0x7525cf528d50fe95, + 0x4a85ed50f4798a6b, + 0x171da0fd6cf8eebd, + ])), + Fq::new(BigInteger384([ + 0x3726c30af242c66c, + 0x7c2ac1aad1b6fe70, + 0xa04007fbba4b14a2, + 0xef517c3266341429, + 0x95ba654ed2226b, + 0x2e370eccc86f7dd, + ])), + ), + ]; +} + +#[cfg(test)] +mod test { + use super::*; + use crate::fields::{ + bls12_381::{fq2::Fq2, fq6::Fq6}, + Field, + }; + use rand::{Rand, SeedableRng, XorShiftRng}; + + #[test] + fn test_fq6_mul_nonresidue() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let nqr = Fq6::new(Fq2::zero(), Fq2::one(), Fq2::zero()); + + for _ in 0..1000 { + let mut a = Fq6::rand(&mut rng); + let mut b = a; + a = Fq12::mul_fp6_by_nonresidue(&a); + b *= &nqr; + + assert_eq!(a, b); + } + } +} diff --git a/algebra/src/fields/bls12_381/fq2.rs b/algebra/src/fields/bls12_381/fq2.rs new file mode 100644 index 000000000..3fa4173cf --- /dev/null +++ b/algebra/src/fields/bls12_381/fq2.rs @@ -0,0 +1,72 @@ +use crate::{ + biginteger::BigInteger384 as BigInteger, + fields::{ + bls12_381::fq::Fq, + fp2::{Fp2, Fp2Parameters}, + }, +}; + +pub type Fq2 = Fp2; + +pub struct Fq2Parameters; + +impl Fp2Parameters for Fq2Parameters { + type Fp = Fq; + + /// NONRESIDUE = -1 + const NONRESIDUE: Fq = Fq::new(BigInteger([ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ])); + + /// QUADRATIC_NONRESIDUE = (U + 1) + const QUADRATIC_NONRESIDUE: (Fq, Fq) = ( + Fq::new(BigInteger([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + Fq::new(BigInteger([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + ); + + /// Coefficients for the Frobenius automorphism. + const FROBENIUS_COEFF_FP2_C1: [Fq; 2] = [ + // Fq(-1)**(((q^0) - 1) / 2) + Fq::new(BigInteger([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + // Fq(-1)**(((q^1) - 1) / 2) + Fq::new(BigInteger([ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ])), + ]; + + #[inline(always)] + fn mul_fp_by_nonresidue(fp: &Self::Fp) -> Self::Fp { + -(*fp) + } +} diff --git a/algebra/src/fields/bls12_381/fq6.rs b/algebra/src/fields/bls12_381/fq6.rs new file mode 100644 index 000000000..3dba375cd --- /dev/null +++ b/algebra/src/fields/bls12_381/fq6.rs @@ -0,0 +1,199 @@ +use crate::{ + biginteger::BigInteger384, + fields::{ + bls12_381::{ + fq::Fq, + fq2::{Fq2, Fq2Parameters}, + }, + fp6_3over2::{Fp6, Fp6Parameters}, + }, +}; + +pub type Fq6 = Fp6; + +#[derive(Clone, Copy)] +pub struct Fq6Parameters; + +impl Fp6Parameters for Fq6Parameters { + type Fp2Params = Fq2Parameters; + + /// NONRESIDUE = (U + 1) + const NONRESIDUE: Fq2 = Fq2::new( + Fq::new(BigInteger384([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + Fq::new(BigInteger384([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + ); + + const FROBENIUS_COEFF_FP6_C1: [Fq2; 6] = [ + // Fq2(u + 1)**(((q^0) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^1) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + Fq::new(BigInteger384([ + 0xcd03c9e48671f071, + 0x5dab22461fcda5d2, + 0x587042afd3851b95, + 0x8eb60ebe01bacb9e, + 0x3f97d6e83d050d2, + 0x18f0206554638741, + ])), + ), + // Fq2(u + 1)**(((q^2) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x30f1361b798a64e8, + 0xf3b8ddab7ece5a2a, + 0x16a8ca3ac61577f7, + 0xc26a2ff874fd029b, + 0x3636b76660701c6e, + 0x51ba4ab241b6160, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^3) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + Fq::new(BigInteger384([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + ), + // Fq2(u + 1)**(((q^4) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xcd03c9e48671f071, + 0x5dab22461fcda5d2, + 0x587042afd3851b95, + 0x8eb60ebe01bacb9e, + 0x3f97d6e83d050d2, + 0x18f0206554638741, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((q^5) - 1) / 3) + Fq2::new( + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + Fq::new(BigInteger384([ + 0x30f1361b798a64e8, + 0xf3b8ddab7ece5a2a, + 0x16a8ca3ac61577f7, + 0xc26a2ff874fd029b, + 0x3636b76660701c6e, + 0x51ba4ab241b6160, + ])), + ), + ]; + + const FROBENIUS_COEFF_FP6_C2: [Fq2; 6] = [ + // Fq2(u + 1)**(((2q^0) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x760900000002fffd, + 0xebf4000bc40c0002, + 0x5f48985753c758ba, + 0x77ce585370525745, + 0x5c071a97a256ec6d, + 0x15f65ec3fa80e493, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((2q^1) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x890dc9e4867545c3, + 0x2af322533285a5d5, + 0x50880866309b7e2c, + 0xa20d1b8c7e881024, + 0x14e4f04fe2db9068, + 0x14e56d3f1564853a, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((2q^2) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xcd03c9e48671f071, + 0x5dab22461fcda5d2, + 0x587042afd3851b95, + 0x8eb60ebe01bacb9e, + 0x3f97d6e83d050d2, + 0x18f0206554638741, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((2q^3) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((2q^4) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0x30f1361b798a64e8, + 0xf3b8ddab7ece5a2a, + 0x16a8ca3ac61577f7, + 0xc26a2ff874fd029b, + 0x3636b76660701c6e, + 0x51ba4ab241b6160, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + // Fq2(u + 1)**(((2q^5) - 2) / 3) + Fq2::new( + Fq::new(BigInteger384([ + 0xecfb361b798dba3a, + 0xc100ddb891865a2c, + 0xec08ff1232bda8e, + 0xd5c13cc6f1ca4721, + 0x47222a47bf7b5c04, + 0x110f184e51c5f59, + ])), + Fq::new(BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x0])), + ), + ]; + + /// Multiply this element by the quadratic nonresidue 1 + u. + /// Make this generic. + fn mul_fp2_by_nonresidue(fe: &Fq2) -> Fq2 { + let mut copy = *fe; + let t0 = copy.c0; + copy.c0 -= &fe.c1; + copy.c1 += &t0; + copy + } +} diff --git a/algebra/src/fields/bls12_381/fr.rs b/algebra/src/fields/bls12_381/fr.rs new file mode 100644 index 000000000..415df370a --- /dev/null +++ b/algebra/src/fields/bls12_381/fr.rs @@ -0,0 +1 @@ +pub use crate::fields::jubjub::fq::{Fq as Fr, FqParameters as FrParameters}; diff --git a/algebra/src/fields/bls12_381/mod.rs b/algebra/src/fields/bls12_381/mod.rs new file mode 100644 index 000000000..8e271b8fc --- /dev/null +++ b/algebra/src/fields/bls12_381/mod.rs @@ -0,0 +1,17 @@ +pub mod fr; +pub use self::fr::*; + +pub mod fq; +pub use self::fq::*; + +pub mod fq2; +pub use self::fq2::*; + +pub mod fq6; +pub use self::fq6::*; + +pub mod fq12; +pub use self::fq12::*; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/bls12_381/tests.rs b/algebra/src/fields/bls12_381/tests.rs new file mode 100644 index 000000000..64aa7cbf3 --- /dev/null +++ b/algebra/src/fields/bls12_381/tests.rs @@ -0,0 +1,2379 @@ +use crate::{ + biginteger::{BigInteger, BigInteger384}, + fields::{ + bls12_381::{ + Fq, Fq12, Fq12Parameters, Fq2, Fq2Parameters, Fq6, Fq6Parameters, FqParameters, + }, + fp12_2over3over2::Fp12Parameters, + fp6_3over2::Fp6Parameters, + tests::{field_test, frobenius_test, primefield_test, sqrt_field_test}, + Field, Fp2Parameters, FpParameters, PrimeField, SquareRootField, + }, +}; +use rand::{Rand, SeedableRng, XorShiftRng}; +use std::{ + cmp::Ordering, + ops::{AddAssign, MulAssign, SubAssign}, +}; + +pub(crate) const ITERATIONS: usize = 5; + +#[test] +fn test_bls12_381_fr() { + use crate::fields::bls12_381::Fr; + + for _ in 0..ITERATIONS { + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + primefield_test::(); + sqrt_field_test(b); + } +} + +#[test] +fn test_bls12_381_fq() { + use crate::fields::bls12_381::Fq; + + for _ in 0..ITERATIONS { + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + primefield_test::(); + sqrt_field_test(a); + } +} + +#[test] +fn test_bls12_381_fq2() { + use crate::fields::{ + bls12_381::{Fq, Fq2}, + PrimeField, + }; + + for _ in 0..ITERATIONS { + let a: Fq2 = rand::random(); + let b: Fq2 = rand::random(); + field_test(a, b); + sqrt_field_test(a); + } + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_bls12_381_fq6() { + use crate::fields::{ + bls12_381::{Fq, Fq6}, + PrimeField, + }; + + for _ in 0..ITERATIONS { + let g: Fq6 = rand::random(); + let h: Fq6 = rand::random(); + field_test(g, h); + } + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_bls12_381_fq12() { + use crate::fields::{ + bls12_381::{Fq, Fq12}, + PrimeField, + }; + + for _ in 0..ITERATIONS { + let g: Fq12 = rand::random(); + let h: Fq12 = rand::random(); + field_test(g, h); + } + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_bls12_381_negative_one() { + use crate::{biginteger::BigInteger384, fields::bls12_381::fq::Fq}; + + let neg_one = Fq::new(BigInteger384([ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ])); + assert_eq!(neg_one, -Fq::one()); +} + +#[test] +fn test_frob_coeffs() { + let nqr = -Fq::one(); + + assert_eq!(Fq2Parameters::FROBENIUS_COEFF_FP2_C1[0], Fq::one()); + assert_eq!( + Fq2Parameters::FROBENIUS_COEFF_FP2_C1[1], + nqr.pow([ + 0xdcff7fffffffd555, + 0xf55ffff58a9ffff, + 0xb39869507b587b12, + 0xb23ba5c279c2895f, + 0x258dd3db21a5d66b, + 0xd0088f51cbff34d, + ]) + ); + + let nqr = Fq2::new(Fq::one(), Fq::one()); + + assert_eq!(Fq6Parameters::FROBENIUS_COEFF_FP6_C1[0], Fq2::one()); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C1[1], + nqr.pow([ + 0x9354ffffffffe38e, + 0xa395554e5c6aaaa, + 0xcd104635a790520c, + 0xcc27c3d6fbd7063f, + 0x190937e76bc3e447, + 0x8ab05f8bdd54cde, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C1[2], + nqr.pow([ + 0xb78e0000097b2f68, + 0xd44f23b47cbd64e3, + 0x5cb9668120b069a9, + 0xccea85f9bf7b3d16, + 0xdba2c8d7adb356d, + 0x9cd75ded75d7429, + 0xfc65c31103284fab, + 0xc58cb9a9b249ee24, + 0xccf734c3118a2e9a, + 0xa0f4304c5a256ce6, + 0xc3f0d2f8e0ba61f8, + 0xe167e192ebca97, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C1[3], + nqr.pow([ + 0xdbc6fcd6f35b9e06, + 0x997dead10becd6aa, + 0x9dbbd24c17206460, + 0x72b97acc6057c45e, + 0xf8e9a230bf0c628e, + 0x647ccb1885c63a7, + 0xce80264fc55bf6ee, + 0x94d8d716c3939fc4, + 0xad78f0eb77ee6ee1, + 0xd6fe49bfe57dc5f9, + 0x2656d6c15c63647, + 0xdf6282f111fa903, + 0x1bdba63e0632b4bb, + 0x6883597bcaa505eb, + 0xa56d4ec90c34a982, + 0x7e4c42823bbe90b2, + 0xf64728aa6dcb0f20, + 0x16e57e16ef152f, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C1[4], + nqr.pow([ + 0x4649add3c71c6d90, + 0x43caa6528972a865, + 0xcda8445bbaaa0fbb, + 0xc93dea665662aa66, + 0x2863bc891834481d, + 0x51a0c3f5d4ccbed8, + 0x9210e660f90ccae9, + 0xe2bd6836c546d65e, + 0xf223abbaa7cf778b, + 0xd4f10b222cf11680, + 0xd540f5eff4a1962e, + 0xa123a1f140b56526, + 0x31ace500636a59f6, + 0x3a82bc8c8dfa57a9, + 0x648c511e217fc1f8, + 0x36c17ffd53a4558f, + 0x881bef5fd684eefd, + 0x5d648dbdc5dbb522, + 0x8fd07bf06e5e59b8, + 0x8ddec8a9acaa4b51, + 0x4cc1f8688e2def26, + 0xa74e63cb492c03de, + 0x57c968173d1349bb, + 0x253674e02a866, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C1[5], + nqr.pow([ + 0xf896f792732eb2be, + 0x49c86a6d1dc593a1, + 0xe5b31e94581f91c3, + 0xe3da5cc0a6b20d7f, + 0x822caef950e0bfed, + 0x317ed950b9ee67cd, + 0xffd664016ee3f6cd, + 0x77d991c88810b122, + 0x62e72e635e698264, + 0x905e1a1a2d22814a, + 0xf5b7ab3a3f33d981, + 0x175871b0bc0e25dd, + 0x1e2e9a63df5c3772, + 0xe888b1f7445b149d, + 0x9551c19e5e7e2c24, + 0xecf21939a3d2d6be, + 0xd830dbfdab72dbd4, + 0x7b34af8d622d40c0, + 0x3df6d20a45671242, + 0xaf86bee30e21d98, + 0x41064c1534e5df5d, + 0xf5f6cabd3164c609, + 0xa5d14bdf2b7ee65, + 0xa718c069defc9138, + 0xdb1447e770e3110e, + 0xc1b164a9e90af491, + 0x7180441f9d251602, + 0x1fd3a5e6a9a893e, + 0x1e17b779d54d5db, + 0x3c7afafe3174, + ]) + ); + + assert_eq!(Fq6Parameters::FROBENIUS_COEFF_FP6_C2[0], Fq2::one()); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C2[1], + nqr.pow([ + 0x26a9ffffffffc71c, + 0x1472aaa9cb8d5555, + 0x9a208c6b4f20a418, + 0x984f87adf7ae0c7f, + 0x32126fced787c88f, + 0x11560bf17baa99bc, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C2[2], + nqr.pow([ + 0x6f1c000012f65ed0, + 0xa89e4768f97ac9c7, + 0xb972cd024160d353, + 0x99d50bf37ef67a2c, + 0x1b74591af5b66adb, + 0x139aebbdaebae852, + 0xf8cb862206509f56, + 0x8b1973536493dc49, + 0x99ee698623145d35, + 0x41e86098b44ad9cd, + 0x87e1a5f1c174c3f1, + 0x1c2cfc325d7952f, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C2[3], + nqr.pow([ + 0xb78df9ade6b73c0c, + 0x32fbd5a217d9ad55, + 0x3b77a4982e40c8c1, + 0xe572f598c0af88bd, + 0xf1d344617e18c51c, + 0xc8f996310b8c74f, + 0x9d004c9f8ab7eddc, + 0x29b1ae2d87273f89, + 0x5af1e1d6efdcddc3, + 0xadfc937fcafb8bf3, + 0x4cadad82b8c6c8f, + 0x1bec505e223f5206, + 0x37b74c7c0c656976, + 0xd106b2f7954a0bd6, + 0x4ada9d9218695304, + 0xfc988504777d2165, + 0xec8e5154db961e40, + 0x2dcafc2dde2a5f, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C2[4], + nqr.pow([ + 0x8c935ba78e38db20, + 0x87954ca512e550ca, + 0x9b5088b775541f76, + 0x927bd4ccacc554cd, + 0x50c779123068903b, + 0xa34187eba9997db0, + 0x2421ccc1f21995d2, + 0xc57ad06d8a8dacbd, + 0xe44757754f9eef17, + 0xa9e2164459e22d01, + 0xaa81ebdfe9432c5d, + 0x424743e2816aca4d, + 0x6359ca00c6d4b3ed, + 0x750579191bf4af52, + 0xc918a23c42ff83f0, + 0x6d82fffaa748ab1e, + 0x1037debfad09ddfa, + 0xbac91b7b8bb76a45, + 0x1fa0f7e0dcbcb370, + 0x1bbd9153595496a3, + 0x9983f0d11c5bde4d, + 0x4e9cc796925807bc, + 0xaf92d02e7a269377, + 0x4a6ce9c0550cc, + ]) + ); + assert_eq!( + Fq6Parameters::FROBENIUS_COEFF_FP6_C2[5], + nqr.pow([ + 0xf12def24e65d657c, + 0x9390d4da3b8b2743, + 0xcb663d28b03f2386, + 0xc7b4b9814d641aff, + 0x4595df2a1c17fdb, + 0x62fdb2a173dccf9b, + 0xffacc802ddc7ed9a, + 0xefb3239110216245, + 0xc5ce5cc6bcd304c8, + 0x20bc34345a450294, + 0xeb6f56747e67b303, + 0x2eb0e361781c4bbb, + 0x3c5d34c7beb86ee4, + 0xd11163ee88b6293a, + 0x2aa3833cbcfc5849, + 0xd9e4327347a5ad7d, + 0xb061b7fb56e5b7a9, + 0xf6695f1ac45a8181, + 0x7beda4148ace2484, + 0x15f0d7dc61c43b30, + 0x820c982a69cbbeba, + 0xebed957a62c98c12, + 0x14ba297be56fdccb, + 0x4e3180d3bdf92270, + 0xb6288fcee1c6221d, + 0x8362c953d215e923, + 0xe300883f3a4a2c05, + 0x3fa74bcd535127c, + 0x3c2f6ef3aa9abb6, + 0x78f5f5fc62e8, + ]) + ); + + assert_eq!(Fq12Parameters::FROBENIUS_COEFF_FP12_C1[0], Fq2::one()); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[1], + nqr.pow([ + 0x49aa7ffffffff1c7, + 0x51caaaa72e35555, + 0xe688231ad3c82906, + 0xe613e1eb7deb831f, + 0xc849bf3b5e1f223, + 0x45582fc5eeaa66f, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[2], + nqr.pow([ + 0xdbc7000004bd97b4, + 0xea2791da3e5eb271, + 0x2e5cb340905834d4, + 0xe67542fcdfbd9e8b, + 0x86dd1646bd6d9ab6, + 0x84e6baef6baeba14, + 0x7e32e188819427d5, + 0x62c65cd4d924f712, + 0x667b9a6188c5174d, + 0x507a18262d12b673, + 0xe1f8697c705d30fc, + 0x70b3f0c975e54b, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[3], + nqr.pow(vec![ + 0x6de37e6b79adcf03, + 0x4cbef56885f66b55, + 0x4edde9260b903230, + 0x395cbd66302be22f, + 0xfc74d1185f863147, + 0x323e658c42e31d3, + 0x67401327e2adfb77, + 0xca6c6b8b61c9cfe2, + 0xd6bc7875bbf73770, + 0xeb7f24dff2bee2fc, + 0x8132b6b60ae31b23, + 0x86fb1417888fd481, + 0x8dedd31f03195a5d, + 0x3441acbde55282f5, + 0x52b6a764861a54c1, + 0x3f2621411ddf4859, + 0xfb23945536e58790, + 0xb72bf0b778a97, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[4], + nqr.pow(vec![ + 0xa324d6e9e38e36c8, + 0xa1e5532944b95432, + 0x66d4222ddd5507dd, + 0xe49ef5332b315533, + 0x1431de448c1a240e, + 0xa8d061faea665f6c, + 0x490873307c866574, + 0xf15eb41b62a36b2f, + 0x7911d5dd53e7bbc5, + 0x6a78859116788b40, + 0x6aa07af7fa50cb17, + 0x5091d0f8a05ab293, + 0x98d6728031b52cfb, + 0x1d415e4646fd2bd4, + 0xb246288f10bfe0fc, + 0x9b60bffea9d22ac7, + 0x440df7afeb42777e, + 0x2eb246dee2edda91, + 0xc7e83df8372f2cdc, + 0x46ef6454d65525a8, + 0x2660fc344716f793, + 0xd3a731e5a49601ef, + 0x2be4b40b9e89a4dd, + 0x129b3a7015433, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[5], + nqr.pow(vec![ + 0xfc4b7bc93997595f, + 0xa4e435368ee2c9d0, + 0xf2d98f4a2c0fc8e1, + 0xf1ed2e60535906bf, + 0xc116577ca8705ff6, + 0x98bf6ca85cf733e6, + 0x7feb3200b771fb66, + 0x3becc8e444085891, + 0x31739731af34c132, + 0xc82f0d0d169140a5, + 0xfadbd59d1f99ecc0, + 0xbac38d85e0712ee, + 0x8f174d31efae1bb9, + 0x744458fba22d8a4e, + 0x4aa8e0cf2f3f1612, + 0x76790c9cd1e96b5f, + 0x6c186dfed5b96dea, + 0x3d9a57c6b116a060, + 0x1efb690522b38921, + 0x857c35f718710ecc, + 0xa083260a9a72efae, + 0xfafb655e98b26304, + 0x52e8a5ef95bf732, + 0x538c6034ef7e489c, + 0xed8a23f3b8718887, + 0x60d8b254f4857a48, + 0x38c0220fce928b01, + 0x80fe9d2f354d449f, + 0xf0bdbbceaa6aed, + 0x1e3d7d7f18ba, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[6], + nqr.pow(vec![ + 0x21219610a012ba3c, + 0xa5c19ad35375325, + 0x4e9df1e497674396, + 0xfb05b717c991c6ef, + 0x4a1265bca93a32f2, + 0xd875ff2a7bdc1f66, + 0xc6d8754736c771b2, + 0x2d80c759ba5a2ae7, + 0x138a20df4b03cc1a, + 0xc22d07fe68e93024, + 0xd1dc474d3b433133, + 0xc22aa5e75044e5c, + 0xf657c6fbf9c17ebf, + 0xc591a794a58660d, + 0x2261850ee1453281, + 0xd17d3bd3b7f5efb4, + 0xf00cec8ec507d01, + 0x2a6a775657a00ae6, + 0x5f098a12ff470719, + 0x409d194e7b5c5afa, + 0x1d66478e982af5b, + 0xda425a5b5e01ca3f, + 0xf77e4f78747e903c, + 0x177d49f73732c6fc, + 0xa9618fecabe0e1f4, + 0xba5337eac90bd080, + 0x66fececdbc35d4e7, + 0xa4cd583203d9206f, + 0x98391632ceeca596, + 0x4946b76e1236ad3f, + 0xa0dec64e60e711a1, + 0xfcb41ed3605013, + 0x8ca8f9692ae1e3a9, + 0xd3078bfc28cc1baf, + 0xf0536f764e982f82, + 0x3125f1a2656, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[7], + nqr.pow(vec![ + 0x742754a1f22fdb, + 0x2a1955c2dec3a702, + 0x9747b28c796d134e, + 0xc113a0411f59db79, + 0x3bb0fa929853bfc1, + 0x28c3c25f8f6fb487, + 0xbc2b6c99d3045b34, + 0x98fb67d6badde1fd, + 0x48841d76a24d2073, + 0xd49891145fe93ae6, + 0xc772b9c8e74d4099, + 0xccf4e7b9907755bb, + 0x9cf47b25d42fd908, + 0x5616a0c347fc445d, + 0xff93b7a7ad1b8a6d, + 0xac2099256b78a77a, + 0x7804a95b02892e1c, + 0x5cf59ca7bfd69776, + 0xa7023502acd3c866, + 0xc76f4982fcf8f37, + 0x51862a5a57ac986e, + 0x38b80ed72b1b1023, + 0x4a291812066a61e1, + 0xcd8a685eff45631, + 0x3f40f708764e4fa5, + 0x8aa0441891285092, + 0x9eff60d71cdf0a9, + 0x4fdd9d56517e2bfa, + 0x1f3c80d74a28bc85, + 0x24617417c064b648, + 0x7ddda1e4385d5088, + 0xf9e132b11dd32a16, + 0xcc957cb8ef66ab99, + 0xd4f206d37cb752c5, + 0x40de343f28ad616b, + 0x8d1f24379068f0e3, + 0x6f31d7947ea21137, + 0x27311f9c32184061, + 0x9eea0664cc78ce5f, + 0x7d4151f6fea9a0da, + 0x454096fa75bd571a, + 0x4fe0f20ecb, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[8], + nqr.pow(vec![ + 0x802f5720d0b25710, + 0x6714f0a258b85c7c, + 0x31394c90afdf16e, + 0xe9d2b0c64f957b19, + 0xe67c0d9c5e7903ee, + 0x3156fdc5443ea8ef, + 0x7c4c50524d88c892, + 0xc99dc8990c0ad244, + 0xd37ababf3649a896, + 0x76fe4b838ff7a20c, + 0xcf69ee2cec728db3, + 0xb83535548e5f41, + 0x371147684ccb0c23, + 0x194f6f4fa500db52, + 0xc4571dc78a4c5374, + 0xe4d46d479999ca97, + 0x76b6785a615a151c, + 0xcceb8bcea7eaf8c1, + 0x80d87a6fbe5ae687, + 0x6a97ddddb85ce85, + 0xd783958f26034204, + 0x7144506f2e2e8590, + 0x948693d377aef166, + 0x8364621ed6f96056, + 0xf021777c4c09ee2d, + 0xc6cf5e746ecd50b, + 0xa2337b7aa22743df, + 0xae753f8bbacab39c, + 0xfc782a9e34d3c1cc, + 0x21b827324fe494d9, + 0x5692ce350ed03b38, + 0xf323a2b3cd0481b0, + 0xe859c97a4ccad2e3, + 0x48434b70381e4503, + 0x46042d62e4132ed8, + 0x48c4d6f56122e2f2, + 0xf87711ab9f5c1af7, + 0xb14b7a054759b469, + 0x8eb0a96993ffa9aa, + 0x9b21fb6fc58b760c, + 0xf3abdd115d2e7d25, + 0xf7beac3d4d12409c, + 0x40a5585cce69bf03, + 0x697881e1ba22d5a8, + 0x3d6c04e6ad373fd9, + 0x849871bf627be886, + 0x550f4b9b71b28ef9, + 0x81d2e0d78, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[9], + nqr.pow(vec![ + 0x4af4accf7de0b977, + 0x742485e21805b4ee, + 0xee388fbc4ac36dec, + 0x1e199da57ad178a, + 0xc27c12b292c6726a, + 0x162e6ed84505b5e8, + 0xe191683f336e09df, + 0x17deb7e8d1e0fce6, + 0xd944f19ad06f5836, + 0x4c5f5e59f6276026, + 0xf1ba9c7c148a38a8, + 0xd205fe2dba72b326, + 0x9a2cf2a4c289824e, + 0x4f47ad512c39e24d, + 0xc5894d984000ea09, + 0x2974c03ff7cf01fa, + 0xfcd243b48cb99a22, + 0x2b5150c9313ac1e8, + 0x9089f37c7fc80eda, + 0x989540cc9a7aea56, + 0x1ab1d4e337e63018, + 0x42b546c30d357e43, + 0x1c6abc04f76233d9, + 0x78b3b8d88bf73e47, + 0x151c4e4c45dc68e6, + 0x519a79c4f54397ed, + 0x93f5b51535a127c5, + 0x5fc51b6f52fa153e, + 0x2e0504f2d4a965c3, + 0xc85bd3a3da52bffe, + 0x98c60957a46a89ef, + 0x48c03b5976b91cae, + 0xc6598040a0a61438, + 0xbf0b49dc255953af, + 0xb78dff905b628ab4, + 0x68140b797ba74ab8, + 0x116cf037991d1143, + 0x2f7fe82e58acb0b8, + 0xc20bf7a8f7be5d45, + 0x86c2905c338d5709, + 0xff13a3ae6c8ace3d, + 0xb6f95e2282d08337, + 0xd49f7b313e9cbf29, + 0xf794517193a1ce8c, + 0x39641fecb596a874, + 0x411c4c4edf462fb3, + 0x3f8cd55c10cf25b4, + 0x2bdd7ea165e860b6, + 0xacd7d2cef4caa193, + 0x6558a1d09a05f96, + 0x1f52b5f5b546fc20, + 0x4ee22a5a8c250c12, + 0xd3a63a54a205b6b3, + 0xd2ff5be8, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[10], + nqr.pow(vec![ + 0xe5953a4f96cdda44, + 0x336b2d734cbc32bb, + 0x3f79bfe3cd7410e, + 0x267ae19aaa0f0332, + 0x85a9c4db78d5c749, + 0x90996b046b5dc7d8, + 0x8945eae9820afc6a, + 0x2644ddea2b036bd, + 0x39898e35ac2e3819, + 0x2574eab095659ab9, + 0x65953d51ac5ea798, + 0xc6b8c7afe6752466, + 0x40e9e993e9286544, + 0x7e0ad34ad9700ea0, + 0xac1015eba2c69222, + 0x24f057a19239b5d8, + 0x2043b48c8a3767eb, + 0x1117c124a75d7ff4, + 0x433cfd1a09fb3ce7, + 0x25b087ce4bcf7fb, + 0xbcee0dc53a3e5bdb, + 0xbffda040cf028735, + 0xf7cf103a25512acc, + 0x31d4ecda673130b9, + 0xea0906dab18461e6, + 0x5a40585a5ac3050d, + 0x803358fc14fd0eda, + 0x3678ca654eada770, + 0x7b91a1293a45e33e, + 0xcd5e5b8ea8530e43, + 0x21ae563ab34da266, + 0xecb00dad60df8894, + 0x77fe53e652facfef, + 0x9b7d1ad0b00244ec, + 0xe695df5ca73f801, + 0x23cdb21feeab0149, + 0x14de113e7ea810d9, + 0x52600cd958dac7e7, + 0xc83392c14667e488, + 0x9f808444bc1717fc, + 0x56facb4bcf7c788f, + 0x8bcad53245fc3ca0, + 0xdef661e83f27d81c, + 0x37d4ebcac9ad87e5, + 0x6fe8b24f5cdb9324, + 0xee08a26c1197654c, + 0xc98b22f65f237e9a, + 0xf54873a908ed3401, + 0x6e1cb951d41f3f3, + 0x290b2250a54e8df6, + 0x7f36d51eb1db669e, + 0xb08c7ed81a6ee43e, + 0x95e1c90fb092f680, + 0x429e4afd0e8b820, + 0x2c14a83ee87d715c, + 0xf37267575cfc8af5, + 0xb99e9afeda3c2c30, + 0x8f0f69da75792d5a, + 0x35074a85a533c73, + 0x156ed119, + ]) + ); + assert_eq!( + Fq12Parameters::FROBENIUS_COEFF_FP12_C1[11], + nqr.pow(vec![ + 0x107db680942de533, + 0x6262b24d2052393b, + 0x6136df824159ebc, + 0xedb052c9970c5deb, + 0xca813aea916c3777, + 0xf49dacb9d76c1788, + 0x624941bd372933bb, + 0xa5e60c2520638331, + 0xb38b661683411074, + 0x1d2c9af4c43d962b, + 0x17d807a0f14aa830, + 0x6e6581a51012c108, + 0x668a537e5b35e6f5, + 0x6c396cf3782dca5d, + 0x33b679d1bff536ed, + 0x736cce41805d90aa, + 0x8a562f369eb680bf, + 0x9f61aa208a11ded8, + 0x43dd89dd94d20f35, + 0xcf84c6610575c10a, + 0x9f318d49cf2fe8e6, + 0xbbc6e5f25a6e434e, + 0x6528c433d11d987b, + 0xffced71cc48c0e8a, + 0x4cbb1474f4cb2a26, + 0x66a035c0b28b7231, + 0xa6f2875faa1a82ae, + 0xdd1ea3deff818b02, + 0xe0cfdf0dcdecf701, + 0x9aefa231f2f6d23, + 0xfb251297efa06746, + 0x5a40d367df985538, + 0x1ea31d69ab506fed, + 0xc64ea8280e89a73f, + 0x969acf9f2d4496f4, + 0xe84c9181ee60c52c, + 0xc60f27fc19fc6ca4, + 0x760b33d850154048, + 0x84f69080f66c8457, + 0xc0192ba0fabf640e, + 0xd2c338765c23a3a8, + 0xa7838c20f02cec6c, + 0xb7cf01d020572877, + 0xd63ffaeba0be200a, + 0xf7492baeb5f041ac, + 0x8602c5212170d117, + 0xad9b2e83a5a42068, + 0x2461829b3ba1083e, + 0x7c34650da5295273, + 0xdc824ba800a8265a, + 0xd18d9b47836af7b2, + 0x3af78945c58cbf4d, + 0x7ed9575b8596906c, + 0x6d0c133895009a66, + 0x53bc1247ea349fe1, + 0x6b3063078d41aa7a, + 0x6184acd8cd880b33, + 0x76f4d15503fd1b96, + 0x7a9afd61eef25746, + 0xce974aadece60609, + 0x88ca59546a8ceafd, + 0x6d29391c41a0ac07, + 0x443843a60e0f46a6, + 0xa1590f62fd2602c7, + 0x536d5b15b514373f, + 0x22d582b, + ]) + ); +} + +#[test] +fn test_neg_one() { + let o = -Fq::one(); + + let thing: [u64; 6] = [ + 0x43f5fffffffcaaae, + 0x32b7fff2ed47fffd, + 0x7e83a49a2e99d69, + 0xeca8f3318332bb7a, + 0xef148d1ea0f4c069, + 0x40ab3263eff0206, + ]; + println!("{:?}", thing); + let negative_one = Fq::new(BigInteger384(thing)); + + assert_eq!(negative_one, o); +} + +#[test] +fn test_fq_repr_from() { + assert_eq!( + BigInteger384::from(100), + BigInteger384([100, 0, 0, 0, 0, 0]) + ); +} + +#[test] +fn test_fq_repr_is_odd() { + assert!(!BigInteger384::from(0).is_odd()); + assert!(BigInteger384::from(0).is_even()); + assert!(BigInteger384::from(1).is_odd()); + assert!(!BigInteger384::from(1).is_even()); + assert!(!BigInteger384::from(324834872).is_odd()); + assert!(BigInteger384::from(324834872).is_even()); + assert!(BigInteger384::from(324834873).is_odd()); + assert!(!BigInteger384::from(324834873).is_even()); +} + +#[test] +fn test_fq_repr_is_zero() { + assert!(BigInteger384::from(0).is_zero()); + assert!(!BigInteger384::from(1).is_zero()); + assert!(!BigInteger384([0, 0, 0, 0, 1, 0]).is_zero()); +} + +#[test] +fn test_fq_repr_div2() { + let mut a = BigInteger384([ + 0x8b0ad39f8dd7482a, + 0x147221c9a7178b69, + 0x54764cb08d8a6aa0, + 0x8519d708e1d83041, + 0x41f82777bd13fdb, + 0xf43944578f9b771b, + ]); + a.div2(); + assert_eq!( + a, + BigInteger384([ + 0xc58569cfc6eba415, + 0xa3910e4d38bc5b4, + 0xaa3b265846c53550, + 0xc28ceb8470ec1820, + 0x820fc13bbde89fed, + 0x7a1ca22bc7cdbb8d, + ]) + ); + for _ in 0..10 { + a.div2(); + } + assert_eq!( + a, + BigInteger384([ + 0x6d31615a73f1bae9, + 0x54028e443934e2f1, + 0x82a8ec99611b14d, + 0xfb70a33ae11c3b06, + 0xe36083f04eef7a27, + 0x1e87288af1f36e, + ]) + ); + for _ in 0..300 { + a.div2(); + } + assert_eq!( + a, + BigInteger384([0x7288af1f36ee3608, 0x1e8, 0x0, 0x0, 0x0, 0x0]) + ); + for _ in 0..50 { + a.div2(); + } + assert_eq!(a, BigInteger384([0x7a1ca2, 0x0, 0x0, 0x0, 0x0, 0x0])); + for _ in 0..22 { + a.div2(); + } + assert_eq!(a, BigInteger384([0x1, 0x0, 0x0, 0x0, 0x0, 0x0])); + a.div2(); + assert!(a.is_zero()); +} + +#[test] +fn test_fq_repr_divn() { + let mut a = BigInteger384([ + 0xaa5cdd6172847ffd, + 0x43242c06aed55287, + 0x9ddd5b312f3dd104, + 0xc5541fd48046b7e7, + 0x16080cf4071e0b05, + 0x1225f2901aea514e, + ]); + a.divn(0); + assert_eq!( + a, + BigInteger384([ + 0xaa5cdd6172847ffd, + 0x43242c06aed55287, + 0x9ddd5b312f3dd104, + 0xc5541fd48046b7e7, + 0x16080cf4071e0b05, + 0x1225f2901aea514e, + ]) + ); + a.divn(1); + assert_eq!( + a, + BigInteger384([ + 0xd52e6eb0b9423ffe, + 0x21921603576aa943, + 0xceeead98979ee882, + 0xe2aa0fea40235bf3, + 0xb04067a038f0582, + 0x912f9480d7528a7, + ]) + ); + a.divn(50); + assert_eq!( + a, + BigInteger384([ + 0x8580d5daaa50f54b, + 0xab6625e7ba208864, + 0x83fa9008d6fcf3bb, + 0x19e80e3c160b8aa, + 0xbe52035d4a29c2c1, + 0x244, + ]) + ); + a.divn(130); + assert_eq!( + a, + BigInteger384([ + 0xa0fea40235bf3cee, + 0x4067a038f0582e2a, + 0x2f9480d7528a70b0, + 0x91, + 0x0, + 0x0, + ]) + ); + a.divn(64); + assert_eq!( + a, + BigInteger384([0x4067a038f0582e2a, 0x2f9480d7528a70b0, 0x91, 0x0, 0x0, 0x0]) + ); +} + +#[test] +fn test_fq_repr_mul2() { + let mut a = BigInteger384::from(23712937547); + a.mul2(); + assert_eq!(a, BigInteger384([0xb0acd6c96, 0x0, 0x0, 0x0, 0x0, 0x0])); + for _ in 0..60 { + a.mul2(); + } + assert_eq!( + a, + BigInteger384([0x6000000000000000, 0xb0acd6c9, 0x0, 0x0, 0x0, 0x0]) + ); + for _ in 0..300 { + a.mul2(); + } + assert_eq!( + a, + BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0xcd6c960000000000]) + ); + for _ in 0..17 { + a.mul2(); + } + assert_eq!( + a, + BigInteger384([0x0, 0x0, 0x0, 0x0, 0x0, 0x2c00000000000000]) + ); + for _ in 0..6 { + a.mul2(); + } + assert!(a.is_zero()); +} + +#[test] +fn test_fq_repr_num_bits() { + let mut a = BigInteger384::from(0); + assert_eq!(0, a.num_bits()); + a = BigInteger384::from(1); + for i in 1..385 { + assert_eq!(i, a.num_bits()); + a.mul2(); + } + assert_eq!(0, a.num_bits()); +} + +#[test] +fn test_fq_repr_sub_noborrow() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let mut t = BigInteger384([ + 0x827a4a08041ebd9, + 0x3c239f3dcc8f0d6b, + 0x9ab46a912d555364, + 0x196936b17b43910b, + 0xad0eb3948a5c34fd, + 0xd56f7b5ab8b5ce8, + ]); + t.sub_noborrow(&BigInteger384([ + 0xc7867917187ca02b, + 0x5d75679d4911ffef, + 0x8c5b3e48b1a71c15, + 0x6a427ae846fd66aa, + 0x7a37e7265ee1eaf9, + 0x7c0577a26f59d5, + ])); + assert!( + t == BigInteger384([ + 0x40a12b8967c54bae, + 0xdeae37a0837d0d7b, + 0xe592c487bae374e, + 0xaf26bbc934462a61, + 0x32d6cc6e2b7a4a03, + 0xcdaf23e091c0313, + ]) + ); + + for _ in 0..1000 { + let mut a = BigInteger384::rand(&mut rng); + a.0[5] >>= 30; + let mut b = a; + for _ in 0..10 { + b.mul2(); + } + let mut c = b; + for _ in 0..10 { + c.mul2(); + } + + assert!(a < b); + assert!(b < c); + + let mut csub_ba = c; + csub_ba.sub_noborrow(&b); + csub_ba.sub_noborrow(&a); + + let mut csub_ab = c; + csub_ab.sub_noborrow(&a); + csub_ab.sub_noborrow(&b); + + assert_eq!(csub_ab, csub_ba); + } + + // Subtracting q+1 from q should produce -1 (mod 2**384) + let mut qplusone = BigInteger384([ + 0xb9feffffffffaaab, + 0x1eabfffeb153ffff, + 0x6730d2a0f6b0f624, + 0x64774b84f38512bf, + 0x4b1ba7b6434bacd7, + 0x1a0111ea397fe69a, + ]); + qplusone.sub_noborrow(&BigInteger384([ + 0xb9feffffffffaaac, + 0x1eabfffeb153ffff, + 0x6730d2a0f6b0f624, + 0x64774b84f38512bf, + 0x4b1ba7b6434bacd7, + 0x1a0111ea397fe69a, + ])); + assert_eq!( + qplusone, + BigInteger384([ + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + ]) + ); +} + +#[test] +fn test_fq_repr_add_nocarry() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let mut t = BigInteger384([ + 0x827a4a08041ebd9, + 0x3c239f3dcc8f0d6b, + 0x9ab46a912d555364, + 0x196936b17b43910b, + 0xad0eb3948a5c34fd, + 0xd56f7b5ab8b5ce8, + ]); + t.add_nocarry(&BigInteger384([ + 0xc7867917187ca02b, + 0x5d75679d4911ffef, + 0x8c5b3e48b1a71c15, + 0x6a427ae846fd66aa, + 0x7a37e7265ee1eaf9, + 0x7c0577a26f59d5, + ])); + assert!( + t == BigInteger384([ + 0xcfae1db798be8c04, + 0x999906db15a10d5a, + 0x270fa8d9defc6f79, + 0x83abb199c240f7b6, + 0x27469abae93e1ff6, + 0xdd2fd2d4dfab6be, + ]) + ); + + // Test for the associativity of addition. + for _ in 0..1000 { + let mut a = BigInteger384::rand(&mut rng); + let mut b = BigInteger384::rand(&mut rng); + let mut c = BigInteger384::rand(&mut rng); + + // Unset the first few bits, so that overflow won't occur. + a.0[5] >>= 3; + b.0[5] >>= 3; + c.0[5] >>= 3; + + let mut abc = a; + abc.add_nocarry(&b); + abc.add_nocarry(&c); + + let mut acb = a; + acb.add_nocarry(&c); + acb.add_nocarry(&b); + + let mut bac = b; + bac.add_nocarry(&a); + bac.add_nocarry(&c); + + let mut bca = b; + bca.add_nocarry(&c); + bca.add_nocarry(&a); + + let mut cab = c; + cab.add_nocarry(&a); + cab.add_nocarry(&b); + + let mut cba = c; + cba.add_nocarry(&b); + cba.add_nocarry(&a); + + assert_eq!(abc, acb); + assert_eq!(abc, bac); + assert_eq!(abc, bca); + assert_eq!(abc, cab); + assert_eq!(abc, cba); + } + + // Adding 1 to (2^384 - 1) should produce zero + let mut x = BigInteger384([ + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + ]); + x.add_nocarry(&BigInteger384::from(1)); + assert!(x.is_zero()); +} + +#[test] +fn test_fq_is_valid() { + let mut a = Fq::new(FqParameters::MODULUS); + assert!(!a.is_valid()); + a.0.sub_noborrow(&BigInteger384::from(1)); + assert!(a.is_valid()); + assert!(Fq::new(BigInteger384::from(0)).is_valid()); + assert!(Fq::new(BigInteger384([ + 0xdf4671abd14dab3e, + 0xe2dc0c9f534fbd33, + 0x31ca6c880cc444a6, + 0x257a67e70ef33359, + 0xf9b29e493f899b36, + 0x17c8be1800b9f059, + ])) + .is_valid()); + assert!(!Fq::new(BigInteger384([ + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + ])) + .is_valid()); + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let a = Fq::rand(&mut rng); + assert!(a.is_valid()); + } +} + +#[test] +fn test_fq_add_assign() { + { + // Random number + let mut tmp = Fq::new(BigInteger384([ + 0x624434821df92b69, + 0x503260c04fd2e2ea, + 0xd9df726e0d16e8ce, + 0xfbcb39adfd5dfaeb, + 0x86b8a22b0c88b112, + 0x165a2ed809e4201b, + ])); + assert!(tmp.is_valid()); + // Test that adding zero has no effect. + tmp.add_assign(&Fq::new(BigInteger384::from(0))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0x624434821df92b69, + 0x503260c04fd2e2ea, + 0xd9df726e0d16e8ce, + 0xfbcb39adfd5dfaeb, + 0x86b8a22b0c88b112, + 0x165a2ed809e4201b, + ])) + ); + // Add one and test for the result. + tmp.add_assign(&Fq::new(BigInteger384::from(1))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0x624434821df92b6a, + 0x503260c04fd2e2ea, + 0xd9df726e0d16e8ce, + 0xfbcb39adfd5dfaeb, + 0x86b8a22b0c88b112, + 0x165a2ed809e4201b, + ])) + ); + // Add another random number that exercises the reduction. + tmp.add_assign(&Fq::new(BigInteger384([ + 0x374d8f8ea7a648d8, + 0xe318bb0ebb8bfa9b, + 0x613d996f0a95b400, + 0x9fac233cb7e4fef1, + 0x67e47552d253c52, + 0x5c31b227edf25da, + ]))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0xdf92c410c59fc997, + 0x149f1bd05a0add85, + 0xd3ec393c20fba6ab, + 0x37001165c1bde71d, + 0x421b41c9f662408e, + 0x21c38104f435f5b, + ])) + ); + // Add one to (q - 1) and test for the result. + tmp = Fq::new(BigInteger384([ + 0xb9feffffffffaaaa, + 0x1eabfffeb153ffff, + 0x6730d2a0f6b0f624, + 0x64774b84f38512bf, + 0x4b1ba7b6434bacd7, + 0x1a0111ea397fe69a, + ])); + tmp.add_assign(&Fq::new(BigInteger384::from(1))); + assert!(tmp.0.is_zero()); + // Add a random number to another one such that the result is q - 1 + tmp = Fq::new(BigInteger384([ + 0x531221a410efc95b, + 0x72819306027e9717, + 0x5ecefb937068b746, + 0x97de59cd6feaefd7, + 0xdc35c51158644588, + 0xb2d176c04f2100, + ])); + tmp.add_assign(&Fq::new(BigInteger384([ + 0x66ecde5bef0fe14f, + 0xac2a6cf8aed568e8, + 0x861d70d86483edd, + 0xcc98f1b7839a22e8, + 0x6ee5e2a4eae7674e, + 0x194e40737930c599, + ]))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0xb9feffffffffaaaa, + 0x1eabfffeb153ffff, + 0x6730d2a0f6b0f624, + 0x64774b84f38512bf, + 0x4b1ba7b6434bacd7, + 0x1a0111ea397fe69a, + ])) + ); + // Add one to the result and test for it. + tmp.add_assign(&Fq::new(BigInteger384::from(1))); + assert!(tmp.0.is_zero()); + } + + // Test associativity + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Generate a, b, c and ensure (a + b) + c == a + (b + c). + let a = Fq::rand(&mut rng); + let b = Fq::rand(&mut rng); + let c = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.add_assign(&b); + tmp1.add_assign(&c); + + let mut tmp2 = b; + tmp2.add_assign(&c); + tmp2.add_assign(&a); + + assert!(tmp1.is_valid()); + assert!(tmp2.is_valid()); + assert_eq!(tmp1, tmp2); + } +} + +#[test] +fn test_fq_sub_assign() { + { + // Test arbitrary subtraction that tests reduction. + let mut tmp = Fq::new(BigInteger384([ + 0x531221a410efc95b, + 0x72819306027e9717, + 0x5ecefb937068b746, + 0x97de59cd6feaefd7, + 0xdc35c51158644588, + 0xb2d176c04f2100, + ])); + tmp.sub_assign(&Fq::new(BigInteger384([ + 0x98910d20877e4ada, + 0x940c983013f4b8ba, + 0xf677dc9b8345ba33, + 0xbef2ce6b7f577eba, + 0xe1ae288ac3222c44, + 0x5968bb602790806, + ]))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0x748014838971292c, + 0xfd20fad49fddde5c, + 0xcf87f198e3d3f336, + 0x3d62d6e6e41883db, + 0x45a3443cd88dc61b, + 0x151d57aaf755ff94, + ])) + ); + + // Test the opposite subtraction which doesn't test reduction. + tmp = Fq::new(BigInteger384([ + 0x98910d20877e4ada, + 0x940c983013f4b8ba, + 0xf677dc9b8345ba33, + 0xbef2ce6b7f577eba, + 0xe1ae288ac3222c44, + 0x5968bb602790806, + ])); + tmp.sub_assign(&Fq::new(BigInteger384([ + 0x531221a410efc95b, + 0x72819306027e9717, + 0x5ecefb937068b746, + 0x97de59cd6feaefd7, + 0xdc35c51158644588, + 0xb2d176c04f2100, + ]))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0x457eeb7c768e817f, + 0x218b052a117621a3, + 0x97a8e10812dd02ed, + 0x2714749e0f6c8ee3, + 0x57863796abde6bc, + 0x4e3ba3f4229e706, + ])) + ); + + // Test for sensible results with zero + tmp = Fq::new(BigInteger384::from(0)); + tmp.sub_assign(&Fq::new(BigInteger384::from(0))); + assert!(tmp.is_zero()); + + tmp = Fq::new(BigInteger384([ + 0x98910d20877e4ada, + 0x940c983013f4b8ba, + 0xf677dc9b8345ba33, + 0xbef2ce6b7f577eba, + 0xe1ae288ac3222c44, + 0x5968bb602790806, + ])); + tmp.sub_assign(&Fq::new(BigInteger384::from(0))); + assert_eq!( + tmp, + Fq::new(BigInteger384([ + 0x98910d20877e4ada, + 0x940c983013f4b8ba, + 0xf677dc9b8345ba33, + 0xbef2ce6b7f577eba, + 0xe1ae288ac3222c44, + 0x5968bb602790806, + ])) + ); + } + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Ensure that (a - b) + (b - a) = 0. + let a = Fq::rand(&mut rng); + let b = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.sub_assign(&b); + + let mut tmp2 = b; + tmp2.sub_assign(&a); + + tmp1.add_assign(&tmp2); + assert!(tmp1.is_zero()); + } +} + +#[test] +fn test_fq_mul_assign() { + let mut tmp = Fq::new(BigInteger384([ + 0xcc6200000020aa8a, + 0x422800801dd8001a, + 0x7f4f5e619041c62c, + 0x8a55171ac70ed2ba, + 0x3f69cc3a3d07d58b, + 0xb972455fd09b8ef, + ])); + tmp.mul_assign(&Fq::new(BigInteger384([ + 0x329300000030ffcf, + 0x633c00c02cc40028, + 0xbef70d925862a942, + 0x4f7fa2a82a963c17, + 0xdf1eb2575b8bc051, + 0x1162b680fb8e9566, + ]))); + assert!( + tmp == Fq::new(BigInteger384([ + 0x9dc4000001ebfe14, + 0x2850078997b00193, + 0xa8197f1abb4d7bf, + 0xc0309573f4bfe871, + 0xf48d0923ffaf7620, + 0x11d4b58c7a926e66, + ])) + ); + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000000 { + // Ensure that (a * b) * c = a * (b * c) + let a = Fq::rand(&mut rng); + let b = Fq::rand(&mut rng); + let c = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.mul_assign(&b); + tmp1.mul_assign(&c); + + let mut tmp2 = b; + tmp2.mul_assign(&c); + tmp2.mul_assign(&a); + + assert_eq!(tmp1, tmp2); + } + + for _ in 0..1000000 { + // Ensure that r * (a + b + c) = r*a + r*b + r*c + + let r = Fq::rand(&mut rng); + let mut a = Fq::rand(&mut rng); + let mut b = Fq::rand(&mut rng); + let mut c = Fq::rand(&mut rng); + + let mut tmp1 = a; + tmp1.add_assign(&b); + tmp1.add_assign(&c); + tmp1.mul_assign(&r); + + a.mul_assign(&r); + b.mul_assign(&r); + c.mul_assign(&r); + + a.add_assign(&b); + a.add_assign(&c); + + assert_eq!(tmp1, a); + } +} + +#[test] +fn test_fq_squaring() { + let mut a = Fq::new(BigInteger384([ + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0xffffffffffffffff, + 0x19ffffffffffffff, + ])); + assert!(a.is_valid()); + a.square_in_place(); + assert_eq!( + a, + Fq::from_repr(BigInteger384([ + 0x1cfb28fe7dfbbb86, + 0x24cbe1731577a59, + 0xcce1d4edc120e66e, + 0xdc05c659b4e15b27, + 0x79361e5a802c6a23, + 0x24bcbe5d51b9a6f, + ])) + ); + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000000 { + // Ensure that (a * a) = a^2 + let a = Fq::rand(&mut rng); + + let mut tmp = a; + tmp.square_in_place(); + + let mut tmp2 = a; + tmp2.mul_assign(&a); + + assert_eq!(tmp, tmp2); + } +} + +#[test] +fn test_fq_inverse() { + assert!(Fq::zero().inverse().is_none()); + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let one = Fq::one(); + + for _ in 0..1000 { + // Ensure that a * a^-1 = 1 + let mut a = Fq::rand(&mut rng); + let ainv = a.inverse().unwrap(); + a.mul_assign(&ainv); + assert_eq!(a, one); + } +} + +#[test] +fn test_fq_double_in_place() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Ensure doubling a is equivalent to adding a to itself. + let mut a = Fq::rand(&mut rng); + let mut b = a; + b.add_assign(&a); + a.double_in_place(); + assert_eq!(a, b); + } +} + +#[test] +fn test_fq_negate() { + { + let a = -Fq::zero(); + + assert!(a.is_zero()); + } + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + // Ensure (a - (-a)) = 0. + let mut a = Fq::rand(&mut rng); + let b = -a; + a.add_assign(&b); + + assert!(a.is_zero()); + } +} + +#[test] +fn test_fq_pow() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for i in 0..1000 { + // Exponentiate by various small numbers and ensure it consists with repeated + // multiplication. + let a = Fq::rand(&mut rng); + let target = a.pow(&[i]); + let mut c = Fq::one(); + for _ in 0..i { + c.mul_assign(&a); + } + assert_eq!(c, target); + } + + for _ in 0..1000 { + // Exponentiating by the modulus should have no effect in a prime field. + let a = Fq::rand(&mut rng); + + assert_eq!(a, a.pow(Fq::characteristic().0)); + } +} + +#[test] +fn test_fq_sqrt() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + assert_eq!(Fq::zero().sqrt().unwrap(), Fq::zero()); + + for _ in 0..1000 { + // Ensure sqrt(a^2) = a or -a + let a = Fq::rand(&mut rng); + let nega = -a; + let mut b = a; + b.square_in_place(); + + let b = b.sqrt().unwrap(); + + assert!(a == b || nega == b); + } + + for _ in 0..1000 { + // Ensure sqrt(a)^2 = a for random a + let a = Fq::rand(&mut rng); + + if let Some(mut tmp) = a.sqrt() { + tmp.square_in_place(); + + assert_eq!(a, tmp); + } + } +} + +#[test] +fn test_fq_num_bits() { + assert_eq!(FqParameters::MODULUS_BITS, 381); + assert_eq!(FqParameters::CAPACITY, 380); +} + +#[test] +fn test_fq_root_of_unity() { + assert_eq!(FqParameters::TWO_ADICITY, 1); + assert_eq!( + Fq::multiplicative_generator(), + Fq::from_repr(BigInteger384::from(2)) + ); + assert_eq!( + Fq::multiplicative_generator().pow([ + 0xdcff7fffffffd555, + 0xf55ffff58a9ffff, + 0xb39869507b587b12, + 0xb23ba5c279c2895f, + 0x258dd3db21a5d66b, + 0xd0088f51cbff34d, + ]), + Fq::root_of_unity() + ); + assert_eq!( + Fq::root_of_unity().pow([1 << FqParameters::TWO_ADICITY]), + Fq::one() + ); + assert!(Fq::multiplicative_generator().sqrt().is_none()); +} + +// #[test] +// fn fq_field_tests() { +// ::tests::field::random_field_tests::(); +// ::tests::field::random_sqrt_tests::(); +// ::tests::field::random_frobenius_tests::(Fq::char(), 13); +// ::tests::field::from_str_tests::(); +// } + +#[test] +fn test_fq_ordering() { + // BigInteger384's ordering is well-tested, but we still need to make sure the + // Fq elements aren't being compared in Montgomery form. + for i in 0..100 { + assert!(Fq::from_repr(BigInteger384::from(i + 1)) > Fq::from_repr(BigInteger384::from(i))); + } +} + +// #[test] +// fn fq_repr_tests() { +// ::tests::repr::random_repr_tests::(); +// } + +#[test] +fn test_fq_legendre() { + use crate::fields::LegendreSymbol::*; + + assert_eq!(QuadraticResidue, Fq::one().legendre()); + assert_eq!(Zero, Fq::zero().legendre()); + + assert_eq!( + QuadraticNonResidue, + Fq::from_repr(BigInteger384::from(2)).legendre() + ); + assert_eq!( + QuadraticResidue, + Fq::from_repr(BigInteger384::from(4)).legendre() + ); + + let e = BigInteger384([ + 0x52a112f249778642, + 0xd0bedb989b7991f, + 0xdad3b6681aa63c05, + 0xf2efc0bb4721b283, + 0x6057a98f18c24733, + 0x1022c2fd122889e4, + ]); + assert_eq!(QuadraticNonResidue, Fq::from_repr(e).legendre()); + let e = BigInteger384([ + 0x6dae594e53a96c74, + 0x19b16ca9ba64b37b, + 0x5c764661a59bfc68, + 0xaa346e9b31c60a, + 0x346059f9d87a9fa9, + 0x1d61ac6bfd5c88b, + ]); + assert_eq!(QuadraticResidue, Fq::from_repr(e).legendre()); +} + +#[test] +fn test_fq2_ordering() { + let mut a = Fq2::new(Fq::zero(), Fq::zero()); + + let mut b = a.clone(); + + assert!(a.cmp(&b) == Ordering::Equal); + b.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Less); + a.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Equal); + b.c1.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Less); + a.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Less); + a.c1.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Greater); + b.c0.add_assign(&Fq::one()); + assert!(a.cmp(&b) == Ordering::Equal); +} + +#[test] +fn test_fq2_basics() { + assert_eq!(Fq2::new(Fq::zero(), Fq::zero(),), Fq2::zero()); + assert_eq!(Fq2::new(Fq::one(), Fq::zero(),), Fq2::one()); + assert!(Fq2::zero().is_zero()); + assert!(!Fq2::one().is_zero()); + assert!(!Fq2::new(Fq::zero(), Fq::one(),).is_zero()); +} + +#[test] +fn test_fq2_squaring() { + let a = Fq2::new(Fq::one(), Fq::one()).square(); // u + 1 + assert_eq!( + a, + Fq2::new(Fq::zero(), Fq::from_repr(BigInteger384::from(2)),) + ); // 2u + + let a = Fq2::new(Fq::zero(), Fq::one()).square(); // u + assert_eq!(a, { + let neg1 = -Fq::one(); + Fq2::new(neg1, Fq::zero()) + }); // -1 + + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x9c2c6309bbf8b598, + 0x4eef5c946536f602, + 0x90e34aab6fb6a6bd, + 0xf7f295a94e58ae7c, + 0x41b76dcc1c3fbe5e, + 0x7080c5fa1d8e042, + ])), + Fq::from_repr(BigInteger384([ + 0x38f473b3c870a4ab, + 0x6ad3291177c8c7e5, + 0xdac5a4c911a4353e, + 0xbfb99020604137a0, + 0xfc58a7b7be815407, + 0x10d1615e75250a21, + ])), + ); + a.square_in_place(); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0xf262c28c538bcf68, + 0xb9f2a66eae1073ba, + 0xdc46ab8fad67ae0, + 0xcb674157618da176, + 0x4cf17b5893c3d327, + 0x7eac81369c43361, + ])), + Fq::from_repr(BigInteger384([ + 0xc1579cf58e980cf8, + 0xa23eb7e12dd54d98, + 0xe75138bce4cec7aa, + 0x38d0d7275a9689e1, + 0x739c983042779a65, + 0x1542a61c8a8db994, + ])), + ) + ); +} + +#[test] +fn test_fq2_mul() { + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x85c9f989e1461f03, + 0xa2e33c333449a1d6, + 0x41e461154a7354a3, + 0x9ee53e7e84d7532e, + 0x1c202d8ed97afb45, + 0x51d3f9253e2516f, + ])), + Fq::from_repr(BigInteger384([ + 0xa7348a8b511aedcf, + 0x143c215d8176b319, + 0x4cc48081c09b8903, + 0x9533e4a9a5158be, + 0x7a5e1ecb676d65f9, + 0x180c3ee46656b008, + ])), + ); + a.mul_assign(&Fq2::new( + Fq::from_repr(BigInteger384([ + 0xe21f9169805f537e, + 0xfc87e62e179c285d, + 0x27ece175be07a531, + 0xcd460f9f0c23e430, + 0x6c9110292bfa409, + 0x2c93a72eb8af83e, + ])), + Fq::from_repr(BigInteger384([ + 0x4b1c3f936d8992d4, + 0x1d2a72916dba4c8a, + 0x8871c508658d1e5f, + 0x57a06d3135a752ae, + 0x634cd3c6c565096d, + 0x19e17334d4e93558, + ])), + )); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x95b5127e6360c7e4, + 0xde29c31a19a6937e, + 0xf61a96dacf5a39bc, + 0x5511fe4d84ee5f78, + 0x5310a202d92f9963, + 0x1751afbe166e5399, + ])), + Fq::from_repr(BigInteger384([ + 0x84af0e1bd630117a, + 0x6c63cd4da2c2aa7, + 0x5ba6e5430e883d40, + 0xc975106579c275ee, + 0x33a9ac82ce4c5083, + 0x1ef1a36c201589d, + ])), + ) + ); +} + +#[test] +fn test_fq2_inverse() { + assert!(Fq2::zero().inverse().is_none()); + + let a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x85c9f989e1461f03, + 0xa2e33c333449a1d6, + 0x41e461154a7354a3, + 0x9ee53e7e84d7532e, + 0x1c202d8ed97afb45, + 0x51d3f9253e2516f, + ])), + Fq::from_repr(BigInteger384([ + 0xa7348a8b511aedcf, + 0x143c215d8176b319, + 0x4cc48081c09b8903, + 0x9533e4a9a5158be, + 0x7a5e1ecb676d65f9, + 0x180c3ee46656b008, + ])), + ); + let a = a.inverse().unwrap(); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x70300f9bcb9e594, + 0xe5ecda5fdafddbb2, + 0x64bef617d2915a8f, + 0xdfba703293941c30, + 0xa6c3d8f9586f2636, + 0x1351ef01941b70c4, + ])), + Fq::from_repr(BigInteger384([ + 0x8c39fd76a8312cb4, + 0x15d7b6b95defbff0, + 0x947143f89faedee9, + 0xcbf651a0f367afb2, + 0xdf4e54f0d3ef15a6, + 0x103bdf241afb0019, + ])), + ) + ); +} + +#[test] +fn test_fq2_addition() { + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ); + a.add_assign(&Fq2::new( + Fq::from_repr(BigInteger384([ + 0x619a02d78dc70ef2, + 0xb93adfc9119e33e8, + 0x4bf0b99a9f0dca12, + 0x3b88899a42a6318f, + 0x986a4a62fa82a49d, + 0x13ce433fa26027f5, + ])), + Fq::from_repr(BigInteger384([ + 0x66323bf80b58b9b9, + 0xa1379b6facf6e596, + 0x402aef1fb797e32f, + 0x2236f55246d0d44d, + 0x4c8c1800eb104566, + 0x11d6e20e986c2085, + ])), + )); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x8e9a7adaf6eb0eb9, + 0xcb207e6b3341eaba, + 0xd70b0c7b481d23ff, + 0xf4ef57d604b6bca2, + 0x65309427b3d5d090, + 0x14c715d5553f01d2, + ])), + Fq::from_repr(BigInteger384([ + 0xfdb032e7d9079a94, + 0x35a2809d15468d83, + 0xfe4b23317e0796d5, + 0xd62fa51334f560fa, + 0x9ad265eb46e01984, + 0x1303f3465112c8bc, + ])), + ) + ); +} + +#[test] +fn test_fq2_subtraction() { + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ); + a.sub_assign(&Fq2::new( + Fq::from_repr(BigInteger384([ + 0x619a02d78dc70ef2, + 0xb93adfc9119e33e8, + 0x4bf0b99a9f0dca12, + 0x3b88899a42a6318f, + 0x986a4a62fa82a49d, + 0x13ce433fa26027f5, + ])), + Fq::from_repr(BigInteger384([ + 0x66323bf80b58b9b9, + 0xa1379b6facf6e596, + 0x402aef1fb797e32f, + 0x2236f55246d0d44d, + 0x4c8c1800eb104566, + 0x11d6e20e986c2085, + ])), + )); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x8565752bdb5c9b80, + 0x7756bed7c15982e9, + 0xa65a6be700b285fe, + 0xe255902672ef6c43, + 0x7f77a718021c342d, + 0x72ba14049fe9881, + ])), + Fq::from_repr(BigInteger384([ + 0xeb4abaf7c255d1cd, + 0x11df49bc6cacc256, + 0xe52617930588c69a, + 0xf63905f39ad8cb1f, + 0x4cd5dd9fb40b3b8f, + 0x957411359ba6e4c, + ])), + ) + ); +} + +#[test] +fn test_fq2_negation() { + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ); + a = -a; + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x8cfe87fc96dbaae4, + 0xcc6615c8fb0492d, + 0xdc167fc04da19c37, + 0xab107d49317487ab, + 0x7e555df189f880e3, + 0x19083f5486a10cbd, + ])), + Fq::from_repr(BigInteger384([ + 0x228109103250c9d0, + 0x8a411ad149045812, + 0xa9109e8f3041427e, + 0xb07e9bc405608611, + 0xfcd559cbe77bd8b8, + 0x18d400b280d93e62, + ])), + ) + ); +} + +#[test] +fn test_fq2_doubling() { + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ); + a.double_in_place(); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x5a00f006d247ff8e, + 0x23cb3d4443476da4, + 0x1634a5c1521eb3da, + 0x72cd9c7784211627, + 0x998c938972a657e7, + 0x1f1a52b65bdb3b9, + ])), + Fq::from_repr(BigInteger384([ + 0x2efbeddf9b5dc1b6, + 0x28d5ca5ad09f4fdb, + 0x7c4068238cdf674b, + 0x67f15f81dc49195b, + 0x9c8c9bd4b79fa83d, + 0x25a226f714d506e, + ])), + ) + ); +} + +#[test] +fn test_fq2_frobenius_map() { + let mut a = Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ); + a.frobenius_map(0); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ) + ); + a.frobenius_map(1); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x228109103250c9d0, + 0x8a411ad149045812, + 0xa9109e8f3041427e, + 0xb07e9bc405608611, + 0xfcd559cbe77bd8b8, + 0x18d400b280d93e62, + ])), + ) + ); + a.frobenius_map(1); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ) + ); + a.frobenius_map(2); + assert_eq!( + a, + Fq2::new( + Fq::from_repr(BigInteger384([ + 0x2d0078036923ffc7, + 0x11e59ea221a3b6d2, + 0x8b1a52e0a90f59ed, + 0xb966ce3bc2108b13, + 0xccc649c4b9532bf3, + 0xf8d295b2ded9dc, + ])), + Fq::from_repr(BigInteger384([ + 0x977df6efcdaee0db, + 0x946ae52d684fa7ed, + 0xbe203411c66fb3a5, + 0xb3f8afc0ee248cad, + 0x4e464dea5bcfd41e, + 0x12d1137b8a6a837, + ])), + ) + ); +} + +#[test] +fn test_fq2_legendre() { + use crate::fields::LegendreSymbol::*; + + assert_eq!(Zero, Fq2::zero().legendre()); + // i^2 = -1 + let mut m1 = -Fq2::one(); + assert_eq!(QuadraticResidue, m1.legendre()); + m1 = Fq6Parameters::mul_fp2_by_nonresidue(&m1); + assert_eq!(QuadraticNonResidue, m1.legendre()); +} + +#[test] +fn test_fq2_mul_nonresidue() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let nqr = Fq2::new(Fq::one(), Fq::one()); + + for _ in 0..1000 { + let mut a = Fq2::rand(&mut rng); + let mut b = a; + a = Fq6Parameters::mul_fp2_by_nonresidue(&a); + b.mul_assign(&nqr); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq6_mul_nonresidue() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let nqr = Fq6::new(Fq2::zero(), Fq2::one(), Fq2::zero()); + + for _ in 0..1000 { + let mut a = Fq6::rand(&mut rng); + let mut b = a; + a = Fq12::mul_fp6_by_nonresidue(&a); + b.mul_assign(&nqr); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq6_mul_by_1() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c1 = Fq2::rand(&mut rng); + let mut a = Fq6::rand(&mut rng); + let mut b = a; + + a.mul_by_1(&c1); + b.mul_assign(&Fq6::new(Fq2::zero(), c1, Fq2::zero())); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq6_mul_by_01() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c0 = Fq2::rand(&mut rng); + let c1 = Fq2::rand(&mut rng); + let mut a = Fq6::rand(&mut rng); + let mut b = a; + + a.mul_by_01(&c0, &c1); + b.mul_assign(&Fq6::new(c0, c1, Fq2::zero())); + + assert_eq!(a, b); + } +} + +#[test] +fn test_fq12_mul_by_014() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..1000 { + let c0 = Fq2::rand(&mut rng); + let c1 = Fq2::rand(&mut rng); + let c5 = Fq2::rand(&mut rng); + let mut a = Fq12::rand(&mut rng); + let mut b = a; + + a.mul_by_014(&c0, &c1, &c5); + b.mul_assign(&Fq12::new( + Fq6::new(c0, c1, Fq2::zero()), + Fq6::new(Fq2::zero(), c5, Fq2::zero()), + )); + + assert_eq!(a, b); + } +} diff --git a/algebra/src/fields/edwards_bls12/fq.rs b/algebra/src/fields/edwards_bls12/fq.rs new file mode 100644 index 000000000..e053865ab --- /dev/null +++ b/algebra/src/fields/edwards_bls12/fq.rs @@ -0,0 +1 @@ +pub use crate::fields::bls12_377::fr::{Fr as Fq, FrParameters as FqParameters}; diff --git a/algebra/src/fields/edwards_bls12/fr.rs b/algebra/src/fields/edwards_bls12/fr.rs new file mode 100644 index 000000000..3b39759ef --- /dev/null +++ b/algebra/src/fields/edwards_bls12/fr.rs @@ -0,0 +1,66 @@ +use crate::{ + biginteger::BigInteger256 as BigInteger, + fields::{Fp256, Fp256Parameters, FpParameters}, +}; + +pub type Fr = Fp256; + +pub struct FrParameters; + +impl Fp256Parameters for FrParameters {} +impl FpParameters for FrParameters { + type BigInt = BigInteger; + + // MODULUS = 2111115437357092606062206234695386632838870926408408195193685246394721360383 + const MODULUS: BigInteger = BigInteger([ + 13356249993388743167u64, + 5950279507993463550u64, + 10965441865914903552u64, + 336320092672043349u64, + ]); + + const MODULUS_BITS: u32 = 251; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 5; + + const R: BigInteger = BigInteger([ + 16632263305389933622u64, + 10726299895124897348u64, + 16608693673010411502u64, + 285459069419210737u64, + ]); + + const R2: BigInteger = BigInteger([ + 3987543627614508126u64, + 17742427666091596403u64, + 14557327917022607905u64, + 322810149704226881u64, + ]); + + const INV: u64 = 9659935179256617473u64; + + // 5 + const GENERATOR: BigInteger = BigInteger([ + 11289572479685143826u64, + 11383637369941080925u64, + 2288212753973340071u64, + 82014976407880291u64, + ]); + + const TWO_ADICITY: u32 = 1; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 15170730761708361161u64, + 13670723686578117817u64, + 12803492266614043665u64, + 50861023252832611u64, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); + + const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); + + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); +} diff --git a/algebra/src/fields/edwards_bls12/mod.rs b/algebra/src/fields/edwards_bls12/mod.rs new file mode 100644 index 000000000..54eaf49d7 --- /dev/null +++ b/algebra/src/fields/edwards_bls12/mod.rs @@ -0,0 +1,5 @@ +pub mod fq; +pub mod fr; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/edwards_bls12/tests.rs b/algebra/src/fields/edwards_bls12/tests.rs new file mode 100644 index 000000000..6ae2379ca --- /dev/null +++ b/algebra/src/fields/edwards_bls12/tests.rs @@ -0,0 +1,21 @@ +use crate::fields::tests::{field_test, primefield_test}; + +#[test] +fn test_edwards_bls12_fr() { + use crate::fields::edwards_bls12::fr::Fr; + + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + primefield_test::(); +} + +#[test] +fn test_edwards_bls12_fq() { + use crate::fields::edwards_bls12::fq::Fq; + + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + primefield_test::(); +} diff --git a/algebra/src/fields/edwards_sw6/fq.rs b/algebra/src/fields/edwards_sw6/fq.rs new file mode 100644 index 000000000..0a3048837 --- /dev/null +++ b/algebra/src/fields/edwards_sw6/fq.rs @@ -0,0 +1 @@ +pub use crate::fields::sw6::fr::{Fr as Fq, FrParameters as FqParameters}; diff --git a/algebra/src/fields/edwards_sw6/fr.rs b/algebra/src/fields/edwards_sw6/fr.rs new file mode 100644 index 000000000..ad7eda148 --- /dev/null +++ b/algebra/src/fields/edwards_sw6/fr.rs @@ -0,0 +1,76 @@ +use crate::{ + biginteger::BigInteger384 as BigInteger, + fields::{Fp384, Fp384Parameters, FpParameters}, +}; + +pub type Fr = Fp384; + +pub struct FrParameters; + +impl Fp384Parameters for FrParameters {} +impl FpParameters for FrParameters { + type BigInt = BigInteger; + + // MODULUS = 32333053251621136751331591711861691692049189094364332567435817881934511297123972799646723302813083835942624121493 + const MODULUS: BigInteger = BigInteger([ + 4684667634276979349u64, + 3748803659444032385u64, + 16273581227874629698u64, + 7152942431629910641u64, + 6397188139321141543u64, + 15137289088311837u64, + ]); + + const MODULUS_BITS: u32 = 374; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 10; + + const R: BigInteger = BigInteger([ + 12565484300600153878u64, + 8749673077137355528u64, + 9027943686469014788u64, + 13026065139386752555u64, + 11197589485989933721u64, + 9525964145733727u64, + ]); + + const R2: BigInteger = BigInteger([ + 17257035094703902127u64, + 16096159112880350050u64, + 3498553494623421763u64, + 333405339929360058u64, + 1125865524035793947u64, + 1586246138566285u64, + ]); + + const INV: u64 = 16242011933465909059u64; + + // 2 + const GENERATOR: BigInteger = BigInteger([ + 1999556893213776791u64, + 13750542494830678672u64, + 1782306145063399878u64, + 452443773434042853u64, + 15997990832658725900u64, + 3914639203155617u64, + ]); + + const TWO_ADICITY: u32 = 2u32; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 12119792640622387781u64, + 8318439284650634613u64, + 6931324077796168275u64, + 12851391603681523141u64, + 6881015057611215092u64, + 1893962574900431u64, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); + + const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); + + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); +} diff --git a/algebra/src/fields/edwards_sw6/mod.rs b/algebra/src/fields/edwards_sw6/mod.rs new file mode 100644 index 000000000..54eaf49d7 --- /dev/null +++ b/algebra/src/fields/edwards_sw6/mod.rs @@ -0,0 +1,5 @@ +pub mod fq; +pub mod fr; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/edwards_sw6/tests.rs b/algebra/src/fields/edwards_sw6/tests.rs new file mode 100644 index 000000000..375eddae4 --- /dev/null +++ b/algebra/src/fields/edwards_sw6/tests.rs @@ -0,0 +1,21 @@ +use crate::fields::tests::{field_test, primefield_test}; + +#[test] +fn test_edwards_sw6_fr() { + use crate::fields::edwards_sw6::fr::Fr; + + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + primefield_test::(); +} + +#[test] +fn test_edwards_sw6_fq() { + use crate::fields::edwards_sw6::fq::Fq; + + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + primefield_test::(); +} diff --git a/algebra/src/fields/jubjub/fq.rs b/algebra/src/fields/jubjub/fq.rs new file mode 100644 index 000000000..25aa19d72 --- /dev/null +++ b/algebra/src/fields/jubjub/fq.rs @@ -0,0 +1,87 @@ +use crate::{ + biginteger::BigInteger256 as BigInteger, + fields::{Fp256, Fp256Parameters, FpParameters}, +}; + +pub type Fq = Fp256; + +pub struct FqParameters; + +impl Fp256Parameters for FqParameters {} +impl FpParameters for FqParameters { + type BigInt = BigInteger; + + // MODULUS = 52435875175126190479447740508185965837690552500527637822603658699938581184513 + const MODULUS: BigInteger = BigInteger([ + 0xffffffff00000001, + 0x53bda402fffe5bfe, + 0x3339d80809a1d805, + 0x73eda753299d7d48, + ]); + + const MODULUS_BITS: u32 = 255; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 1; + + const R: BigInteger = BigInteger([ + 0x1fffffffe, + 0x5884b7fa00034802, + 0x998c4fefecbc4ff5, + 0x1824b159acc5056f, + ]); + + const R2: BigInteger = BigInteger([ + 0xc999e990f3f29c6d, + 0x2b6cedcb87925c23, + 0x5d314967254398f, + 0x748d9d99f59ff11, + ]); + + const INV: u64 = 0xfffffffeffffffff; + + // + const GENERATOR: BigInteger = BigInteger([ + 0xefffffff1, + 0x17e363d300189c0f, + 0xff9c57876f8457b0, + 0x351332208fc5a8c4, + ]); + + const TWO_ADICITY: u32 = 32; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0xb9b58d8c5f0e466a, + 0x5b1b4c801819d7ec, + 0xaf53ae352a31e64, + 0x5bf3adda19e9b27b, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x7fffffff80000000, + 0xa9ded2017fff2dff, + 0x199cec0404d0ec02, + 0x39f6d3a994cebea4, + ]); + + // T and T_MINUS_ONE_DIV_TWO, where MODULUS - 1 = 2^S * T + + // T = (MODULUS - 1) / 2^S = + // 12208678567578594777604504606729831043093128246378069236549469339647 + const T: BigInteger = BigInteger([ + 0xfffe5bfeffffffff, + 0x9a1d80553bda402, + 0x299d7d483339d808, + 0x73eda753, + ]); + + // (T - 1) / 2 = + // 6104339283789297388802252303364915521546564123189034618274734669823 + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x7fff2dff7fffffff, + 0x4d0ec02a9ded201, + 0x94cebea4199cec04, + 0x39f6d3a9, + ]); +} diff --git a/algebra/src/fields/jubjub/fr.rs b/algebra/src/fields/jubjub/fr.rs new file mode 100644 index 000000000..7af9903f5 --- /dev/null +++ b/algebra/src/fields/jubjub/fr.rs @@ -0,0 +1,65 @@ +use crate::{ + biginteger::BigInteger256 as BigInteger, + fields::{Fp256, Fp256Parameters, FpParameters}, +}; + +pub type Fr = Fp256; + +pub struct FrParameters; + +impl Fp256Parameters for FrParameters {} +impl FpParameters for FrParameters { + type BigInt = BigInteger; + + // MODULUS = 6554484396890773809930967563523245729705921265872317281365359162392183254199. + const MODULUS: BigInteger = BigInteger([ + 0xd0970e5ed6f72cb7, + 0xa6682093ccc81082, + 0x6673b0101343b00, + 0xe7db4ea6533afa9, + ]); + + const MODULUS_BITS: u32 = 252; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 4; + + const R: BigInteger = BigInteger([ + 0x25f80bb3b99607d9, + 0xf315d62f66b6e750, + 0x932514eeeb8814f4, + 0x9a6fc6f479155c6, + ]); + + const R2: BigInteger = BigInteger([ + 0x67719aa495e57731, + 0x51b0cef09ce3fc26, + 0x69dab7fac026e9a5, + 0x4f6547b8d127688, + ]); + + const INV: u64 = 0x1ba3a358ef788ef9; + + const GENERATOR: BigInteger = BigInteger([ + 0x720b1b19d49ea8f1, + 0xbf4aa36101f13a58, + 0x5fa8cc968193ccbb, + 0xe70cbdc7dccf3ac, + ]); + + const TWO_ADICITY: u32 = 1; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0xaa9f02ab1d6124de, + 0xb3524a6466112932, + 0x7342261215ac260b, + 0x4d6b87b1da259e2, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); + + const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); + + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); +} diff --git a/algebra/src/fields/jubjub/mod.rs b/algebra/src/fields/jubjub/mod.rs new file mode 100644 index 000000000..54eaf49d7 --- /dev/null +++ b/algebra/src/fields/jubjub/mod.rs @@ -0,0 +1,5 @@ +pub mod fq; +pub mod fr; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/jubjub/tests.rs b/algebra/src/fields/jubjub/tests.rs new file mode 100644 index 000000000..7212175a7 --- /dev/null +++ b/algebra/src/fields/jubjub/tests.rs @@ -0,0 +1,449 @@ +use crate::{ + biginteger::BigInteger256 as BigInteger, + bytes::{FromBytes, ToBytes}, + fields::{ + jubjub::{fq::Fq, fr::Fr}, + tests::{field_test, primefield_test}, + Field, + LegendreSymbol::*, + PrimeField, SquareRootField, + }, +}; +use std::str::FromStr; + +#[test] +fn test_jubjub_fr() { + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + primefield_test::(); +} + +#[test] +fn test_jubjub_fq() { + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + primefield_test::(); +} + +#[test] +fn test_fq_add() { + let f1 = Fq::from_str( + "18386742314266644595564329008376577163854043021652781768352795308532764650733", + ) + .unwrap(); + let f2 = Fq::from_str( + "39786307610986038981023499868190793548353538256264351797285876981647142458383", + ) + .unwrap(); + let f3 = Fq::from_str( + "5737174750126493097140088368381404874517028777389495743035013590241325924603", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f2.is_zero()); + assert!(!f3.is_zero()); + assert_eq!(f1 + &f2, f3); +} + +#[test] +fn test_fq_add_one() { + let f1 = Fq::from_str( + "4946875394261337176810256604189376311946643975348516311606738923340201185904", + ) + .unwrap(); + let f2 = Fq::from_str( + "4946875394261337176810256604189376311946643975348516311606738923340201185905", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f2.is_zero()); + assert_eq!(f1 + &Fq::one(), f2); +} + +#[test] +fn test_fq_mul() { + let f1 = Fq::from_str( + "24703123148064348394273033316595937198355721297494556079070134653139656190956", + ) + .unwrap(); + let f2 = Fq::from_str( + "38196797080882758914424853878212529985425118523754343117256179679117054302131", + ) + .unwrap(); + let f3 = Fq::from_str( + "38057113854472161555556064369220825628027487067886761874351491955834635348140", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f2.is_zero()); + assert!(!f3.is_zero()); + assert_eq!(f1 * &f2, f3); +} + +#[test] +fn test_fq_triple_mul() { + let f1 = Fq::from_str( + "23834398828139479510988224171342199299644042568628082836691700490363123893905", + ) + .unwrap(); + let f2 = Fq::from_str( + "48343809612844640454129919255697536258606705076971130519928764925719046689317", + ) + .unwrap(); + let f3 = Fq::from_str( + "22704845471524346880579660022678666462201713488283356385810726260959369106033", + ) + .unwrap(); + let f4 = Fq::from_str( + "18897508522635316277030308074760673440128491438505204942623624791502972539393", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f2.is_zero()); + assert!(!f3.is_zero()); + assert_eq!(f1 * &f2 * &f3, f4); +} + +#[test] +fn test_fq_div() { + let f1 = Fq::from_str( + "31892744363926593013886463524057935370302352424137349660481695792871889573091", + ) + .unwrap(); + let f2 = Fq::from_str( + "47695868328933459965610498875668250916462767196500056002116961816137113470902", + ) + .unwrap(); + let f3 = Fq::from_str( + "29049672724678710659792141917402891276693777283079976086581207190825261000580", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f2.is_zero()); + assert!(!f3.is_zero()); + assert_eq!(f1 / &f2, f3); +} + +#[test] +fn test_fq_sub() { + let f1 = Fq::from_str( + "18695869713129401390241150743745601908470616448391638969502807001833388904079", + ) + .unwrap(); + let f2 = Fq::from_str( + "10105476028534616828778879109836101003805485072436929139123765141153277007373", + ) + .unwrap(); + let f3 = Fq::from_str( + "8590393684594784561462271633909500904665131375954709830379041860680111896706", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f2.is_zero()); + assert!(!f3.is_zero()); + assert_eq!(f1 - &f2, f3); +} + +#[test] +fn test_fq_double_in_place() { + let mut f1 = Fq::from_str( + "29729289787452206300641229002276778748586801323231253291984198106063944136114", + ) + .unwrap(); + let f3 = Fq::from_str( + "7022704399778222121834717496367591659483050145934868761364737512189307087715", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f3.is_zero()); + f1.double_in_place(); + assert_eq!(f1, f3); +} + +#[test] +fn test_fq_double_in_place_thrice() { + let mut f1 = Fq::from_str( + "32768907806651393940832831055386272949401004221411141755415956893066040832473", + ) + .unwrap(); + let f3 = Fq::from_str( + "52407761752706389608871686410346320244445823769178582752913020344774001921732", + ) + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f3.is_zero()); + f1.double_in_place(); + f1.double_in_place(); + f1.double_in_place(); + assert_eq!(f1, f3); +} + +#[test] +fn test_fq_generate_random_jubjub_point() { + let d = Fq::from_str( + "19257038036680949359750312669786877991949435402254120286184196891950884077233", + ) + .unwrap(); + let y = Fq::from_str( + "20269054604167148422407276086932743904275456233139568486008667107872965128512", + ) + .unwrap(); + let x2 = Fq::from_str( + "35041048504708632193693740149219726446678304552734087046982753200179718192840", + ) + .unwrap(); + + let computed_y2 = y.square(); + let y2 = Fq::from_str( + "22730681238307918419349440108285755984465605552827817317611903495170775437833", + ) + .unwrap(); + assert_eq!(y2, computed_y2); + + let computed_dy2 = d * &computed_y2; + let dy2 = Fq::from_str( + "24720347560552809545835752815204882739669031262711919770503096707526812943411", + ) + .unwrap(); + assert_eq!(dy2, computed_dy2); + + let computed_divisor = computed_dy2 + &Fq::one(); + let divisor = Fq::from_str( + "24720347560552809545835752815204882739669031262711919770503096707526812943412", + ) + .unwrap(); + assert_eq!(divisor, computed_divisor); + + let computed_x2 = (computed_y2 - &Fq::one()) / &computed_divisor; + assert_eq!(x2, computed_x2); + + let x = Fq::from_str( + "15337652609730546173818014678723269532482775720866471265774032070871608223361", + ) + .unwrap(); + let computed_x = computed_x2.sqrt().unwrap(); + assert_eq!(computed_x.square(), x2); + assert_eq!(x, computed_x); + + fn add<'a>(curr: (Fq, Fq), other: &'a (Fq, Fq)) -> (Fq, Fq) { + let y1y2 = curr.1 * &other.1; + let x1x2 = curr.0 * &other.0; + let d = Fq::from_str( + "19257038036680949359750312669786877991949435402254120286184196891950884077233", + ) + .unwrap(); + let dx1x2y1y2 = d * &y1y2 * &x1x2; + + let d1 = Fq::one() + &dx1x2y1y2; + let d2 = Fq::one() - &dx1x2y1y2; + + let x1y2 = curr.0 * &other.1; + let y1x2 = curr.1 * &other.0; + + let x = (x1y2 + &y1x2) / &d1; + let y = (y1y2 + &x1x2) / &d2; + + (x, y) + } + + let result = add((x, y), &(x, y)); + let result = add(result, &result); + let result = add(result, &result); + + let point_x = Fq::from_str( + "47259664076168047050113154262636619161204477920503059672059915868534495873964", + ) + .unwrap(); + let point_y = Fq::from_str( + "19016409245280491801573912449420132838852726543024859389273314249842195919690", + ) + .unwrap(); + assert_eq!((point_x, point_y), result); +} + +#[test] +fn test_fq_square_in_place() { + let mut f1 = Fq::from_str( + "34864651240005695523200639428464570946052769938774601449735727714436878540682", + ) + .unwrap(); + let f3 = + Fq::from_str("213133100629336594719108316042277780359104840987226496279264105585804377948") + .unwrap(); + assert!(!f1.is_zero()); + assert!(!f3.is_zero()); + f1.square_in_place(); + assert_eq!(f1, f3); +} + +#[test] +fn test_fq_sqrt() { + let f1 = Fq::from_str( + "10875927553327821418567659853801220899541454800710193788767706167237535308235", + ) + .unwrap(); + let f3 = Fq::from_str( + "10816221372957505053219354782681292880545918527618367765651802809826238616708", + ) + .unwrap(); + assert_eq!(f1.sqrt().unwrap(), f3); +} + +#[test] +fn test_fq_from_str() { + let f1_from_repr = Fq::from_repr(BigInteger([ + 0xab8a2535947d1a77, + 0x9ba74cbfda0bbcda, + 0xe928b59724d60baf, + 0x1cccaaeb9bb1680a, + ])); + let f1 = Fq::from_str( + "13026376210409056429264774981357153555336288129100724591327877625017068755575", + ) + .unwrap(); + let f2_from_repr = Fq::from_repr(BigInteger([ + 0x97e9103775d2f35c, + 0xbe6756b6c587544b, + 0x6ee38c3afd88ef4b, + 0x2bacd150f540c677, + ])); + let f2 = Fq::from_str( + "19754794831832707859764530223239420866832328728734160755396495950822165902172", + ) + .unwrap(); + assert_eq!(f1_from_repr, f1); + assert_eq!(f2_from_repr, f2); +} + +#[test] +fn test_fq_legendre() { + assert_eq!(QuadraticResidue, Fq::one().legendre()); + assert_eq!(Zero, Fq::zero().legendre()); + + let e = BigInteger([ + 0x0dbc5349cd5664da, + 0x8ac5b6296e3ae29d, + 0x127cb819feceaa3b, + 0x3a6b21fb03867191, + ]); + assert_eq!(QuadraticResidue, Fq::from_repr(e).legendre()); + let e = BigInteger([ + 0x96341aefd047c045, + 0x9b5f4254500a4d65, + 0x1ee08223b68ac240, + 0x31d9cd545c0ec7c6, + ]); + assert_eq!(QuadraticNonResidue, Fq::from_repr(e).legendre()); +} + +#[test] +fn test_fq_bytes() { + let f1_from_repr = Fq::from_repr(BigInteger([ + 0xab8a2535947d1a77, + 0x9ba74cbfda0bbcda, + 0xe928b59724d60baf, + 0x1cccaaeb9bb1680a, + ])); + + let mut f1_bytes = [0u8; 32]; + f1_from_repr.write(f1_bytes.as_mut()).unwrap(); + + let f1 = Fq::read(f1_bytes.as_ref()).unwrap(); + assert_eq!(f1_from_repr, f1); +} + +#[test] +fn test_fr_add() { + let f1 = Fr::from_repr(BigInteger([ + 0xc81265fb4130fe0c, + 0xb308836c14e22279, + 0x699e887f96bff372, + 0x84ecc7e76c11ad, + ])); + let f2 = Fr::from_repr(BigInteger([ + 0x71875719b422efb8, + 0x43658e68a93612, + 0x9fa756be2011e833, + 0xaa2b2cb08dac497, + ])); + let f3 = Fr::from_repr(BigInteger([ + 0x3999bd14f553edc4, + 0xb34be8fa7d8b588c, + 0x945df3db6d1dba5, + 0xb279f92f046d645, + ])); + assert_eq!(f1 + &f2, f3); +} + +#[test] +fn test_fr_mul() { + let f1 = Fr::from_repr(BigInteger([ + 0xc81265fb4130fe0c, + 0xb308836c14e22279, + 0x699e887f96bff372, + 0x84ecc7e76c11ad, + ])); + let f2 = Fr::from_repr(BigInteger([ + 0x71875719b422efb8, + 0x43658e68a93612, + 0x9fa756be2011e833, + 0xaa2b2cb08dac497, + ])); + let f3 = Fr::from_repr(BigInteger([ + 0x6d6618ac6b4a8381, + 0x5b9eb35d711ee1da, + 0xce83310e6ac4105d, + 0x98032e0f206320a, + ])); + assert_eq!(f1 * &f2, f3); +} + +#[test] +fn test_fr_bytes() { + let f1_from_repr = Fr::from_repr(BigInteger([ + 0xc81265fb4130fe0c, + 0xb308836c14e22279, + 0x699e887f96bff372, + 0x84ecc7e76c11ad, + ])); + + let mut f1_bytes = [0u8; 32]; + f1_from_repr.write(f1_bytes.as_mut()).unwrap(); + + let f1 = Fr::read(f1_bytes.as_ref()).unwrap(); + assert_eq!(f1_from_repr, f1); +} + +#[test] +fn test_fr_from_str() { + let f100_from_repr = Fr::from_repr(BigInteger([0x64, 0, 0, 0])); + let f100 = Fr::from_str("100").unwrap(); + assert_eq!(f100_from_repr, f100); +} + +#[test] +#[ignore] +fn print_field() { + println!("one: {:?}", Fq::one()); + println!("zero: {:?}", Fq::zero()); + println!( + "256 in repr: {:?}", + Fq::from_repr(BigInteger([0, 0, 1, 255])) + ); + println!("256: {:?}", Fq::from_str("256").unwrap().into_repr()); + println!("1024: {:?}", Fq::from_str("1024").unwrap().into_repr()); + println!( + "255 to bytes: {:?}", + to_bytes![Fq::from_str("255").unwrap().into_repr()].unwrap() + ); + println!( + "256 to bytes: {:?}", + to_bytes![Fq::from_str("256").unwrap().into_repr()].unwrap() + ); + println!( + "1023 to bytes: {:?}", + to_bytes![Fq::from_str("1023").unwrap().into_repr()].unwrap() + ); +} diff --git a/algebra/src/fields/macros.rs b/algebra/src/fields/macros.rs new file mode 100644 index 000000000..a8f77c92d --- /dev/null +++ b/algebra/src/fields/macros.rs @@ -0,0 +1,66 @@ +macro_rules! impl_field_into_bigint { + ($field: ident, $bigint: ident, $params: ident) => { + impl Into<$bigint> for $field

{ + fn into(self) -> $bigint { + self.into_repr() + } + } + }; +} + +macro_rules! sqrt_impl { + ($Self:ident, $P:tt, $self:expr) => {{ + use crate::fields::LegendreSymbol::*; + // https://eprint.iacr.org/2012/685.pdf (page 12, algorithm 5) + // Actually this is just normal Tonelli-Shanks; since `P::Generator` + // is a quadratic non-residue, `P::ROOT_OF_UNITY = P::GENERATOR ^ t` + // is also a quadratic non-residue (since `t` is odd). + match $self.legendre() { + Zero => Some(*$self), + QuadraticNonResidue => None, + QuadraticResidue => { + let mut z = $Self::qnr_to_t(); + let mut w = $self.pow($P::T_MINUS_ONE_DIV_TWO); + let mut x = w * $self; + let mut b = x * &w; + + let mut v = $P::TWO_ADICITY as usize; + // t = self^t + #[cfg(debug_assertions)] + { + let mut check = b; + for _ in 0..(v - 1) { + check.square_in_place(); + } + if !check.is_one() { + panic!("Input is not a square root, but it passed the QR test") + } + } + + while !b.is_one() { + let mut k = 0usize; + + let mut b2k = b; + while !b2k.is_one() { + // invariant: b2k = b^(2^k) after entering this loop + b2k.square_in_place(); + k += 1; + } + + let j = v - k - 1; + w = z; + for _ in 0..j { + w.square_in_place(); + } + + z = w.square(); + b *= &z; + x *= &w; + v = k; + } + + Some(x) + }, + } + }}; +} diff --git a/algebra/src/fields/mnt6/fq.rs b/algebra/src/fields/mnt6/fq.rs new file mode 100644 index 000000000..e8843de2c --- /dev/null +++ b/algebra/src/fields/mnt6/fq.rs @@ -0,0 +1,90 @@ +use crate::{ + biginteger::BigInteger320 as BigInteger, + fields::{Fp320, Fp320Parameters, FpParameters}, +}; + +pub type Fq = Fp320; + +pub struct FqParameters; + +impl Fp320Parameters for FqParameters {} +impl FpParameters for FqParameters { + type BigInt = BigInteger; + + // MODULUS = 475922286169261325753349249653048451545124878552823515553267735739164647307408490559963137 + const MODULUS: BigInteger = BigInteger([ + 0xbb4334a400000001, + 0xfb494c07925d6ad3, + 0xcaeec9635cf44194, + 0xa266249da7b0548e, + 0x3bcf7bcd473, + ]); + + const MODULUS_BITS: u32 = 298; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 22; + + const R: BigInteger = BigInteger([ + 0xc3177aefffbb845c, + 0x9b80c702f9961788, + 0xc5df8dcdac70a85a, + 0x29184098647b5197, + 0x1c1223d33c3, + ]); + + const R2: BigInteger = BigInteger([ + 0x465a743c68e0596b, + 0x34f9102adb68371, + 0x4bbd6dcf1e3a8386, + 0x2ff00dced8e4b6d, + 0x149bb44a342, + ]); + + const INV: u64 = 0xbb4334a3ffffffff; + + const GENERATOR: BigInteger = BigInteger([ + 0xb1ddfacffd532b94, + 0x25e295ff76674008, + 0x8f00647b48958d36, + 0x1159f37d4e0fddb2, + 0x2977770b3d1, + ]); + + const TWO_ADICITY: u32 = 34; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0x818b361df1af7be4, + 0x2ae2750d46a53957, + 0x5784a8fe792c5f8a, + 0xf9bd39c0cdcf1bb6, + 0x6a24a0f8a8, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0xdda19a5200000000, + 0x7da4a603c92eb569, + 0x657764b1ae7a20ca, + 0xd133124ed3d82a47, + 0x1de7bde6a39, + ]); + + // T and T_MINUS_ONE_DIV_TWO, where MODULUS - 1 = 2^S * T + + const T: BigInteger = BigInteger([ + 0xe4975ab4eed0cd29, + 0xd73d10653ed25301, + 0x69ec1523b2bbb258, + 0x3def351ce8998927, + 0xef, + ]); + + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0xf24bad5a77686694, + 0x6b9e88329f692980, + 0xb4f60a91d95dd92c, + 0x9ef79a8e744cc493, + 0x77, + ]); +} diff --git a/algebra/src/fields/mnt6/fq3.rs b/algebra/src/fields/mnt6/fq3.rs new file mode 100644 index 000000000..b62c8b51e --- /dev/null +++ b/algebra/src/fields/mnt6/fq3.rs @@ -0,0 +1,102 @@ +use crate::{ + biginteger::BigInteger320 as BigInteger, + fields::{ + fp3::{Fp3, Fp3Parameters}, + mnt6::fq::Fq, + }, +}; + +pub type Fq3 = Fp3; + +pub struct Fq3Parameters; + +impl Fp3Parameters for Fq3Parameters { + type Fp = Fq; + + const NONRESIDUE: Fq = Fq::new(BigInteger([ + 0x58eefd67fea995ca, + 0x12f14affbb33a004, + 0x4780323da44ac69b, + 0x88acf9bea707eed9, + 0x14bbbb859e8, + ])); + + const TWO_ADICITY: u32 = 34; + + const T_MINUS_ONE_DIV_TWO: &'static [u64] = &[ + 0x69232b75663933bd, + 0xca650efcfc00ee0, + 0x77ca3963fe36f720, + 0xe4cb46632f9bcf7e, + 0xef510453f08f9f30, + 0x9dd5b8fc72f02d83, + 0x7f8d017ed86608ab, + 0xeb2219b3697c97a4, + 0xc8663846ab96996f, + 0x833cd532053eac7d, + 0x1d5b73dfb20bd3cc, + 0x6f5f6da606b59873, + 0x62e990f43dfc42d6, + 0x6878f58, + ]; + + const QUADRATIC_NONRESIDUE_TO_T: (Fq, Fq, Fq) = ( + Fq::new(BigInteger([ + 0x44a4178610a3a4e6, + 0x49321e4d00f35073, + 0xbbc01b9c400c07a1, + 0xd0127c4589095738, + 0x3730de2a45d, + ])), + Fq::new(BigInteger([0, 0, 0, 0, 0])), + Fq::new(BigInteger([0, 0, 0, 0, 0])), + ); + + const FROBENIUS_COEFF_FP3_C1: [Fq; 3] = [ + Fq::new(BigInteger([ + 0xc3177aefffbb845c, + 0x9b80c702f9961788, + 0xc5df8dcdac70a85a, + 0x29184098647b5197, + 0x1c1223d33c3, + ])), + Fq::new(BigInteger([ + 0x1c17bb7477085b6a, + 0x2621629c22e83dbb, + 0x21c062106d949dd8, + 0x9d5b981062164ba, + 0x84ad703207, + ])), + Fq::new(BigInteger([ + 0xdc13fe3f893c203b, + 0x39a7226875df158f, + 0xe34ed98542eefb62, + 0x6f782a843d139e3c, + 0x177280f6ea9, + ])), + ]; + + const FROBENIUS_COEFF_FP3_C2: [Fq; 3] = [ + Fq::new(BigInteger([ + 0xc3177aefffbb845c, + 0x9b80c702f9961788, + 0xc5df8dcdac70a85a, + 0x29184098647b5197, + 0x1c1223d33c3, + ])), + Fq::new(BigInteger([ + 0xdc13fe3f893c203b, + 0x39a7226875df158f, + 0xe34ed98542eefb62, + 0x6f782a843d139e3c, + 0x177280f6ea9, + ])), + Fq::new(BigInteger([ + 0x1c17bb7477085b6a, + 0x2621629c22e83dbb, + 0x21c062106d949dd8, + 0x9d5b981062164ba, + 0x84ad703207, + ])), + ]; +} diff --git a/algebra/src/fields/mnt6/fq6.rs b/algebra/src/fields/mnt6/fq6.rs new file mode 100644 index 000000000..27bc39e0f --- /dev/null +++ b/algebra/src/fields/mnt6/fq6.rs @@ -0,0 +1,75 @@ +use crate::{ + biginteger::BigInteger320 as BigInteger, + fields::{ + fp6_2over3::{Fp6, Fp6Parameters}, + mnt6::{ + fq::Fq, + fq3::{Fq3, Fq3Parameters}, + }, + }, +}; + +pub type Fq6 = Fp6; + +pub struct Fq6Parameters; + +impl Fp6Parameters for Fq6Parameters { + type Fp3Params = Fq3Parameters; + + const NONRESIDUE: Fq3 = Fq3::new( + Fq::new(BigInteger([ + 6408337942890780106, + 1364954624287809540, + 5152173214042605211, + 9848521082393849561, + 1424783596008, + ])), + Fq::new(BigInteger([0, 0, 0, 0, 0])), + Fq::new(BigInteger([0, 0, 0, 0, 0])), + ); + + const FROBENIUS_COEFF_FP6_C1: [Fq; 6] = [ + Fq::new(BigInteger([ + 0xc3177aefffbb845c, + 0x9b80c702f9961788, + 0xc5df8dcdac70a85a, + 0x29184098647b5197, + 0x1c1223d33c3, + ])), + Fq::new(BigInteger([ + 0xdf2f366476c3dfc6, + 0xc1a2299f1c7e5543, + 0xe79fefde1a054632, + 0x32edfa196a9cb651, + 0x245cfad65ca, + ])), + Fq::new(BigInteger([ + 0x1c17bb7477085b6a, + 0x2621629c22e83dbb, + 0x21c062106d949dd8, + 0x9d5b981062164ba, + 0x84ad703207, + ])), + Fq::new(BigInteger([ + 0xf82bb9b400447ba5, + 0x5fc8850498c7534a, + 0x50f3b95b083993a, + 0x794de405433502f7, + 0x1fbd57fa0b0, + ])), + Fq::new(BigInteger([ + 0xdc13fe3f893c203b, + 0x39a7226875df158f, + 0xe34ed98542eefb62, + 0x6f782a843d139e3c, + 0x177280f6ea9, + ])), + Fq::new(BigInteger([ + 0x9f2b792f88f7a497, + 0xd527e96b6f752d18, + 0xa92e6752ef5fa3bc, + 0x98906b1ca18eefd4, + 0x3384a4ca26c, + ])), + ]; +} diff --git a/algebra/src/fields/mnt6/fr.rs b/algebra/src/fields/mnt6/fr.rs new file mode 100644 index 000000000..611a24fbf --- /dev/null +++ b/algebra/src/fields/mnt6/fr.rs @@ -0,0 +1,88 @@ +use crate::{ + biginteger::BigInteger320 as BigInteger, + fields::{Fp320, Fp320Parameters, FpParameters}, +}; + +pub type Fr = Fp320; + +pub struct FrParameters; + +impl Fp320Parameters for FrParameters {} +impl FpParameters for FrParameters { + type BigInt = BigInteger; + + // MODULUS = 475922286169261325753349249653048451545124879242694725395555128576210262817955800483758081 + const MODULUS: BigInteger = BigInteger([ + 14487189785281953793u64, + 4731562877756902930u64, + 14622846468719063274u64, + 11702080941310629006u64, + 4110145082483u64, + ]); + + const MODULUS_BITS: u32 = 298; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 22; + + const R: BigInteger = BigInteger([ + 1784298994435064924u64, + 16852041090100268533u64, + 14258261760832875328u64, + 2961187778261111191u64, + 1929014752195u64, + ]); + + const R2: BigInteger = BigInteger([ + 28619103704175136u64, + 11702218449377544339u64, + 7403203599591297249u64, + 2248105543421449339u64, + 2357678148148u64, + ]); + + const INV: u64 = 12714121028002250751u64; + + const GENERATOR: BigInteger = BigInteger([ + 2709730703260633621u64, + 13556085429182073539u64, + 10903316137158576359u64, + 5319113788683590444u64, + 4022235209932u64, + ]); + + const TWO_ADICITY: u32 = 17; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 9821480371597472441u64, + 9468346035609379175u64, + 9963748368231707135u64, + 14865337659602750405u64, + 3984815592673u64, + ]); + + const T: BigInteger = BigInteger([ + 0x70964866b2d38b3, + 0x987520d4f1af2890, + 0x2a47657764b1ae89, + 0x6a39d133124ed3d8, + 0x1de7bde, + ]); + + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x384b24335969c59, + 0xcc3a906a78d79448, + 0x1523b2bbb258d744, + 0x351ce899892769ec, + 0xef3def, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x64866b2d38b30000, + 0x20d4f1af28900709, + 0x657764b1ae899875, + 0xd133124ed3d82a47, + 0x1de7bde6a39, + ]); +} diff --git a/algebra/src/fields/mnt6/mod.rs b/algebra/src/fields/mnt6/mod.rs new file mode 100644 index 000000000..7bfd333df --- /dev/null +++ b/algebra/src/fields/mnt6/mod.rs @@ -0,0 +1,14 @@ +pub mod fr; +pub use self::fr::*; + +pub mod fq; +pub use self::fq::*; + +pub mod fq3; +pub use self::fq3::*; + +pub mod fq6; +pub use self::fq6::*; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/mnt6/tests.rs b/algebra/src/fields/mnt6/tests.rs new file mode 100644 index 000000000..9e7f75e7c --- /dev/null +++ b/algebra/src/fields/mnt6/tests.rs @@ -0,0 +1,50 @@ +use crate::fields::tests::{field_test, frobenius_test, primefield_test, sqrt_field_test}; + +#[test] +fn test_mnt6_fr() { + use crate::fields::mnt6::Fr; + + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + sqrt_field_test(a); + primefield_test::(); +} + +#[test] +fn test_mnt6_fq() { + use crate::fields::mnt6::Fq; + + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + sqrt_field_test(a); + primefield_test::(); +} + +#[test] +fn test_mnt6_fq3() { + use crate::fields::{ + mnt6::{Fq, Fq3}, + PrimeField, + }; + + let a: Fq3 = rand::random(); + let b: Fq3 = rand::random(); + field_test(a, b); + sqrt_field_test(a); + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_mnt6_fq6() { + use crate::fields::{ + mnt6::{Fq, Fq6}, + PrimeField, + }; + + let a: Fq6 = rand::random(); + let b: Fq6 = rand::random(); + field_test(a, b); + frobenius_test::(Fq::characteristic().0, 13); +} diff --git a/algebra/src/fields/mod.rs b/algebra/src/fields/mod.rs new file mode 100644 index 000000000..f41c78e7e --- /dev/null +++ b/algebra/src/fields/mod.rs @@ -0,0 +1,329 @@ +use crate::{ + biginteger::BigInteger, + bytes::{FromBytes, ToBytes}, +}; +use rand::Rand; +use std::{ + fmt::{Debug, Display}, + hash::Hash, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +#[macro_use] +mod macros; + +pub mod bls12_377; +pub mod bls12_381; +pub mod edwards_bls12; +pub mod edwards_sw6; +pub mod jubjub; +pub mod mnt6; +pub mod models; +pub mod sw6; +#[cfg(test)] +pub mod tests; + +pub use self::models::*; + +/// The interface for a generic field. +pub trait Field: + ToBytes + + FromBytes + + Copy + + Clone + + Debug + + Display + + Default + + Send + + Sync + + 'static + + Eq + + Ord + + Neg + + Rand + + Sized + + Hash + + for<'a> Add<&'a Self, Output = Self> + + for<'a> Sub<&'a Self, Output = Self> + + for<'a> Mul<&'a Self, Output = Self> + + for<'a> Div<&'a Self, Output = Self> + + for<'a> AddAssign<&'a Self> + + for<'a> SubAssign<&'a Self> + + for<'a> MulAssign<&'a Self> + + for<'a> DivAssign<&'a Self> +{ + /// Returns the zero element of the field, the additive identity. + fn zero() -> Self; + + /// Returns true if and only if `self == Self::zero()`. + fn is_zero(&self) -> bool; + + /// Returns the one element of the field, a field generator. + fn one() -> Self; + + /// Returns true if and only if `self == Self::one()`. + fn is_one(&self) -> bool; + + /// Returns the characteristic of the field. + fn characteristic<'a>() -> &'a [u64]; + + /// Returns `self + self`. + #[must_use] + fn double(&self) -> Self; + + /// Doubles `self` in place. + fn double_in_place(&mut self) -> &mut Self; + + /// Returns `self * self`. + #[must_use] + fn square(&self) -> Self; + + /// Squares `self` in place. + fn square_in_place(&mut self) -> &mut Self; + + /// Computes the multiplicative inverse of `self` if `self` is nonzero. + #[must_use] + fn inverse(&self) -> Option; + + // Sets `self` to `self`'s inverse if it exists. Otherwise it is a no-op. + fn inverse_in_place(&mut self) -> Option<&mut Self>; + + /// Exponentiates this element by a power of the base prime modulus via + /// the Frobenius automorphism. + fn frobenius_map(&mut self, power: usize); + + /// Exponentiates this element by a number represented with `u64` limbs, + /// least significant limb first. + fn pow>(&self, exp: S) -> Self { + let mut res = Self::one(); + + let mut found_one = false; + + for i in BitIterator::new(exp) { + if !found_one { + if i { + found_one = true; + } else { + continue; + } + } + + res.square_in_place(); + + if i { + res *= self; + } + } + res + } +} + +/// A trait that defines parameters for a prime field. +pub trait FpParameters: 'static + Send + Sync + Sized { + type BigInt: BigInteger; + + /// The modulus of the field. + const MODULUS: Self::BigInt; + + /// The number of bits needed to represent the `Self::MODULUS`. + const MODULUS_BITS: u32; + + /// The number of bits that must be shaved from the beginning of + /// the representation when randomly sampling. + const REPR_SHAVE_BITS: u32; + + /// R = 2^256 % Self::MODULUS + const R: Self::BigInt; + + /// R2 = R^2 % Self::MODULUS + const R2: Self::BigInt; + + /// INV = -(MODULUS^{-1} mod MODULUS) mod MODULUS + const INV: u64; + + /// A multiplicative generator that is also a quadratic nonresidue. + /// `Self::GENERATOR` is an element having multiplicative order + /// `Self::MODULUS - 1`. + /// There also does not exist `x` such that `Self::GENERATOR = x^2 % + /// Self::MODULUS` + const GENERATOR: Self::BigInt; + + /// The number of bits that can be reliably stored. + /// (Should equal `SELF::MODULUS_BITS - 1`) + const CAPACITY: u32; + + /// 2^s * t = MODULUS - 1 with t odd. This is the two-adicity of the prime. + const TWO_ADICITY: u32; + + /// 2^s root of unity computed by GENERATOR^t + const ROOT_OF_UNITY: Self::BigInt; + + /// t for 2^s * t = MODULUS - 1 + const T: Self::BigInt; + + /// (t - 1) / 2 + const T_MINUS_ONE_DIV_TWO: Self::BigInt; + + /// (Self::MODULUS - 1) / 2 + const MODULUS_MINUS_ONE_DIV_TWO: Self::BigInt; +} + +/// The interface for a prime field. +pub trait PrimeField: Field + FromStr { + type Params: FpParameters; + type BigInt: BigInteger; + + /// Returns a prime field element from its underlying representation. + fn from_repr(repr: ::BigInt) -> Self; + + /// Returns the underlying representation of the prime field element. + fn into_repr(&self) -> Self::BigInt; + + /// Returns a prime field element from its underlying raw representation. + fn from_repr_raw(repr: Self::BigInt) -> Self; + + /// Returns the underlying raw representation of the prime field element. + fn into_repr_raw(&self) -> Self::BigInt; + + /// Returns a field element if the set of bytes forms a valid field element, + /// otherwise returns None. + fn from_random_bytes(bytes: &[u8]) -> Option; + + /// Returns the multiplicative generator of `char()` - 1 order. + fn multiplicative_generator() -> Self; + + /// Returns the 2^s root of unity. + fn root_of_unity() -> Self; + + /// Return the a QNR^T + fn qnr_to_t() -> Self { + Self::root_of_unity() + } + + /// Returns the field size in bits. + fn size_in_bits() -> usize { + Self::Params::MODULUS_BITS as usize + } + + /// Returns the trace. + fn trace() -> Self::BigInt { + Self::Params::T + } + + /// Returns the trace minus one divided by two. + fn trace_minus_one_div_two() -> Self::BigInt { + Self::Params::T_MINUS_ONE_DIV_TWO + } + + /// Returns the modulus minus one divided by two. + fn modulus_minus_one_div_two() -> Self::BigInt { + Self::Params::MODULUS_MINUS_ONE_DIV_TWO + } +} + +/// The interface for a field that supports an efficient square-root operation. +pub trait SquareRootField: Field { + /// Returns the Legendre symbol. + fn legendre(&self) -> LegendreSymbol; + + /// Returns the square root of self, if it exists. + #[must_use] + fn sqrt(&self) -> Option; + + /// Sets `self` to be the square root of `self`, if it exists. + fn sqrt_in_place(&mut self) -> Option<&mut Self>; +} + +#[derive(Debug, PartialEq)] +pub enum LegendreSymbol { + Zero = 0, + QuadraticResidue = 1, + QuadraticNonResidue = -1, +} + +impl LegendreSymbol { + pub fn is_zero(&self) -> bool { + *self == LegendreSymbol::Zero + } + + pub fn is_qnr(&self) -> bool { + *self == LegendreSymbol::QuadraticNonResidue + } + + pub fn is_qr(&self) -> bool { + *self == LegendreSymbol::QuadraticResidue + } +} + +#[derive(Debug)] +pub struct BitIterator { + t: E, + n: usize, +} + +impl> BitIterator { + pub fn new(t: E) -> Self { + let n = t.as_ref().len() * 64; + + BitIterator { t, n } + } +} + +impl> Iterator for BitIterator { + type Item = bool; + + fn next(&mut self) -> Option { + if self.n == 0 { + None + } else { + self.n -= 1; + let part = self.n / 64; + let bit = self.n - (64 * part); + + Some(self.t.as_ref()[part] & (1 << bit) > 0) + } + } +} + +use crate::biginteger::{ + BigInteger256, BigInteger320, BigInteger384, BigInteger768, BigInteger832, +}; + +impl_field_into_bigint!(Fp256, BigInteger256, Fp256Parameters); +impl_field_into_bigint!(Fp320, BigInteger320, Fp320Parameters); +impl_field_into_bigint!(Fp384, BigInteger384, Fp384Parameters); +impl_field_into_bigint!(Fp768, BigInteger768, Fp768Parameters); +impl_field_into_bigint!(Fp832, BigInteger832, Fp832Parameters); + +pub fn batch_inversion(v: &mut [F]) { + // Montgomery’s Trick and Fast Implementation of Masked AES + // Genelle, Prouff and Quisquater + // Section 3.2 + + // First pass: compute [a, ab, abc, ...] + let mut prod = Vec::with_capacity(v.len()); + let mut tmp = F::one(); + for f in v.iter().filter(|f| !f.is_zero()) { + tmp.mul_assign(&f); + prod.push(tmp); + } + + // Invert `tmp`. + tmp = tmp.inverse().unwrap(); // Guaranteed to be nonzero. + + // Second pass: iterate backwards to compute inverses + for (f, s) in v.iter_mut() + // Backwards + .rev() + // Ignore normalized elements + .filter(|f| !f.is_zero()) + // Backwards, skip last element, fill in one for last term. + .zip(prod.into_iter().rev().skip(1).chain(Some(F::one()))) + { + // tmp := tmp * g.z; g.z := tmp * s = 1/z + let newtmp = tmp * &f; + *f = tmp * &s; + tmp = newtmp; + } +} diff --git a/algebra/src/fields/models/fp12_2over3over2.rs b/algebra/src/fields/models/fp12_2over3over2.rs new file mode 100644 index 000000000..f28231330 --- /dev/null +++ b/algebra/src/fields/models/fp12_2over3over2.rs @@ -0,0 +1,450 @@ +use rand::{Rand, Rng}; +use std::{ + cmp::Ordering, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::{fp6_3over2::*, Field, Fp2, Fp2Parameters}, + BitIterator, +}; + +pub trait Fp12Parameters: 'static + Send + Sync + Copy { + type Fp6Params: Fp6Parameters; + + /// Coefficients for the Frobenius automorphism. + const FROBENIUS_COEFF_FP12_C1: [Fp2>; 12]; +} + +/// An element of Fp12, represented by c0 + c1 * v +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp12Parameters"), + Hash(bound = "P: Fp12Parameters"), + Clone(bound = "P: Fp12Parameters"), + Copy(bound = "P: Fp12Parameters"), + Debug(bound = "P: Fp12Parameters"), + PartialEq(bound = "P: Fp12Parameters"), + Eq(bound = "P: Fp12Parameters") +)] +pub struct Fp12 { + pub c0: Fp6, + pub c1: Fp6, + #[derivative(Debug = "ignore")] + pub params: PhantomData

, +} + +type Fp2Params

= <

::Fp6Params as Fp6Parameters>::Fp2Params; + +impl Fp12

{ + /// Multiply by quadratic nonresidue v. + #[inline(always)] + pub(crate) fn mul_fp6_by_nonresidue(fe: &Fp6) -> Fp6 { + let new_c0 = P::Fp6Params::mul_fp2_by_nonresidue(&fe.c2); + let new_c1 = fe.c0; + let new_c2 = fe.c1; + Fp6::new(new_c0, new_c1, new_c2) + } + + pub const fn new(c0: Fp6, c1: Fp6) -> Self { + Self { + c0, + c1, + params: PhantomData, + } + } + + pub fn mul_by_fp( + &mut self, + element: &<::Fp2Params as Fp2Parameters>::Fp, + ) { + self.c0.mul_by_fp(&element); + self.c1.mul_by_fp(&element); + } + + pub fn conjugate(&mut self) { + self.c1 = self.c1.neg(); + } + + pub fn mul_by_034( + &mut self, + c0: &Fp2>, + c3: &Fp2>, + c4: &Fp2>, + ) { + let a0 = self.c0.c0 * c0; + let a1 = self.c0.c1 * c0; + let a2 = self.c0.c2 * c0; + let a = Fp6::new(a0, a1, a2); + let mut b = self.c1; + b.mul_by_01(&c3, &c4); + + let c0 = *c0 + c3; + let c1 = c4; + let mut e = self.c0 + &self.c1; + e.mul_by_01(&c0, &c1); + self.c1 = e - &(a + &b); + self.c0 = a + &Self::mul_fp6_by_nonresidue(&b); + } + + pub fn mul_by_014( + &mut self, + c0: &Fp2>, + c1: &Fp2>, + c4: &Fp2>, + ) { + let mut aa = self.c0; + aa.mul_by_01(c0, c1); + let mut bb = self.c1; + bb.mul_by_1(c4); + let mut o = *c1; + o.add_assign(c4); + self.c1.add_assign(&self.c0); + self.c1.mul_by_01(c0, &o); + self.c1.sub_assign(&aa); + self.c1.sub_assign(&bb); + self.c0 = bb; + self.c0 = Self::mul_fp6_by_nonresidue(&self.c0); + self.c0.add_assign(&aa); + } + + pub fn cyclotomic_square(&self) -> Self { + let mut result = Self::zero(); + let fp2_nr = ::mul_fp2_by_nonresidue; + + let mut z0 = self.c0.c0; + let mut z4 = self.c0.c1; + let mut z3 = self.c0.c2; + let mut z2 = self.c1.c0; + let mut z1 = self.c1.c1; + let mut z5 = self.c1.c2; + + // t0 + t1*y = (z0 + z1*y)^2 = a^2 + let mut tmp = z0 * &z1; + let t0 = (z0 + &z1) * &(z0 + &fp2_nr(&z1)) - &tmp - &fp2_nr(&tmp); + let t1 = tmp.double(); + + // t2 + t3*y = (z2 + z3*y)^2 = b^2 + tmp = z2 * &z3; + let t2 = (z2 + &z3) * &(z2 + &fp2_nr(&z3)) - &tmp - &fp2_nr(&tmp); + let t3 = tmp.double(); + + // t4 + t5*y = (z4 + z5*y)^2 = c^2 + tmp = z4 * &z5; + let t4 = (z4 + &z5) * &(z4 + &fp2_nr(&z5)) - &tmp - &fp2_nr(&tmp); + let t5 = tmp.double(); + + // for A + + // z0 = 3 * t0 - 2 * z0 + z0 = t0 - &z0; + z0 = z0 + &z0; + result.c0.c0 = z0 + &t0; + + // z1 = 3 * t1 + 2 * z1 + z1 = t1 + &z1; + z1 = z1 + &z1; + result.c1.c1 = z1 + &t1; + + // for B + + // z2 = 3 * (xi * t5) + 2 * z2 + tmp = fp2_nr(&t5); + z2 = tmp + &z2; + z2 = z2 + &z2; + result.c1.c0 = z2 + &tmp; + + // z3 = 3 * t4 - 2 * z3 + z3 = t4 - &z3; + z3 = z3 + &z3; + result.c0.c2 = z3 + &t4; + + // for C + + // z4 = 3 * t2 - 2 * z4 + z4 = t2 - &z4; + z4 = z4 + &z4; + result.c0.c1 = z4 + &t2; + + // z5 = 3 * t3 + 2 * z5 + z5 = t3 + &z5; + z5 = z5 + &z5; + result.c1.c2 = z5 + &t3; + + result + } + + pub fn cyclotomic_exp>(&self, exp: S) -> Self { + let mut res = Self::one(); + + let mut found_one = false; + + for i in BitIterator::new(exp) { + if !found_one { + if i { + found_one = true; + } else { + continue; + } + } + + res = res.cyclotomic_square(); + + if i { + res *= self; + } + } + res + } +} + +impl std::fmt::Display for Fp12

{ + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + write!(f, "Fp12({} + {} * w)", self.c0, self.c1) + } +} + +impl Rand for Fp12

{ + fn rand(rng: &mut R) -> Self { + Fp12::new(rng.gen(), rng.gen()) + } +} + +impl Field for Fp12

{ + fn zero() -> Self { + Self::new(Fp6::zero(), Fp6::zero()) + } + + fn one() -> Self { + Self::new(Fp6::one(), Fp6::zero()) + } + + fn is_zero(&self) -> bool { + self.c0.is_zero() && self.c1.is_zero() + } + + fn is_one(&self) -> bool { + self.c0.is_one() && self.c1.is_zero() + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + Fp6::::characteristic() + } + + fn double(&self) -> Self { + let mut copy = *self; + copy.double_in_place(); + copy + } + + fn double_in_place(&mut self) -> &mut Self { + self.c0.double_in_place(); + self.c1.double_in_place(); + self + } + fn frobenius_map(&mut self, power: usize) { + self.c0.frobenius_map(power); + self.c1.frobenius_map(power); + + self.c1 + .c0 + .mul_assign(&P::FROBENIUS_COEFF_FP12_C1[power % 12]); + self.c1 + .c1 + .mul_assign(&P::FROBENIUS_COEFF_FP12_C1[power % 12]); + self.c1 + .c2 + .mul_assign(&P::FROBENIUS_COEFF_FP12_C1[power % 12]); + } + + fn square(&self) -> Self { + let mut copy = *self; + copy.square_in_place(); + copy + } + + fn square_in_place(&mut self) -> &mut Self { + let mut ab = self.c0; + ab.mul_assign(&self.c1); + let mut c0c1 = self.c0; + c0c1.add_assign(&self.c1); + let mut c0 = self.c1; + c0 = Self::mul_fp6_by_nonresidue(&c0); + c0.add_assign(&self.c0); + c0.mul_assign(&c0c1); + c0.sub_assign(&ab); + self.c1 = ab; + self.c1.add_assign(&ab); + ab = Self::mul_fp6_by_nonresidue(&ab); + c0.sub_assign(&ab); + self.c0 = c0; + self + } + + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + let mut c0s = self.c0; + c0s.square_in_place(); + let mut c1s = self.c1; + c1s.square_in_place(); + c1s = Self::mul_fp6_by_nonresidue(&c1s); + c0s.sub_assign(&c1s); + + c0s.inverse().map(|t| { + let mut tmp = Fp12::new(t, t); + tmp.c0.mul_assign(&self.c0); + tmp.c1.mul_assign(&self.c1); + tmp.c1 = -tmp.c1; + + tmp + }) + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + match self.inverse() { + Some(inv) => { + *self = inv; + Some(self) + }, + None => None, + } + } +} + +impl Neg for Fp12

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + let mut copy = Self::zero(); + copy.c0 = self.c0.neg(); + copy.c1 = self.c1.neg(); + copy + } +} + +impl<'a, P: Fp12Parameters> Add<&'a Self> for Fp12

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self; + result.add_assign(&other); + result + } +} + +impl<'a, P: Fp12Parameters> Sub<&'a Self> for Fp12

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self; + result.sub_assign(&other); + result + } +} + +impl<'a, P: Fp12Parameters> Mul<&'a Self> for Fp12

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other); + result + } +} + +impl<'a, P: Fp12Parameters> Div<&'a Self> for Fp12

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp12Parameters> AddAssign<&'a Self> for Fp12

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + self.c0.add_assign(&other.c0); + self.c1.add_assign(&other.c1); + } +} + +impl<'a, P: Fp12Parameters> SubAssign<&'a Self> for Fp12

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + self.c0.sub_assign(&other.c0); + self.c1.sub_assign(&other.c1); + } +} + +impl<'a, P: Fp12Parameters> MulAssign<&'a Self> for Fp12

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let v0 = self.c0 * &other.c0; + let v1 = self.c1 * &other.c1; + self.c1 = (self.c0 + &self.c1) * &(other.c0 + &other.c1) - &v0 - &v1; + self.c0 = v0 + &Self::mul_fp6_by_nonresidue(&v1); + } +} + +impl<'a, P: Fp12Parameters> DivAssign<&'a Self> for Fp12

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} + +impl<'a, P: Fp12Parameters> From<&'a [bool]> for Fp12

{ + fn from(_bits: &[bool]) -> Self { + unimplemented!() + } +} + +impl Ord for Fp12

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + let c1_cmp = self.c1.cmp(&other.c1); + if c1_cmp == Ordering::Equal { + self.c0.cmp(&other.c0) + } else { + c1_cmp + } + } +} + +impl PartialOrd for Fp12

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp12

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.c0.write(&mut writer)?; + self.c1.write(&mut writer) + } +} + +impl FromBytes for Fp12

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let c0 = Fp6::read(&mut reader)?; + let c1 = Fp6::read(&mut reader)?; + Ok(Fp12::new(c0, c1)) + } +} diff --git a/algebra/src/fields/models/fp2.rs b/algebra/src/fields/models/fp2.rs new file mode 100644 index 000000000..fbc3faa7c --- /dev/null +++ b/algebra/src/fields/models/fp2.rs @@ -0,0 +1,346 @@ +use rand::{Rand, Rng}; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::{Field, LegendreSymbol, PrimeField, SquareRootField}, +}; + +pub trait Fp2Parameters: 'static + Send + Sync { + type Fp: PrimeField + SquareRootField; + + const NONRESIDUE: Self::Fp; + + const QUADRATIC_NONRESIDUE: (Self::Fp, Self::Fp); + + /// Coefficients for the Frobenius automorphism. + const FROBENIUS_COEFF_FP2_C1: [Self::Fp; 2]; + + #[inline(always)] + fn mul_fp_by_nonresidue(fe: &Self::Fp) -> Self::Fp { + Self::NONRESIDUE * fe + } +} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp2Parameters"), + Hash(bound = "P: Fp2Parameters"), + Clone(bound = "P: Fp2Parameters"), + Copy(bound = "P: Fp2Parameters"), + Debug(bound = "P: Fp2Parameters"), + PartialEq(bound = "P: Fp2Parameters"), + Eq(bound = "P: Fp2Parameters") +)] +pub struct Fp2 { + pub c0: P::Fp, + pub c1: P::Fp, + #[derivative(Debug = "ignore")] + _parameters: PhantomData

, +} + +impl Fp2

{ + pub const fn new(c0: P::Fp, c1: P::Fp) -> Self { + Fp2 { + c0, + c1, + _parameters: PhantomData, + } + } + + /// Norm of Fp2 over Fp: Norm(a) = a.x^2 - beta * a.y^2 + pub fn norm(&self) -> P::Fp { + let t0 = self.c0.square(); + let mut t1 = self.c1.square(); + t1 = -P::mul_fp_by_nonresidue(&t1); + t1.add_assign(&t0); + t1 + } + + pub fn mul_by_fp(&mut self, element: &P::Fp) { + self.c0.mul_assign(&element); + self.c1.mul_assign(&element); + } +} + +impl Field for Fp2

{ + fn zero() -> Self { + Fp2::new(P::Fp::zero(), P::Fp::zero()) + } + + fn is_zero(&self) -> bool { + self.c0.is_zero() && self.c1.is_zero() + } + + fn one() -> Self { + Fp2::new(P::Fp::one(), P::Fp::zero()) + } + + fn is_one(&self) -> bool { + self.c0.is_one() && self.c1.is_zero() + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::Fp::characteristic() + } + + fn double(&self) -> Self { + let mut result = self.clone(); + result.double_in_place(); + result + } + + fn double_in_place(&mut self) -> &mut Self { + self.c0.double_in_place(); + self.c1.double_in_place(); + self + } + + fn square(&self) -> Self { + let mut result = *self; + result.square_in_place(); + result + } + + fn square_in_place(&mut self) -> &mut Self { + // v0 = c0 - c1 + let mut v0 = self.c0 - &self.c1; + // v3 = c0 - beta * c1 + let v3 = self.c0 - &P::mul_fp_by_nonresidue(&self.c1); + // v2 = c0 * c1 + let v2 = self.c0 * &self.c1; + + // v0 = (v0 * v3) + v2 + v0 *= &v3; + v0 += &v2; + + self.c1 = v2.double(); + self.c0 = v0 + &P::mul_fp_by_nonresidue(&v2); + + self + } + + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // Guide to Pairing-based Cryptography, Algorithm 5.19. + // v0 = c0.square() + let mut v0 = self.c0.square(); + // v1 = c1.square() + let v1 = self.c1.square(); + // v0 = v0 - beta * v1 + v0 -= &P::mul_fp_by_nonresidue(&v1); + v0.inverse().map(|v1| { + let c0 = self.c0 * &v1; + let c1 = -(self.c1 * &v1); + Self::new(c0, c1) + }) + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + fn frobenius_map(&mut self, power: usize) { + self.c1.mul_assign(&P::FROBENIUS_COEFF_FP2_C1[power % 2]); + } +} + +impl<'a, P: Fp2Parameters> SquareRootField for Fp2

{ + fn legendre(&self) -> LegendreSymbol { + self.norm().legendre() + } + + fn sqrt(&self) -> Option { + use crate::LegendreSymbol::*; + if self.c1.is_zero() { + return self.c0.sqrt().map(|c0| Self::new(c0, P::Fp::zero())); + } + match self.legendre() { + // Square root based on the complex method. See + // https://eprint.iacr.org/2012/685.pdf (page 15, algorithm 8) + Zero => Some(*self), + QuadraticNonResidue => None, + QuadraticResidue => { + let two_inv = P::Fp::one() + .double() + .inverse() + .expect("Two should always have an inverse"); + let alpha = self + .norm() + .sqrt() + .expect("We are in the QR case, the norm should have a square root"); + let mut delta = (alpha + &self.c0) * &two_inv; + if delta.legendre().is_qnr() { + delta -= α + } + let c0 = delta.sqrt().expect("Delta must have a square root"); + let c0_inv = c0.inverse().expect("c0 must have an inverse"); + Some(Self::new(c0, self.c1 * &two_inv * &c0_inv)) + }, + } + } + + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + (*self).sqrt().map(|sqrt| { + *self = sqrt; + self + }) + } +} + +/// `Fp2` elements are ordered lexicographically. +impl Ord for Fp2

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + match self.c1.cmp(&other.c1) { + Ordering::Greater => Ordering::Greater, + Ordering::Less => Ordering::Less, + Ordering::Equal => self.c0.cmp(&other.c0), + } + } +} + +impl PartialOrd for Fp2

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp2

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.c0.write(&mut writer)?; + self.c1.write(writer) + } +} + +impl FromBytes for Fp2

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let c0 = P::Fp::read(&mut reader)?; + let c1 = P::Fp::read(reader)?; + Ok(Fp2::new(c0, c1)) + } +} + +impl Neg for Fp2

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + let mut res = self.clone(); + res.c0 = res.c0.neg(); + res.c1 = res.c1.neg(); + res + } +} + +impl Rand for Fp2

{ + fn rand(rng: &mut R) -> Self { + Fp2::new(rng.gen(), rng.gen()) + } +} + +impl<'a, P: Fp2Parameters> Add<&'a Fp2

> for Fp2

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self; + result.add_assign(&other); + result + } +} + +impl<'a, P: Fp2Parameters> Sub<&'a Fp2

> for Fp2

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self; + result.sub_assign(&other); + result + } +} + +impl<'a, P: Fp2Parameters> Mul<&'a Fp2

> for Fp2

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other); + result + } +} + +impl<'a, P: Fp2Parameters> Div<&'a Fp2

> for Fp2

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp2Parameters> AddAssign<&'a Self> for Fp2

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + self.c0.add_assign(&other.c0); + self.c1.add_assign(&other.c1); + } +} + +impl<'a, P: Fp2Parameters> SubAssign<&'a Self> for Fp2

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + self.c0.sub_assign(&other.c0); + self.c1.sub_assign(&other.c1); + } +} + +impl<'a, P: Fp2Parameters> MulAssign<&'a Self> for Fp2

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + // Karatsuba multiplication; + // Guide to Pairing-based cryprography, Algorithm 5.16. + let v0 = self.c0 * &other.c0; + let v1 = self.c1 * &other.c1; + + self.c1 += &self.c0; + self.c1 *= &(other.c0 + &other.c1); + self.c1 -= &v0; + self.c1 -= &v1; + self.c0 = v0 + &P::mul_fp_by_nonresidue(&v1); + } +} + +impl<'a, P: Fp2Parameters> DivAssign<&'a Self> for Fp2

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} + +impl std::fmt::Display for Fp2

{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Fp2({} + {} * u)", self.c0, self.c1) + } +} diff --git a/algebra/src/fields/models/fp3.rs b/algebra/src/fields/models/fp3.rs new file mode 100644 index 000000000..5def0f3f1 --- /dev/null +++ b/algebra/src/fields/models/fp3.rs @@ -0,0 +1,454 @@ +use rand::{Rand, Rng}; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::{Field, LegendreSymbol, PrimeField, SquareRootField}, +}; + +pub trait Fp3Parameters: 'static + Send + Sync { + type Fp: PrimeField + SquareRootField; + + const NONRESIDUE: Self::Fp; + const FROBENIUS_COEFF_FP3_C1: [Self::Fp; 3]; + const FROBENIUS_COEFF_FP3_C2: [Self::Fp; 3]; + /// p^3 - 1 = 2^s * t, where t is odd. + const TWO_ADICITY: u32; + const T_MINUS_ONE_DIV_TWO: &'static [u64]; + /// t-th power of a quadratic nonresidue in Fp3. + const QUADRATIC_NONRESIDUE_TO_T: (Self::Fp, Self::Fp, Self::Fp); + + #[inline(always)] + fn mul_fp_by_nonresidue(fe: &Self::Fp) -> Self::Fp { + Self::NONRESIDUE * fe + } +} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp3Parameters"), + Hash(bound = "P: Fp3Parameters"), + Clone(bound = "P: Fp3Parameters"), + Copy(bound = "P: Fp3Parameters"), + Debug(bound = "P: Fp3Parameters"), + PartialEq(bound = "P: Fp3Parameters"), + Eq(bound = "P: Fp3Parameters") +)] +pub struct Fp3 { + pub c0: P::Fp, + pub c1: P::Fp, + pub c2: P::Fp, + #[derivative(Debug = "ignore")] + _parameters: PhantomData

, +} + +impl Fp3

{ + pub const fn new(c0: P::Fp, c1: P::Fp, c2: P::Fp) -> Self { + Fp3 { + c0, + c1, + c2, + _parameters: PhantomData, + } + } + + pub fn mul_assign_by_fp(&mut self, value: &P::Fp) { + self.c0.mul_assign(value); + self.c1.mul_assign(value); + self.c2.mul_assign(value); + } + + // Calculate the norm of an element with respect to the base field Fp. + pub fn norm(&self) -> P::Fp { + let mut self_to_p = *self; + self_to_p.frobenius_map(1); + let mut self_to_p2 = *self; + self_to_p2.frobenius_map(2); + self_to_p *= &(self_to_p2 * self); + assert!(self_to_p.c1.is_zero() && self_to_p.c2.is_zero()); + self_to_p.c0 + } + + // Returns the value of QNR^T. + #[inline] + pub const fn qnr_to_t() -> Self { + Self::new( + P::QUADRATIC_NONRESIDUE_TO_T.0, + P::QUADRATIC_NONRESIDUE_TO_T.1, + P::QUADRATIC_NONRESIDUE_TO_T.2, + ) + } +} + +impl Field for Fp3

{ + fn zero() -> Self { + Fp3 { + c0: P::Fp::zero(), + c1: P::Fp::zero(), + c2: P::Fp::zero(), + _parameters: PhantomData, + } + } + + fn is_zero(&self) -> bool { + self.c0.is_zero() && self.c1.is_zero() && self.c2.is_zero() + } + + fn one() -> Self { + Fp3 { + c0: P::Fp::one(), + c1: P::Fp::zero(), + c2: P::Fp::zero(), + _parameters: PhantomData, + } + } + + fn is_one(&self) -> bool { + self.c0.is_one() && self.c1.is_zero() && self.c2.is_zero() + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::Fp::characteristic() + } + + fn double(&self) -> Self { + let mut result = self.clone(); + result.double_in_place(); + result + } + + fn double_in_place(&mut self) -> &mut Self { + self.c0.double_in_place(); + self.c1.double_in_place(); + self.c2.double_in_place(); + self + } + + fn square(&self) -> Self { + let mut result = self.clone(); + result.square_in_place(); + result + } + + fn square_in_place(&mut self) -> &mut Self { + // Devegili OhEig Scott Dahab --- Multiplication and Squaring on + // AbstractPairing-Friendly + // Fields.pdf; Section 4 (CH-SQR2) + let a = self.c0.clone(); + let b = self.c1.clone(); + let c = self.c2.clone(); + + let s0 = a.square(); + let ab = a * &b; + let s1 = ab + &ab; + let s2 = (a - &b + &c).square(); + let bc = b * &c; + let s3 = bc + &bc; + let s4 = c.square(); + + self.c0 = s0 + &P::mul_fp_by_nonresidue(&s3); + self.c1 = s1 + &P::mul_fp_by_nonresidue(&s4); + self.c2 = s1 + &s2 + &s3 - &s0 - &s4; + self + } + + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // From "High-Speed Software Implementation of the Optimal Ate AbstractPairing + // over + // Barreto-Naehrig Curves"; Algorithm 17 + let t0 = self.c0.square(); + let t1 = self.c1.square(); + let t2 = self.c2.square(); + let mut t3 = self.c0.clone(); + t3.mul_assign(&self.c1); + let mut t4 = self.c0.clone(); + t4.mul_assign(&self.c2); + let mut t5 = self.c1.clone(); + t5.mul_assign(&self.c2); + let n5 = P::mul_fp_by_nonresidue(&t5); + + let mut s0 = t0.clone(); + s0.sub_assign(&n5); + let mut s1 = P::mul_fp_by_nonresidue(&t2); + s1.sub_assign(&t3); + let mut s2 = t1.clone(); + s2.sub_assign(&t4); // typo in paper referenced above. should be "-" as per Scott, but is "*" + + let mut a1 = self.c2.clone(); + a1.mul_assign(&s1); + let mut a2 = self.c1.clone(); + a2.mul_assign(&s2); + let mut a3 = a1.clone(); + a3.add_assign(&a2); + a3 = P::mul_fp_by_nonresidue(&a3); + let mut t6 = self.c0.clone(); + t6.mul_assign(&s0); + t6.add_assign(&a3); + t6.inverse_in_place(); + + let mut c0 = t6.clone(); + c0.mul_assign(&s0); + let mut c1 = t6.clone(); + c1.mul_assign(&s1); + let mut c2 = t6.clone(); + c2.mul_assign(&s2); + + Some(Self::new(c0, c1, c2)) + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + fn frobenius_map(&mut self, power: usize) { + self.c1.mul_assign(&P::FROBENIUS_COEFF_FP3_C1[power % 3]); + self.c2.mul_assign(&P::FROBENIUS_COEFF_FP3_C2[power % 3]); + } +} + +impl SquareRootField for Fp3

{ + /// Returns the Legendre symbol. + fn legendre(&self) -> LegendreSymbol { + self.norm().legendre() + } + + /// Returns the square root of self, if it exists. + fn sqrt(&self) -> Option { + sqrt_impl!(Self, P, self) + } + + /// Sets `self` to be the square root of `self`, if it exists. + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + (*self).sqrt().map(|sqrt| { + *self = sqrt; + self + }) + } +} + +/// `Fp3` elements are ordered lexicographically. +impl Ord for Fp3

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + let c2_cmp = self.c2.cmp(&other.c2); + let c1_cmp = self.c1.cmp(&other.c1); + let c0_cmp = self.c0.cmp(&other.c0); + if c2_cmp == Ordering::Equal { + if c1_cmp == Ordering::Equal { + c0_cmp + } else { + c1_cmp + } + } else { + c2_cmp + } + } +} + +impl PartialOrd for Fp3

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp3

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.c0.write(&mut writer)?; + self.c1.write(&mut writer)?; + self.c2.write(writer) + } +} + +impl FromBytes for Fp3

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let c0 = P::Fp::read(&mut reader)?; + let c1 = P::Fp::read(&mut reader)?; + let c2 = P::Fp::read(reader)?; + Ok(Fp3::new(c0, c1, c2)) + } +} + +impl Neg for Fp3

{ + type Output = Self; + #[inline] + fn neg(self) -> Self { + let mut res = self.clone(); + res.c0 = res.c0.neg(); + res.c1 = res.c1.neg(); + res.c2 = res.c2.neg(); + res + } +} + +impl Rand for Fp3

{ + fn rand(rng: &mut R) -> Self { + Fp3 { + c0: rng.gen(), + c1: rng.gen(), + c2: rng.gen(), + _parameters: PhantomData, + } + } +} + +impl<'a, P: Fp3Parameters> Add<&'a Fp3

> for Fp3

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self; + result.add_assign(&other); + result + } +} + +impl<'a, P: Fp3Parameters> Sub<&'a Fp3

> for Fp3

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self; + result.sub_assign(&other); + result + } +} + +impl<'a, P: Fp3Parameters> Mul<&'a Fp3

> for Fp3

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other); + result + } +} + +impl<'a, P: Fp3Parameters> Div<&'a Fp3

> for Fp3

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp3Parameters> AddAssign<&'a Self> for Fp3

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + self.c0.add_assign(&other.c0); + self.c1.add_assign(&other.c1); + self.c2.add_assign(&other.c2); + } +} + +impl<'a, P: Fp3Parameters> SubAssign<&'a Self> for Fp3

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + self.c0.sub_assign(&other.c0); + self.c1.sub_assign(&other.c1); + self.c2.sub_assign(&other.c2); + } +} + +impl<'a, P: Fp3Parameters> MulAssign<&'a Self> for Fp3

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + // Devegili OhEig Scott Dahab --- Multiplication and Squaring on + // AbstractPairing-Friendly + // Fields.pdf; Section 4 (Karatsuba) + + let a = other.c0; + let b = other.c1; + let c = other.c2; + + let d = self.c0; + let e = self.c1; + let f = self.c2; + + let ad = d * &a; + let be = e * &b; + let cf = f * &c; + + let x = (e + &f) * &(b + &c) - &be - &cf; + let y = (d + &e) * &(a + &b) - &ad - &be; + let z = (d + &f) * &(a + &c) - &ad + &be - &cf; + + self.c0 = ad + &P::mul_fp_by_nonresidue(&x); + self.c1 = y + &P::mul_fp_by_nonresidue(&cf); + self.c2 = z; + } +} + +impl<'a, P: Fp3Parameters> DivAssign<&'a Self> for Fp3

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} + +impl<'a, P: Fp3Parameters> From<&'a [bool]> for Fp3

{ + fn from(_bits: &[bool]) -> Self { + unimplemented!() + } +} + +impl FromStr for Fp3

{ + type Err = (); + + fn from_str(mut s: &str) -> Result { + s = s.trim(); + if s.is_empty() { + println!("is empty"); + return Err(()); + } + if s.len() < 3 { + println!("len is less than 3"); + return Err(()); + } + if !(s.starts_with('[') && s.ends_with(']')) { + println!("doesn't start and end with square brackets"); + return Err(()); + } + let mut point = Vec::new(); + for substr in s.split(|c| c == '[' || c == ']' || c == ',' || c == ' ') { + if !substr.is_empty() { + let coord = P::Fp::from_str(substr).map_err(|_| ())?; + point.push(coord); + } + } + if point.len() != 3 { + println!("not enough points"); + return Err(()); + } + let point = Fp3::new(point[0], point[1], point[2]); + Ok(point) + } +} + +impl ::std::fmt::Display for Fp3

{ + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + write!(f, "Fp3({}, {}, {})", self.c0, self.c1, self.c2) + } +} diff --git a/algebra/src/fields/models/fp6_2over3.rs b/algebra/src/fields/models/fp6_2over3.rs new file mode 100644 index 000000000..4d6ddaa05 --- /dev/null +++ b/algebra/src/fields/models/fp6_2over3.rs @@ -0,0 +1,359 @@ +use rand::{Rand, Rng}; +use std::{ + cmp::Ordering, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; + +use crate::{ + biginteger::BigInteger, + bytes::{FromBytes, ToBytes}, + fields::{Field, Fp3, Fp3Parameters}, +}; + +pub trait Fp6Parameters: 'static + Send + Sync { + type Fp3Params: Fp3Parameters; + + const NONRESIDUE: Fp3; + + /// Coefficients for the Frobenius automorphism. + const FROBENIUS_COEFF_FP6_C1: [::Fp; 6]; + + #[inline(always)] + fn mul_fp3_by_nonresidue(fe: &Fp3) -> Fp3 { + Self::NONRESIDUE * fe + } +} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp6Parameters"), + Hash(bound = "P: Fp6Parameters"), + Clone(bound = "P: Fp6Parameters"), + Copy(bound = "P: Fp6Parameters"), + Debug(bound = "P: Fp6Parameters"), + PartialEq(bound = "P: Fp6Parameters"), + Eq(bound = "P: Fp6Parameters") +)] +pub struct Fp6 { + pub c0: Fp3, + pub c1: Fp3, + #[derivative(Debug = "ignore")] + _parameters: PhantomData

, +} + +impl Fp6

{ + pub fn new(c0: Fp3, c1: Fp3) -> Self { + Fp6 { + c0, + c1, + _parameters: PhantomData, + } + } + + /// Multiply by quadratic nonresidue v. + pub fn mul_by_nonresidue(value: &Fp3) -> Fp3 { + let mut res = *value; + res.c0 = value.c2; + res.c1 = value.c0; + res.c2 = value.c1; + res.c0 + .mul_assign(&::NONRESIDUE); + res + } + + pub fn unitary_inverse(&self) -> Self { + Self::new(self.c0, -self.c1) + } + + pub fn cyclotomic_exp(&self, exponent: &B) -> Self { + let mut res = Self::one(); + let self_inverse = self.unitary_inverse(); + + let mut found_nonzero = false; + let naf = exponent.find_wnaf(); + + for &value in naf.iter().rev() { + if found_nonzero { + res = res.square(); + } + + if value != 0 { + found_nonzero = true; + + if value > 0 { + res = res * self; + } else { + res = res * &self_inverse; + } + } + } + + res + } +} + +impl Field for Fp6

{ + fn zero() -> Self { + Fp6 { + c0: Fp3::zero(), + c1: Fp3::zero(), + _parameters: PhantomData, + } + } + + fn is_zero(&self) -> bool { + self.c0.is_zero() && self.c1.is_zero() + } + + fn one() -> Self { + Fp6 { + c0: Fp3::one(), + c1: Fp3::zero(), + _parameters: PhantomData, + } + } + + fn is_one(&self) -> bool { + self.c0.is_one() && self.c1.is_zero() + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + Fp3::::characteristic() + } + + fn double(&self) -> Self { + let mut result = *self; + result.double_in_place(); + result + } + + fn double_in_place(&mut self) -> &mut Self { + self.c0.double_in_place(); + self.c1.double_in_place(); + self + } + + fn square(&self) -> Self { + let mut result = *self; + result.square_in_place(); + result + } + + fn square_in_place(&mut self) -> &mut Self { + // Devegili OhEig Scott Dahab --- Multiplication and Squaring on + // Pairing-Friendly + // Fields.pdf; Section 3 (Complex) + let a = self.c0; + let mut b = self.c1; + let ab_add = a + &b; + let mut ab_mul = a * &b; + + let c0 = ab_add * &(a + &Self::mul_by_nonresidue(&mut b)) + - &ab_mul + - &Self::mul_by_nonresidue(&mut ab_mul); + let c1 = ab_mul.double(); + + self.c0 = c0; + self.c1 = c1; + self + } + + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // From "High-Speed Software Implementation of the Optimal Ate Pairing over + // Barreto-Naehrig + // Curves"; Algorithm 8 + let a = self.c0; + let b = self.c1; + + let mut t1 = b.square(); + let t0 = a.square() - &Self::mul_by_nonresidue(&mut t1); + let t2 = t0.inverse().unwrap(); + + let c0 = a * &t2; + let c1 = (b * &t2).neg(); + + Some(Self::new(c0, c1)) + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + fn frobenius_map(&mut self, power: usize) { + self.c0.frobenius_map(power); + self.c1.frobenius_map(power); + self.c1 + .mul_assign_by_fp(&P::FROBENIUS_COEFF_FP6_C1[power % 6]); + } +} + +/// `Fp6` elements are ordered lexicographically. +impl Ord for Fp6

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + let c1_cmp = self.c1.cmp(&other.c1); + if c1_cmp == Ordering::Equal { + self.c0.cmp(&other.c0) + } else { + c1_cmp + } + } +} + +impl PartialOrd for Fp6

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp6

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.c0.write(&mut writer)?; + self.c1.write(&mut writer) + } +} + +impl FromBytes for Fp6

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let c0 = Fp3::read(&mut reader)?; + let c1 = Fp3::read(&mut reader)?; + Ok(Fp6::new(c0, c1)) + } +} + +impl Neg for Fp6

{ + type Output = Self; + #[inline] + fn neg(mut self) -> Self { + self.c0 = self.c0.neg(); + self.c1 = self.c1.neg(); + self + } +} + +impl Rand for Fp6

{ + fn rand(rng: &mut R) -> Self { + Fp6 { + c0: rng.gen(), + c1: rng.gen(), + _parameters: PhantomData, + } + } +} + +impl<'a, P: Fp6Parameters> Add<&'a Fp6

> for Fp6

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self; + result.add_assign(&other); + result + } +} + +impl<'a, P: Fp6Parameters> Sub<&'a Fp6

> for Fp6

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self; + result.sub_assign(&other); + result + } +} + +impl<'a, P: Fp6Parameters> Mul<&'a Fp6

> for Fp6

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other); + result + } +} + +impl<'a, P: Fp6Parameters> Div<&'a Fp6

> for Fp6

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp6Parameters> AddAssign<&'a Self> for Fp6

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + self.c0.add_assign(&other.c0); + self.c1.add_assign(&other.c1); + } +} + +impl<'a, P: Fp6Parameters> SubAssign<&'a Self> for Fp6

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + self.c0.sub_assign(&other.c0); + self.c1.sub_assign(&other.c1); + } +} + +impl<'a, P: Fp6Parameters> MulAssign<&'a Self> for Fp6

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + // Devegili OhEig Scott Dahab --- Multiplication and Squaring on + // Pairing-Friendly + // Fields.pdf; Section 3 (Karatsuba) + let a0 = self.c0; + let b0 = self.c1; + let a1 = other.c0; + let b1 = other.c1; + + let a0a1 = a0 * &a1; + let mut b0b1 = b0 * &b1; + let beta_b0b1 = Self::mul_by_nonresidue(&mut b0b1); + + let c0 = a0a1 + &beta_b0b1; + let c1 = (a0 + &b0) * &(a1 + &b1) - &a0a1 - &b0b1; + + self.c0 = c0; + self.c1 = c1; + } +} + +impl<'a, P: Fp6Parameters> DivAssign<&'a Self> for Fp6

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} + +impl<'a, P: Fp6Parameters> From<&'a [bool]> for Fp6

{ + fn from(_bits: &[bool]) -> Self { + unimplemented!() + } +} + +impl ::std::fmt::Display for Fp6

{ + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + write!(f, "Fp6_2over3({}, {})", self.c0, self.c1) + } +} diff --git a/algebra/src/fields/models/fp6_3over2.rs b/algebra/src/fields/models/fp6_3over2.rs new file mode 100644 index 000000000..ba43803a3 --- /dev/null +++ b/algebra/src/fields/models/fp6_3over2.rs @@ -0,0 +1,429 @@ +use rand::{Rand, Rng}; +use std::{ + cmp::Ordering, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::{Field, Fp2, Fp2Parameters}, +}; + +pub trait Fp6Parameters: 'static + Send + Sync + Copy { + type Fp2Params: Fp2Parameters; + + const NONRESIDUE: Fp2; + + /// Coefficients for the Frobenius automorphism. + const FROBENIUS_COEFF_FP6_C1: [Fp2; 6]; + const FROBENIUS_COEFF_FP6_C2: [Fp2; 6]; + + #[inline(always)] + fn mul_fp2_by_nonresidue(fe: &Fp2) -> Fp2 { + Self::NONRESIDUE * fe + } +} + +/// An element of Fp6, represented by c0 + c1 * v + c2 * v^(2). +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp6Parameters"), + Hash(bound = "P: Fp6Parameters"), + Clone(bound = "P: Fp6Parameters"), + Copy(bound = "P: Fp6Parameters"), + Debug(bound = "P: Fp6Parameters"), + PartialEq(bound = "P: Fp6Parameters"), + Eq(bound = "P: Fp6Parameters") +)] +pub struct Fp6 { + pub c0: Fp2, + pub c1: Fp2, + pub c2: Fp2, + #[derivative(Debug = "ignore")] + pub params: PhantomData

, +} + +impl Fp6

{ + pub const fn new(c0: Fp2, c1: Fp2, c2: Fp2) -> Self { + Self { + c0, + c1, + c2, + params: PhantomData, + } + } + + pub fn mul_by_fp(&mut self, element: &::Fp) { + self.c0.mul_by_fp(&element); + self.c1.mul_by_fp(&element); + self.c2.mul_by_fp(&element); + } + + pub fn mul_by_fp2(&mut self, element: &Fp2) { + self.c0.mul_assign(&element); + self.c1.mul_assign(&element); + self.c2.mul_assign(&element); + } + + pub fn mul_by_1(&mut self, c1: &Fp2) { + let mut b_b = self.c1; + b_b.mul_assign(c1); + + let mut t1 = *c1; + { + let mut tmp = self.c1; + tmp.add_assign(&self.c2); + + t1.mul_assign(&tmp); + t1.sub_assign(&b_b); + t1 = P::mul_fp2_by_nonresidue(&t1); + } + + let mut t2 = *c1; + { + let mut tmp = self.c0; + tmp.add_assign(&self.c1); + + t2.mul_assign(&tmp); + t2.sub_assign(&b_b); + } + + self.c0 = t1; + self.c1 = t2; + self.c2 = b_b; + } + + pub fn mul_by_01(&mut self, c0: &Fp2, c1: &Fp2) { + let mut a_a = self.c0; + let mut b_b = self.c1; + a_a.mul_assign(c0); + b_b.mul_assign(c1); + + let mut t1 = *c1; + { + let mut tmp = self.c1; + tmp.add_assign(&self.c2); + + t1.mul_assign(&tmp); + t1.sub_assign(&b_b); + t1 = P::mul_fp2_by_nonresidue(&t1); + t1.add_assign(&a_a); + } + + let mut t3 = *c0; + { + let mut tmp = self.c0; + tmp.add_assign(&self.c2); + + t3.mul_assign(&tmp); + t3.sub_assign(&a_a); + t3.add_assign(&b_b); + } + + let mut t2 = *c0; + t2.add_assign(c1); + { + let mut tmp = self.c0; + tmp.add_assign(&self.c1); + + t2.mul_assign(&tmp); + t2.sub_assign(&a_a); + t2.sub_assign(&b_b); + } + + self.c0 = t1; + self.c1 = t2; + self.c2 = t3; + } +} + +impl Field for Fp6

{ + fn zero() -> Self { + Self::new(Fp2::zero(), Fp2::zero(), Fp2::zero()) + } + + fn is_zero(&self) -> bool { + self.c0.is_zero() && self.c1.is_zero() && self.c2.is_zero() + } + + fn one() -> Self { + Self::new(Fp2::one(), Fp2::zero(), Fp2::zero()) + } + + fn is_one(&self) -> bool { + self.c0.is_one() && self.c1.is_zero() && self.c2.is_zero() + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + Fp2::::characteristic() + } + + fn double(&self) -> Self { + let mut result = self.clone(); + result.double_in_place(); + result + } + + fn double_in_place(&mut self) -> &mut Self { + self.c0.double_in_place(); + self.c1.double_in_place(); + self.c2.double_in_place(); + self + } + + fn square(&self) -> Self { + let mut result = self.clone(); + result.square_in_place(); + result + } + + fn square_in_place(&mut self) -> &mut Self { + let s0 = self.c0.square(); + let s1 = (self.c0 * &self.c1).double(); + let s2 = (self.c0 - &self.c1 + &self.c2).square(); + let s3 = (self.c1 * &self.c2).double(); + let s4 = self.c2.square(); + + self.c0 = s0 + &P::mul_fp2_by_nonresidue(&s3); + self.c1 = s1 + &P::mul_fp2_by_nonresidue(&s4); + self.c2 = s1 + &s2 + &s3 - &s0 - &s4; + + self + } + + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + let mut c0 = self.c2; + c0 = P::mul_fp2_by_nonresidue(&c0); + c0.mul_assign(&self.c1); + c0 = c0.neg(); + { + let mut c0s = self.c0; + c0s.square_in_place(); + c0.add_assign(&c0s); + } + let mut c1 = self.c2; + c1.square_in_place(); + c1 = P::mul_fp2_by_nonresidue(&c1); + { + let mut c01 = self.c0; + c01.mul_assign(&self.c1); + c1.sub_assign(&c01); + } + let mut c2 = self.c1; + c2.square_in_place(); + { + let mut c02 = self.c0; + c02.mul_assign(&self.c2); + c2.sub_assign(&c02); + } + + let mut tmp1 = self.c2; + tmp1.mul_assign(&c1); + let mut tmp2 = self.c1; + tmp2.mul_assign(&c2); + tmp1.add_assign(&tmp2); + tmp1 = P::mul_fp2_by_nonresidue(&tmp1); + tmp2 = self.c0; + tmp2.mul_assign(&c0); + tmp1.add_assign(&tmp2); + + match tmp1.inverse() { + Some(t) => Some(Self::new(t * &c0, t * &c1, t * &c2)), + None => None, + } + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + fn frobenius_map(&mut self, power: usize) { + self.c0.frobenius_map(power); + self.c1.frobenius_map(power); + self.c2.frobenius_map(power); + + self.c1.mul_assign(&P::FROBENIUS_COEFF_FP6_C1[power % 6]); + self.c2.mul_assign(&P::FROBENIUS_COEFF_FP6_C2[power % 6]); + } +} + +impl std::fmt::Display for Fp6

{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Fq6_3over2({} + {} * v, {} * v^2)", + self.c0, self.c1, self.c2 + ) + } +} + +impl Rand for Fp6

{ + fn rand(rng: &mut R) -> Self { + Self::new(rng.gen(), rng.gen(), rng.gen()) + } +} + +impl Neg for Fp6

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + let mut copy = Self::zero(); + copy.c0 = self.c0.neg(); + copy.c1 = self.c1.neg(); + copy.c2 = self.c2.neg(); + copy + } +} + +impl<'a, P: Fp6Parameters> Add<&'a Self> for Fp6

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self; + result.add_assign(&other); + result + } +} + +impl<'a, P: Fp6Parameters> Sub<&'a Self> for Fp6

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self; + result.sub_assign(&other); + result + } +} + +impl<'a, P: Fp6Parameters> Mul<&'a Self> for Fp6

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other); + result + } +} + +impl<'a, P: Fp6Parameters> Div<&'a Self> for Fp6

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp6Parameters> AddAssign<&'a Self> for Fp6

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + self.c0 += &other.c0; + self.c1 += &other.c1; + self.c2 += &other.c2; + } +} + +impl<'a, P: Fp6Parameters> SubAssign<&'a Self> for Fp6

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + self.c0 -= &other.c0; + self.c1 -= &other.c1; + self.c2 -= &other.c2; + } +} + +impl<'a, P: Fp6Parameters> MulAssign<&'a Self> for Fp6

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let v0 = self.c0 * &other.c0; + let v1 = self.c1 * &other.c1; + let v2 = self.c2 * &other.c2; + + let c0 = + P::mul_fp2_by_nonresidue(&((self.c1 + &self.c2) * &(other.c1 + &other.c2) - &v1 - &v2)) + + &v0; + let c1 = (self.c0 + &self.c1) * &(other.c0 + &other.c1) - &v0 - &v1 + + &P::mul_fp2_by_nonresidue(&v2); + let c2 = (self.c0 + &self.c2) * &(other.c0 + &other.c2) - &v0 - &v2 + &v1; + + self.c0 = c0; + self.c1 = c1; + self.c2 = c2; + } +} + +impl<'a, P: Fp6Parameters> DivAssign<&'a Self> for Fp6

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} + +impl<'a, P: Fp6Parameters> From<&'a [bool]> for Fp6

{ + fn from(_bits: &[bool]) -> Self { + unimplemented!() + } +} + +/// `Fp3` elements are ordered lexicographically. +impl Ord for Fp6

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + let c2_cmp = self.c2.cmp(&other.c2); + let c1_cmp = self.c1.cmp(&other.c1); + let c0_cmp = self.c0.cmp(&other.c0); + if c2_cmp == Ordering::Equal { + if c1_cmp == Ordering::Equal { + c0_cmp + } else { + c1_cmp + } + } else { + c2_cmp + } + } +} + +impl PartialOrd for Fp6

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp6

{ + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + self.c0.write(&mut writer)?; + self.c1.write(&mut writer)?; + self.c2.write(&mut writer) + } +} + +impl FromBytes for Fp6

{ + #[inline] + fn read(mut reader: R) -> IoResult { + let c0 = Fp2::read(&mut reader)?; + let c1 = Fp2::read(&mut reader)?; + let c2 = Fp2::read(&mut reader)?; + Ok(Fp6::new(c0, c1, c2)) + } +} diff --git a/algebra/src/fields/models/fp_256.rs b/algebra/src/fields/models/fp_256.rs new file mode 100644 index 000000000..779d38be1 --- /dev/null +++ b/algebra/src/fields/models/fp_256.rs @@ -0,0 +1,590 @@ +use rand::Rand; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +use crate::{ + biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger256 as BigInteger}, + bytes::{FromBytes, ToBytes}, + fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, +}; + +pub trait Fp256Parameters: FpParameters {} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp256Parameters"), + Hash(bound = "P: Fp256Parameters"), + Clone(bound = "P: Fp256Parameters"), + Copy(bound = "P: Fp256Parameters"), + Debug(bound = "P: Fp256Parameters"), + PartialEq(bound = "P: Fp256Parameters"), + Eq(bound = "P: Fp256Parameters") +)] +pub struct Fp256( + pub(crate) BigInteger, + #[derivative(Debug = "ignore")] PhantomData

, +); + +impl Fp256

{ + #[inline] + pub const fn new(element: BigInteger) -> Self { + Fp256::

(element, PhantomData) + } + + #[inline] + fn is_valid(&self) -> bool { + self.0 < P::MODULUS + } + + #[inline] + fn reduce(&mut self) { + if !self.is_valid() { + self.0.sub_noborrow(&P::MODULUS); + } + } + + #[inline] + fn mont_reduce( + &mut self, + r0: u64, + mut r1: u64, + mut r2: u64, + mut r3: u64, + mut r4: u64, + mut r5: u64, + mut r6: u64, + mut r7: u64, + ) { + // The Montgomery reduction here is based on Algorithm 14.32 in + // Handbook of Applied Cryptography + // . + + let k = r0.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); + r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); + r4 = fa::adc(r4, 0, &mut carry); + let carry2 = carry; + let k = r1.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); + r5 = fa::adc(r5, carry2, &mut carry); + let carry2 = carry; + let k = r2.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); + r6 = fa::adc(r6, carry2, &mut carry); + let carry2 = carry; + let k = r3.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); + r7 = fa::adc(r7, carry2, &mut carry); + (self.0).0[0] = r4; + (self.0).0[1] = r5; + (self.0).0[2] = r6; + (self.0).0[3] = r7; + self.reduce(); + } +} + +impl Field for Fp256

{ + #[inline] + fn zero() -> Self { + Fp256::

(BigInteger::from(0), PhantomData) + } + + #[inline] + fn is_zero(&self) -> bool { + self.0.is_zero() + } + + #[inline] + fn double(&self) -> Self { + let mut temp = *self; + temp.double_in_place(); + temp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + // This cannot exceed the backing capacity. + self.0.mul2(); + // However, it may need to be reduced. + self.reduce(); + self + } + + #[inline] + fn one() -> Self { + Fp256::

(P::R, PhantomData) + } + + #[inline] + fn is_one(&self) -> bool { + self == &Self::one() + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::MODULUS.as_ref() + } + + #[inline] + fn square(&self) -> Self { + let mut temp = self.clone(); + temp.square_in_place(); + temp + } + + #[inline] + fn square_in_place(&mut self) -> &mut Self { + let mut carry = 0; + let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry); + let r4 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry); + let r5 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry); + let r6 = carry; + + let r7 = r6 >> 63; + let r6 = (r6 << 1) | (r5 >> 63); + let r5 = (r5 << 1) | (r4 >> 63); + let r4 = (r4 << 1) | (r3 >> 63); + let r3 = (r3 << 1) | (r2 >> 63); + let r2 = (r2 << 1) | (r1 >> 63); + let r1 = r1 << 1; + + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry); + let r1 = fa::adc(r1, 0, &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry); + let r3 = fa::adc(r3, 0, &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry); + let r5 = fa::adc(r5, 0, &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry); + let r7 = fa::adc(r7, 0, &mut carry); + + self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7); + self + } + + #[inline] + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // Guajardo Kumar Paar Pelzl + // Efficient Software-Implementation of Finite Fields with Applications to + // Cryptography + // Algorithm 16 (BEA for Inversion in Fp) + + let one = BigInteger::from(1); + + let mut u = self.0; + let mut v = P::MODULUS; + let mut b = Fp256::

(P::R2, PhantomData); // Avoids unnecessary reduction step. + let mut c = Self::zero(); + + while u != one && v != one { + while u.is_even() { + u.div2(); + + if b.0.is_even() { + b.0.div2(); + } else { + b.0.add_nocarry(&P::MODULUS); + b.0.div2(); + } + } + + while v.is_even() { + v.div2(); + + if c.0.is_even() { + c.0.div2(); + } else { + c.0.add_nocarry(&P::MODULUS); + c.0.div2(); + } + } + + if v < u { + u.sub_noborrow(&v); + b.sub_assign(&c); + } else { + v.sub_noborrow(&u); + c.sub_assign(&b); + } + } + + if u == one { + Some(b) + } else { + Some(c) + } + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + #[inline] + fn frobenius_map(&mut self, _: usize) { + // No-op: No effect in a prime field. + } +} + +impl PrimeField for Fp256

{ + type Params = P; + type BigInt = BigInteger; + + #[inline] + fn from_repr(r: BigInteger) -> Self { + let mut r = Fp256(r, PhantomData); + if r.is_valid() { + r.mul_assign(&Fp256(P::R2, PhantomData)); + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr(&self) -> BigInteger { + let mut r = *self; + r.mont_reduce( + (self.0).0[0], + (self.0).0[1], + (self.0).0[2], + (self.0).0[3], + 0, + 0, + 0, + 0, + ); + r.0 + } + + #[inline] + fn from_repr_raw(r: BigInteger) -> Self { + let r = Fp256(r, PhantomData); + if r.is_valid() { + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr_raw(&self) -> BigInteger { + let r = *self; + r.0 + } + + #[inline] + fn from_random_bytes(bytes: &[u8]) -> Option { + use std::io::Read; + let mut result = Self::zero(); + if result.0.read_le((&bytes[..]).by_ref()).is_ok() { + result.0.as_mut()[3] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + if result.is_valid() { + Some(result) + } else { + None + } + } else { + None + } + } + + #[inline] + fn multiplicative_generator() -> Self { + Fp256::

(P::GENERATOR, PhantomData) + } + + #[inline] + fn root_of_unity() -> Self { + Fp256::

(P::ROOT_OF_UNITY, PhantomData) + } +} + +impl SquareRootField for Fp256

{ + #[inline] + fn legendre(&self) -> LegendreSymbol { + use crate::fields::LegendreSymbol::*; + + // s = self^((MODULUS - 1) // 2) + let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); + if s.is_zero() { + Zero + } else if s.is_one() { + QuadraticResidue + } else { + QuadraticNonResidue + } + } + + // Only works for p = 1 (mod 16). + #[inline] + fn sqrt(&self) -> Option { + sqrt_impl!(Self, P, self) + } + + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + if let Some(sqrt) = self.sqrt() { + *self = sqrt; + Some(self) + } else { + None + } + } +} + +impl ToBytes for Fp256

{ + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + self.into_repr().write(writer) + } +} + +impl FromBytes for Fp256

{ + #[inline] + fn read(reader: R) -> IoResult { + BigInteger::read(reader).map(Fp256::from_repr) + } +} + +/// `Fp` elements are ordered lexicographically. +impl Ord for Fp256

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + self.into_repr().cmp(&other.into_repr()) + } +} + +impl PartialOrd for Fp256

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl FromStr for Fp256

{ + type Err = (); + + /// Interpret a string of numbers as a (congruent) prime field element. + /// Does not accept unnecessary leading zeroes or a blank string. + fn from_str(s: &str) -> Result { + if s.is_empty() { + return Err(()); + } + + if s == "0" { + return Ok(Self::zero()); + } + + let mut res = Self::zero(); + + let ten = Self::from_repr(::BigInt::from(10)); + + let mut first_digit = true; + + for c in s.chars() { + match c.to_digit(10) { + Some(c) => { + if first_digit { + if c == 0 { + return Err(()); + } + + first_digit = false; + } + + res.mul_assign(&ten); + res.add_assign(&Self::from_repr(::BigInt::from( + u64::from(c), + ))); + }, + None => { + return Err(()); + }, + } + } + if !res.is_valid() { + Err(()) + } else { + Ok(res) + } + } +} + +impl Display for Fp256

{ + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "Fp256({})", self.into_repr()) + } +} + +impl Neg for Fp256

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + if !self.is_zero() { + let mut tmp = P::MODULUS; + tmp.sub_noborrow(&self.0); + Fp256::

(tmp, PhantomData) + } else { + self + } + } +} + +impl Rand for Fp256

{ + #[inline] + fn rand(rng: &mut R) -> Self { + loop { + let mut tmp = Fp256::

(BigInteger::rand(rng), PhantomData); + + // Mask away the unused bits at the beginning. + tmp.0.as_mut()[3] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + + if tmp.is_valid() { + return tmp; + } + } + } +} + +impl<'a, P: Fp256Parameters> Add<&'a Fp256

> for Fp256

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self; + result.add_assign(other); + result + } +} + +impl<'a, P: Fp256Parameters> Sub<&'a Fp256

> for Fp256

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self; + result.sub_assign(other); + result + } +} + +impl<'a, P: Fp256Parameters> Mul<&'a Fp256

> for Fp256

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(other); + result + } +} + +impl<'a, P: Fp256Parameters> Div<&'a Fp256

> for Fp256

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self; + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp256Parameters> AddAssign<&'a Self> for Fp256

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + // This cannot exceed the backing capacity. + self.0.add_nocarry(&other.0); + // However, it may need to be reduced + + self.reduce(); + } +} + +impl<'a, P: Fp256Parameters> SubAssign<&'a Self> for Fp256

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + // If `other` is larger than `self`, add the modulus to self first. + if other.0 > self.0 { + self.0.add_nocarry(&P::MODULUS); + } + + self.0.sub_noborrow(&other.0); + } +} + +impl<'a, P: Fp256Parameters> MulAssign<&'a Self> for Fp256

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[0], &mut carry); + let r1 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[3], &mut carry); + let r4 = carry; + let mut carry = 0; + let r1 = fa::mac_with_carry(r1, (self.0).0[1], (other.0).0[0], &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (other.0).0[1], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (other.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (other.0).0[3], &mut carry); + let r5 = carry; + let mut carry = 0; + let r2 = fa::mac_with_carry(r2, (self.0).0[2], (other.0).0[0], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[2], (other.0).0[1], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (other.0).0[2], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (other.0).0[3], &mut carry); + let r6 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[3], (other.0).0[0], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[3], (other.0).0[1], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[3], (other.0).0[2], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (other.0).0[3], &mut carry); + let r7 = carry; + self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7); + } +} + +impl<'a, P: Fp256Parameters> DivAssign<&'a Self> for Fp256

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} diff --git a/algebra/src/fields/models/fp_320.rs b/algebra/src/fields/models/fp_320.rs new file mode 100644 index 000000000..44943b69f --- /dev/null +++ b/algebra/src/fields/models/fp_320.rs @@ -0,0 +1,628 @@ +use rand::Rand; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +use crate::{ + biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger320 as BigInteger}, + bytes::{FromBytes, ToBytes}, + fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, +}; + +pub trait Fp320Parameters: FpParameters {} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp320Parameters"), + Hash(bound = "P: Fp320Parameters"), + Clone(bound = "P: Fp320Parameters"), + Copy(bound = "P: Fp320Parameters"), + Debug(bound = "P: Fp320Parameters"), + PartialEq(bound = "P: Fp320Parameters"), + Eq(bound = "P: Fp320Parameters") +)] +pub struct Fp320( + pub(crate) BigInteger, + #[derivative(Debug = "ignore")] PhantomData

, +); + +impl Fp320

{ + #[inline] + pub const fn new(element: BigInteger) -> Self { + Fp320::

(element, PhantomData) + } + + #[inline] + fn is_valid(&self) -> bool { + self.0 < P::MODULUS + } + + #[inline] + fn reduce(&mut self) { + if !self.is_valid() { + self.0.sub_noborrow(&P::MODULUS); + } + } + + #[inline] + fn mont_reduce( + &mut self, + r0: u64, + mut r1: u64, + mut r2: u64, + mut r3: u64, + mut r4: u64, + mut r5: u64, + mut r6: u64, + mut r7: u64, + mut r8: u64, + mut r9: u64, + ) { + // The Montgomery reduction here is based on Algorithm 14.32 in + // Handbook of Applied Cryptography + // . + + let k = r0.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); + r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[4], &mut carry); + r5 = fa::adc(r5, 0, &mut carry); + let carry2 = carry; + let k = r1.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[4], &mut carry); + r6 = fa::adc(r6, carry2, &mut carry); + let carry2 = carry; + let k = r2.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[4], &mut carry); + r7 = fa::adc(r7, carry2, &mut carry); + let carry2 = carry; + let k = r3.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[4], &mut carry); + r8 = fa::adc(r8, carry2, &mut carry); + let carry2 = carry; + let k = r4.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r4, k, P::MODULUS.0[0], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[1], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[2], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[3], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[4], &mut carry); + r9 = fa::adc(r9, carry2, &mut carry); + (self.0).0[0] = r5; + (self.0).0[1] = r6; + (self.0).0[2] = r7; + (self.0).0[3] = r8; + (self.0).0[4] = r9; + self.reduce(); + } +} + +impl Field for Fp320

{ + #[inline] + fn zero() -> Self { + Fp320::

(BigInteger::from(0), PhantomData) + } + + #[inline] + fn is_zero(&self) -> bool { + self.0.is_zero() + } + + #[inline] + fn double(&self) -> Self { + let mut temp = *self; + temp.double_in_place(); + temp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + // This cannot exceed the backing capacity. + self.0.mul2(); + // However, it may need to be reduced. + self.reduce(); + self + } + + #[inline] + fn one() -> Self { + Fp320::

(P::R, PhantomData) + } + + #[inline] + fn is_one(&self) -> bool { + self.0 == P::R + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::MODULUS.as_ref() + } + + #[inline] + fn square(&self) -> Self { + let mut temp = self.clone(); + temp.square_in_place(); + temp + } + + #[inline] + fn square_in_place(&mut self) -> &mut Self { + let mut carry = 0; + let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[4], &mut carry); + let r5 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1], (self.0).0[4], &mut carry); + let r6 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2], (self.0).0[4], &mut carry); + let r7 = carry; + let mut carry = 0; + let r7 = fa::mac_with_carry(r7, (self.0).0[3], (self.0).0[4], &mut carry); + let r8 = carry; + + let r9 = r8 >> 63; + let r8 = (r8 << 1) | (r7 >> 63); + let r7 = (r7 << 1) | (r6 >> 63); + let r6 = (r6 << 1) | (r5 >> 63); + let r5 = (r5 << 1) | (r4 >> 63); + let r4 = (r4 << 1) | (r3 >> 63); + let r3 = (r3 << 1) | (r2 >> 63); + let r2 = (r2 << 1) | (r1 >> 63); + let r1 = r1 << 1; + + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry); + let r1 = fa::adc(r1, 0, &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry); + let r3 = fa::adc(r3, 0, &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry); + let r5 = fa::adc(r5, 0, &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry); + let r7 = fa::adc(r7, 0, &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4], (self.0).0[4], &mut carry); + let r9 = fa::adc(r9, 0, &mut carry); + self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9); + self + } + + #[inline] + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // Guajardo Kumar Paar Pelzl + // Efficient Software-Implementation of Finite Fields with Applications to + // Cryptography + // Algorithm 16 (BEA for Inversion in Fp) + + let one = BigInteger::from(1); + + let mut u = self.0; + let mut v = P::MODULUS; + let mut b = Fp320::

(P::R2, PhantomData); // Avoids unnecessary reduction step. + let mut c = Self::zero(); + + while u != one && v != one { + while u.is_even() { + u.div2(); + + if b.0.is_even() { + b.0.div2(); + } else { + b.0.add_nocarry(&P::MODULUS); + b.0.div2(); + } + } + + while v.is_even() { + v.div2(); + + if c.0.is_even() { + c.0.div2(); + } else { + c.0.add_nocarry(&P::MODULUS); + c.0.div2(); + } + } + + if v < u { + u.sub_noborrow(&v); + b.sub_assign(&c); + } else { + v.sub_noborrow(&u); + c.sub_assign(&b); + } + } + + if u == one { + Some(b) + } else { + Some(c) + } + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + #[inline] + fn frobenius_map(&mut self, _: usize) { + // No-op: No effect in a prime field. + } +} + +impl PrimeField for Fp320

{ + type Params = P; + type BigInt = BigInteger; + + #[inline] + fn from_repr(r: BigInteger) -> Self { + let mut r = Fp320(r, PhantomData); + if r.is_valid() { + r.mul_assign(&Fp320(P::R2, PhantomData)); + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr(&self) -> BigInteger { + let mut r = *self; + r.mont_reduce( + (self.0).0[0], + (self.0).0[1], + (self.0).0[2], + (self.0).0[3], + (self.0).0[4], + 0, + 0, + 0, + 0, + 0, + ); + r.0 + } + + #[inline] + fn from_repr_raw(r: BigInteger) -> Self { + let r = Fp320(r, PhantomData); + if r.is_valid() { + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr_raw(&self) -> BigInteger { + let r = *self; + r.0 + } + + #[inline] + fn from_random_bytes(bytes: &[u8]) -> Option { + use std::io::Read; + let mut result = Self::zero(); + if result.0.read_le((&bytes[..]).by_ref()).is_ok() { + result.0.as_mut()[4] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + if result.is_valid() { + Some(result) + } else { + None + } + } else { + None + } + } + + #[inline] + fn multiplicative_generator() -> Self { + Fp320::

(P::GENERATOR, PhantomData) + } + + #[inline] + fn root_of_unity() -> Self { + Fp320::

(P::ROOT_OF_UNITY, PhantomData) + } +} + +impl SquareRootField for Fp320

{ + #[inline] + fn legendre(&self) -> LegendreSymbol { + use crate::fields::LegendreSymbol::*; + + // s = self^((MODULUS - 1) // 2) + let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); + if s.is_zero() { + Zero + } else if s.is_one() { + QuadraticResidue + } else { + QuadraticNonResidue + } + } + + #[inline] + fn sqrt(&self) -> Option { + sqrt_impl!(Self, P, self) + } + + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + if let Some(sqrt) = self.sqrt() { + *self = sqrt; + Some(self) + } else { + None + } + } +} + +/// `Fp` elements are ordered lexicographically. +impl Ord for Fp320

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + self.into_repr().cmp(&other.into_repr()) + } +} + +impl PartialOrd for Fp320

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp320

{ + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + self.into_repr().write(writer) + } +} + +impl FromBytes for Fp320

{ + #[inline] + fn read(reader: R) -> IoResult { + BigInteger::read(reader).map(Fp320::from_repr) + } +} + +impl FromStr for Fp320

{ + type Err = (); + + /// Interpret a string of numbers as a (congruent) prime field element. + /// Does not accept unnecessary leading zeroes or a blank string. + fn from_str(s: &str) -> Result { + if s.is_empty() { + println!("Is empty!"); + return Err(()); + } + + if s == "0" { + return Ok(Self::zero()); + } + + let mut res = Self::zero(); + + let ten = Self::from_repr(::BigInt::from(10)); + + let mut first_digit = true; + + for c in s.chars() { + match c.to_digit(10) { + Some(c) => { + if first_digit { + if c == 0 { + return Err(()); + } + + first_digit = false; + } + + res.mul_assign(&ten); + res.add_assign(&Self::from_repr(::BigInt::from( + u64::from(c), + ))); + }, + None => { + println!("Not valid digit!"); + return Err(()); + }, + } + } + if !res.is_valid() { + Err(()) + } else { + Ok(res) + } + } +} + +impl Display for Fp320

{ + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "Fp320({})", self.into_repr()) + } +} + +impl Neg for Fp320

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + if !self.is_zero() { + let mut tmp = P::MODULUS.clone(); + tmp.sub_noborrow(&self.0); + Fp320::

(tmp, PhantomData) + } else { + self + } + } +} + +impl Rand for Fp320

{ + #[inline] + fn rand(rng: &mut R) -> Self { + loop { + let mut tmp = Fp320::

(BigInteger::rand(rng), PhantomData); + + // Mask away the unused bits at the beginning. + tmp.0.as_mut()[4] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + + if tmp.is_valid() { + return tmp; + } + } + } +} + +impl<'a, P: Fp320Parameters> Add<&'a Fp320

> for Fp320

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self.clone(); + result.add_assign(other); + result + } +} + +impl<'a, P: Fp320Parameters> Sub<&'a Fp320

> for Fp320

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self.clone(); + result.sub_assign(other); + result + } +} + +impl<'a, P: Fp320Parameters> Mul<&'a Fp320

> for Fp320

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(other); + result + } +} + +impl<'a, P: Fp320Parameters> Div<&'a Fp320

> for Fp320

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp320Parameters> AddAssign<&'a Self> for Fp320

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + // This cannot exceed the backing capacity. + self.0.add_nocarry(&other.0); + // However, it may need to be reduced + self.reduce(); + } +} + +impl<'a, P: Fp320Parameters> SubAssign<&'a Self> for Fp320

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + // If `other` is larger than `self`, add the modulus to self first. + if other.0 > self.0 { + self.0.add_nocarry(&P::MODULUS); + } + + self.0.sub_noborrow(&other.0); + } +} + +impl<'a, P: Fp320Parameters> MulAssign<&'a Self> for Fp320

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[0], &mut carry); + let r1 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[3], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[4], &mut carry); + let r5 = carry; + let mut carry = 0; + let r1 = fa::mac_with_carry(r1, (self.0).0[1], (other.0).0[0], &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (other.0).0[1], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (other.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (other.0).0[3], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1], (other.0).0[4], &mut carry); + let r6 = carry; + let mut carry = 0; + let r2 = fa::mac_with_carry(r2, (self.0).0[2], (other.0).0[0], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[2], (other.0).0[1], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (other.0).0[2], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (other.0).0[3], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2], (other.0).0[4], &mut carry); + let r7 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[3], (other.0).0[0], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[3], (other.0).0[1], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[3], (other.0).0[2], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (other.0).0[3], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[3], (other.0).0[4], &mut carry); + let r8 = carry; + let mut carry = 0; + let r4 = fa::mac_with_carry(r4, (self.0).0[4], (other.0).0[0], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[4], (other.0).0[1], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[4], (other.0).0[2], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[4], (other.0).0[3], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4], (other.0).0[4], &mut carry); + let r9 = carry; + self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9); + } +} + +impl<'a, P: Fp320Parameters> DivAssign<&'a Self> for Fp320

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} diff --git a/algebra/src/fields/models/fp_384.rs b/algebra/src/fields/models/fp_384.rs new file mode 100644 index 000000000..b048b5a8a --- /dev/null +++ b/algebra/src/fields/models/fp_384.rs @@ -0,0 +1,671 @@ +use rand::Rand; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +use crate::{ + biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger384 as BigInteger}, + bytes::{FromBytes, ToBytes}, + fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, +}; + +pub trait Fp384Parameters: FpParameters {} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp384Parameters"), + Hash(bound = "P: Fp384Parameters"), + Clone(bound = "P: Fp384Parameters"), + Copy(bound = "P: Fp384Parameters"), + Debug(bound = "P: Fp384Parameters"), + PartialEq(bound = "P: Fp384Parameters"), + Eq(bound = "P: Fp384Parameters") +)] +pub struct Fp384( + pub(crate) BigInteger, + #[derivative(Debug = "ignore")] PhantomData

, +); + +impl Fp384

{ + #[inline] + pub const fn new(element: BigInteger) -> Self { + Fp384::

(element, PhantomData) + } + + #[inline] + pub(crate) fn is_valid(&self) -> bool { + self.0 < P::MODULUS + } + + #[inline] + fn reduce(&mut self) { + if !self.is_valid() { + self.0.sub_noborrow(&P::MODULUS); + } + } + + #[inline] + fn mont_reduce( + &mut self, + r0: u64, + mut r1: u64, + mut r2: u64, + mut r3: u64, + mut r4: u64, + mut r5: u64, + mut r6: u64, + mut r7: u64, + mut r8: u64, + mut r9: u64, + mut r10: u64, + mut r11: u64, + ) { + // The Montgomery reduction here is based on Algorithm 14.32 in + // Handbook of Applied Cryptography + // . + + let k = r0.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); + r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[4], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[5], &mut carry); + r6 = fa::adc(r6, 0, &mut carry); + let carry2 = carry; + let k = r1.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[4], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[5], &mut carry); + r7 = fa::adc(r7, carry2, &mut carry); + let carry2 = carry; + let k = r2.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[4], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[5], &mut carry); + r8 = fa::adc(r8, carry2, &mut carry); + let carry2 = carry; + let k = r3.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[4], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[5], &mut carry); + r9 = fa::adc(r9, carry2, &mut carry); + let carry2 = carry; + let k = r4.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r4, k, P::MODULUS.0[0], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[1], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[2], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[3], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[4], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[5], &mut carry); + r10 = fa::adc(r10, carry2, &mut carry); + let carry2 = carry; + let k = r5.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r5, k, P::MODULUS.0[0], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[1], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[2], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[3], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[4], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[5], &mut carry); + r11 = fa::adc(r11, carry2, &mut carry); + (self.0).0[0] = r6; + (self.0).0[1] = r7; + (self.0).0[2] = r8; + (self.0).0[3] = r9; + (self.0).0[4] = r10; + (self.0).0[5] = r11; + self.reduce(); + } +} + +impl Field for Fp384

{ + #[inline] + fn zero() -> Self { + Fp384::

(BigInteger::from(0), PhantomData) + } + + #[inline] + fn is_zero(&self) -> bool { + self.0.is_zero() + } + + #[inline] + fn double(&self) -> Self { + let mut temp = *self; + temp.double_in_place(); + temp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + // This cannot exceed the backing capacity. + self.0.mul2(); + // However, it may need to be reduced. + self.reduce(); + self + } + + #[inline] + fn one() -> Self { + Fp384::

(P::R, PhantomData) + } + + #[inline] + fn is_one(&self) -> bool { + self.0 == P::R + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::MODULUS.as_ref() + } + + #[inline] + fn square(&self) -> Self { + let mut temp = self.clone(); + temp.square_in_place(); + temp + } + + #[inline] + fn square_in_place(&mut self) -> &mut Self { + let mut carry = 0; + let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[4], &mut carry); + let r5 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[5], &mut carry); + let r6 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1], (self.0).0[4], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[1], (self.0).0[5], &mut carry); + let r7 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2], (self.0).0[4], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[2], (self.0).0[5], &mut carry); + let r8 = carry; + let mut carry = 0; + let r7 = fa::mac_with_carry(r7, (self.0).0[3], (self.0).0[4], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[3], (self.0).0[5], &mut carry); + let r9 = carry; + let mut carry = 0; + let r9 = fa::mac_with_carry(r9, (self.0).0[4], (self.0).0[5], &mut carry); + let r10 = carry; + + let r11 = r10 >> 63; + let r10 = (r10 << 1) | (r9 >> 63); + let r9 = (r9 << 1) | (r8 >> 63); + let r8 = (r8 << 1) | (r7 >> 63); + let r7 = (r7 << 1) | (r6 >> 63); + let r6 = (r6 << 1) | (r5 >> 63); + let r5 = (r5 << 1) | (r4 >> 63); + let r4 = (r4 << 1) | (r3 >> 63); + let r3 = (r3 << 1) | (r2 >> 63); + let r2 = (r2 << 1) | (r1 >> 63); + let r1 = r1 << 1; + + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry); + let r1 = fa::adc(r1, 0, &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry); + let r3 = fa::adc(r3, 0, &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry); + let r5 = fa::adc(r5, 0, &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry); + let r7 = fa::adc(r7, 0, &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4], (self.0).0[4], &mut carry); + let r9 = fa::adc(r9, 0, &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[5], (self.0).0[5], &mut carry); + let r11 = fa::adc(r11, 0, &mut carry); + self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11); + self + } + + #[inline] + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // Guajardo Kumar Paar Pelzl + // Efficient Software-Implementation of Finite Fields with Applications to + // Cryptography + // Algorithm 16 (BEA for Inversion in Fp) + + let one = BigInteger::from(1); + + let mut u = self.0; + let mut v = P::MODULUS; + let mut b = Fp384::

(P::R2, PhantomData); // Avoids unnecessary reduction step. + let mut c = Self::zero(); + + while u != one && v != one { + while u.is_even() { + u.div2(); + + if b.0.is_even() { + b.0.div2(); + } else { + b.0.add_nocarry(&P::MODULUS); + b.0.div2(); + } + } + + while v.is_even() { + v.div2(); + + if c.0.is_even() { + c.0.div2(); + } else { + c.0.add_nocarry(&P::MODULUS); + c.0.div2(); + } + } + + if v < u { + u.sub_noborrow(&v); + b.sub_assign(&c); + } else { + v.sub_noborrow(&u); + c.sub_assign(&b); + } + } + + if u == one { + Some(b) + } else { + Some(c) + } + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + #[inline] + fn frobenius_map(&mut self, _: usize) { + // No-op: No effect in a prime field. + } +} + +impl PrimeField for Fp384

{ + type Params = P; + type BigInt = BigInteger; + + #[inline] + fn from_repr(r: BigInteger) -> Self { + let mut r = Fp384(r, PhantomData); + if r.is_valid() { + r.mul_assign(&Fp384(P::R2, PhantomData)); + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr(&self) -> BigInteger { + let mut r = *self; + r.mont_reduce( + (self.0).0[0], + (self.0).0[1], + (self.0).0[2], + (self.0).0[3], + (self.0).0[4], + (self.0).0[5], + 0, + 0, + 0, + 0, + 0, + 0, + ); + r.0 + } + + #[inline] + fn from_repr_raw(r: BigInteger) -> Self { + let r = Fp384(r, PhantomData); + if r.is_valid() { + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr_raw(&self) -> BigInteger { + self.0 + } + + #[inline] + fn from_random_bytes(bytes: &[u8]) -> Option { + let mut result_bytes = vec![0u8; (Self::zero().0).0.len() * 8]; + for (result_byte, in_byte) in result_bytes.iter_mut().zip(bytes.iter()) { + *result_byte = *in_byte; + } + BigInteger::read(result_bytes.as_slice()) + .ok() + .and_then(|mut res| { + res.as_mut()[5] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + let result = Self::new(res); + if result.is_valid() { + Some(result) + } else { + None + } + }) + } + + #[inline] + fn multiplicative_generator() -> Self { + Fp384::

(P::GENERATOR, PhantomData) + } + + #[inline] + fn root_of_unity() -> Self { + Fp384::

(P::ROOT_OF_UNITY, PhantomData) + } +} + +impl SquareRootField for Fp384

{ + #[inline] + fn legendre(&self) -> LegendreSymbol { + use crate::fields::LegendreSymbol::*; + + // s = self^((MODULUS - 1) // 2) + let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); + if s.is_zero() { + Zero + } else if s.is_one() { + QuadraticResidue + } else { + QuadraticNonResidue + } + } + + #[inline] + fn sqrt(&self) -> Option { + sqrt_impl!(Self, P, self) + } + + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + (*self).sqrt().map(|sqrt| { + *self = sqrt; + self + }) + } +} + +impl Ord for Fp384

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + self.into_repr().cmp(&other.into_repr()) + } +} + +impl PartialOrd for Fp384

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp384

{ + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + self.into_repr().write(writer) + } +} + +impl FromBytes for Fp384

{ + #[inline] + fn read(reader: R) -> IoResult { + BigInteger::read(reader).map(Fp384::from_repr) + } +} + +impl FromStr for Fp384

{ + type Err = (); + + /// Interpret a string of numbers as a (congruent) prime field element. + /// Does not accept unnecessary leading zeroes or a blank string. + fn from_str(s: &str) -> Result { + if s.is_empty() { + println!("Is empty!"); + return Err(()); + } + + if s == "0" { + return Ok(Self::zero()); + } + + let mut res = Self::zero(); + + let ten = Self::from_repr(::BigInt::from(10)); + + let mut first_digit = true; + + for c in s.chars() { + match c.to_digit(10) { + Some(c) => { + if first_digit { + if c == 0 { + return Err(()); + } + + first_digit = false; + } + + res.mul_assign(&ten); + res.add_assign(&Self::from_repr(::BigInt::from( + u64::from(c), + ))); + }, + None => { + println!("Not valid digit!"); + return Err(()); + }, + } + } + if !res.is_valid() { + Err(()) + } else { + Ok(res) + } + } +} + +impl Display for Fp384

{ + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "Fp384({})", self.into_repr()) + } +} + +impl Neg for Fp384

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + if !self.is_zero() { + let mut tmp = P::MODULUS.clone(); + tmp.sub_noborrow(&self.0); + Fp384::

(tmp, PhantomData) + } else { + self + } + } +} + +impl Rand for Fp384

{ + #[inline] + fn rand(rng: &mut R) -> Self { + loop { + let mut tmp = Fp384::

(BigInteger::rand(rng), PhantomData); + + // Mask away the unused bits at the beginning. + tmp.0.as_mut()[5] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + + if tmp.is_valid() { + return tmp; + } + } + } +} + +impl<'a, P: Fp384Parameters> Add<&'a Fp384

> for Fp384

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self.clone(); + result.add_assign(other); + result + } +} + +impl<'a, P: Fp384Parameters> Sub<&'a Fp384

> for Fp384

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self.clone(); + result.sub_assign(other); + result + } +} + +impl<'a, P: Fp384Parameters> Mul<&'a Fp384

> for Fp384

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(other); + result + } +} + +impl<'a, P: Fp384Parameters> Div<&'a Fp384

> for Fp384

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp384Parameters> AddAssign<&'a Self> for Fp384

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + // This cannot exceed the backing capacity. + self.0.add_nocarry(&other.0); + // However, it may need to be reduced + self.reduce(); + } +} + +impl<'a, P: Fp384Parameters> SubAssign<&'a Self> for Fp384

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + // If `other` is larger than `self`, add the modulus to self first. + if other.0 > self.0 { + self.0.add_nocarry(&P::MODULUS); + } + + self.0.sub_noborrow(&other.0); + } +} + +impl<'a, P: Fp384Parameters> MulAssign<&'a Self> for Fp384

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[0], &mut carry); + let r1 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[3], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[4], &mut carry); + let r5 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[5], &mut carry); + let r6 = carry; + let mut carry = 0; + let r1 = fa::mac_with_carry(r1, (self.0).0[1], (other.0).0[0], &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (other.0).0[1], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (other.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (other.0).0[3], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1], (other.0).0[4], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[1], (other.0).0[5], &mut carry); + let r7 = carry; + let mut carry = 0; + let r2 = fa::mac_with_carry(r2, (self.0).0[2], (other.0).0[0], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[2], (other.0).0[1], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (other.0).0[2], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (other.0).0[3], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2], (other.0).0[4], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[2], (other.0).0[5], &mut carry); + let r8 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[3], (other.0).0[0], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[3], (other.0).0[1], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[3], (other.0).0[2], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (other.0).0[3], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[3], (other.0).0[4], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[3], (other.0).0[5], &mut carry); + let r9 = carry; + let mut carry = 0; + let r4 = fa::mac_with_carry(r4, (self.0).0[4], (other.0).0[0], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[4], (other.0).0[1], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[4], (other.0).0[2], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[4], (other.0).0[3], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4], (other.0).0[4], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[4], (other.0).0[5], &mut carry); + let r10 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[5], (other.0).0[0], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[5], (other.0).0[1], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[5], (other.0).0[2], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[5], (other.0).0[3], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[5], (other.0).0[4], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[5], (other.0).0[5], &mut carry); + let r11 = carry; + self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11); + } +} + +impl<'a, P: Fp384Parameters> DivAssign<&'a Self> for Fp384

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} diff --git a/algebra/src/fields/models/fp_768.rs b/algebra/src/fields/models/fp_768.rs new file mode 100644 index 000000000..425414aed --- /dev/null +++ b/algebra/src/fields/models/fp_768.rs @@ -0,0 +1,1126 @@ +use rand::Rand; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +use crate::{ + biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger768 as BigInteger}, + bytes::{FromBytes, ToBytes}, + fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, +}; + +pub trait Fp768Parameters: FpParameters {} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp768Parameters"), + Hash(bound = "P: Fp768Parameters"), + Clone(bound = "P: Fp768Parameters"), + Copy(bound = "P: Fp768Parameters"), + Debug(bound = "P: Fp768Parameters"), + PartialEq(bound = "P: Fp768Parameters"), + Eq(bound = "P: Fp768Parameters") +)] +pub struct Fp768( + pub(crate) BigInteger, + #[derivative(Debug = "ignore")] PhantomData

, +); + +impl Fp768

{ + #[inline] + pub const fn new(element: BigInteger) -> Self { + Fp768::

(element, PhantomData) + } + + #[inline] + pub(crate) fn is_valid(&self) -> bool { + self.0 < P::MODULUS + } + + #[inline] + fn reduce(&mut self) { + if !self.is_valid() { + self.0.sub_noborrow(&P::MODULUS); + } + } + + fn mont_reduce( + &mut self, + r0: u64, + mut r1: u64, + mut r2: u64, + mut r3: u64, + mut r4: u64, + mut r5: u64, + mut r6: u64, + mut r7: u64, + mut r8: u64, + mut r9: u64, + mut r10: u64, + mut r11: u64, + mut r12: u64, + mut r13: u64, + mut r14: u64, + mut r15: u64, + mut r16: u64, + mut r17: u64, + mut r18: u64, + mut r19: u64, + mut r20: u64, + mut r21: u64, + mut r22: u64, + mut r23: u64, + ) { + let k = r0.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); + r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[4], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[5], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[6], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[7], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[8], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[9], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[10], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[11], &mut carry); + r12 = fa::adc(r12, 0, &mut carry); + let carry2 = carry; + let k = r1.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[4], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[5], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[6], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[7], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[8], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[9], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[10], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[11], &mut carry); + r13 = fa::adc(r13, carry2, &mut carry); + let carry2 = carry; + let k = r2.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[4], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[5], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[6], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[7], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[8], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[9], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[10], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[11], &mut carry); + r14 = fa::adc(r14, carry2, &mut carry); + let carry2 = carry; + let k = r3.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[4], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[5], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[6], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[7], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[8], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[9], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[10], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[11], &mut carry); + r15 = fa::adc(r15, carry2, &mut carry); + let carry2 = carry; + let k = r4.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r4, k, P::MODULUS.0[0], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[1], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[2], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[3], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[4], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[5], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[6], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[7], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[8], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[9], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[10], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[11], &mut carry); + r16 = fa::adc(r16, carry2, &mut carry); + let carry2 = carry; + let k = r5.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r5, k, P::MODULUS.0[0], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[1], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[2], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[3], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[4], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[5], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[6], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[7], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[8], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[9], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[10], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[11], &mut carry); + r17 = fa::adc(r17, carry2, &mut carry); + let carry2 = carry; + let k = r6.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r6, k, P::MODULUS.0[0], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[1], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[2], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[3], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[4], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[5], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[6], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[7], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[8], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[9], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[10], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[11], &mut carry); + r18 = fa::adc(r18, carry2, &mut carry); + let carry2 = carry; + let k = r7.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r7, k, P::MODULUS.0[0], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[1], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[2], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[3], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[4], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[5], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[6], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[7], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[8], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[9], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[10], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[11], &mut carry); + r19 = fa::adc(r19, carry2, &mut carry); + let carry2 = carry; + let k = r8.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r8, k, P::MODULUS.0[0], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[1], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[2], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[3], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[4], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[5], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[6], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[7], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[8], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[9], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[10], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[11], &mut carry); + r20 = fa::adc(r20, carry2, &mut carry); + let carry2 = carry; + let k = r9.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r9, k, P::MODULUS.0[0], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[1], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[2], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[3], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[4], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[5], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[6], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[7], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[8], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[9], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[10], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[11], &mut carry); + r21 = fa::adc(r21, carry2, &mut carry); + let carry2 = carry; + let k = r10.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r10, k, P::MODULUS.0[0], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[1], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[2], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[3], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[4], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[5], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[6], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[7], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[8], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[9], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[10], &mut carry); + r21 = fa::mac_with_carry(r21, k, P::MODULUS.0[11], &mut carry); + r22 = fa::adc(r22, carry2, &mut carry); + let carry2 = carry; + let k = r11.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r11, k, P::MODULUS.0[0], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[1], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[2], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[3], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[4], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[5], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[6], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[7], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[8], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[9], &mut carry); + r21 = fa::mac_with_carry(r21, k, P::MODULUS.0[10], &mut carry); + r22 = fa::mac_with_carry(r22, k, P::MODULUS.0[11], &mut carry); + r23 = fa::adc(r23, carry2, &mut carry); + (self.0).0[0] = r12; + (self.0).0[1] = r13; + (self.0).0[2] = r14; + (self.0).0[3] = r15; + (self.0).0[4] = r16; + (self.0).0[5] = r17; + (self.0).0[6] = r18; + (self.0).0[7] = r19; + (self.0).0[8] = r20; + (self.0).0[9] = r21; + (self.0).0[10] = r22; + (self.0).0[11] = r23; + self.reduce(); + } +} + +impl Field for Fp768

{ + #[inline] + fn zero() -> Self { + Fp768::

(BigInteger::from(0), PhantomData) + } + + #[inline] + fn is_zero(&self) -> bool { + self.0.is_zero() + } + + #[inline] + fn double(&self) -> Self { + let mut temp = *self; + temp.double_in_place(); + temp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + // This cannot exceed the backing capacity. + self.0.mul2(); + // However, it may need to be reduced. + self.reduce(); + self + } + + #[inline] + fn one() -> Self { + Fp768::

(P::R, PhantomData) + } + + #[inline] + fn is_one(&self) -> bool { + self.0 == P::R + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::MODULUS.as_ref() + } + + #[inline] + fn square(&self) -> Self { + let mut temp = self.clone(); + temp.square_in_place(); + temp + } + + #[inline] + fn square_in_place(&mut self) -> &mut Self { + let mut carry = 0; + let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[4], &mut carry); + let r5 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[5], &mut carry); + let r6 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[6], &mut carry); + let r7 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[7], &mut carry); + let r8 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[8], &mut carry); + let r9 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[9], &mut carry); + let r10 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[10], &mut carry); + let r11 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[11], &mut carry); + let r12 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1], (self.0).0[4], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[1], (self.0).0[5], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[1], (self.0).0[6], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[1], (self.0).0[7], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[1], (self.0).0[8], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[1], (self.0).0[9], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[1], (self.0).0[10], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[1], (self.0).0[11], &mut carry); + let r13 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2], (self.0).0[4], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[2], (self.0).0[5], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[2], (self.0).0[6], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[2], (self.0).0[7], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[2], (self.0).0[8], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[2], (self.0).0[9], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[2], (self.0).0[10], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[2], (self.0).0[11], &mut carry); + let r14 = carry; + let mut carry = 0; + let r7 = fa::mac_with_carry(r7, (self.0).0[3], (self.0).0[4], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[3], (self.0).0[5], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[3], (self.0).0[6], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[3], (self.0).0[7], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[3], (self.0).0[8], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[3], (self.0).0[9], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[3], (self.0).0[10], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[3], (self.0).0[11], &mut carry); + let r15 = carry; + let mut carry = 0; + let r9 = fa::mac_with_carry(r9, (self.0).0[4], (self.0).0[5], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[4], (self.0).0[6], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[4], (self.0).0[7], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[4], (self.0).0[8], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[4], (self.0).0[9], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[4], (self.0).0[10], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[4], (self.0).0[11], &mut carry); + let r16 = carry; + let mut carry = 0; + let r11 = fa::mac_with_carry(r11, (self.0).0[5], (self.0).0[6], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[5], (self.0).0[7], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[5], (self.0).0[8], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[5], (self.0).0[9], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[5], (self.0).0[10], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[5], (self.0).0[11], &mut carry); + let r17 = carry; + let mut carry = 0; + let r13 = fa::mac_with_carry(r13, (self.0).0[6], (self.0).0[7], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[6], (self.0).0[8], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[6], (self.0).0[9], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[6], (self.0).0[10], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[6], (self.0).0[11], &mut carry); + let r18 = carry; + let mut carry = 0; + let r15 = fa::mac_with_carry(r15, (self.0).0[7], (self.0).0[8], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[7], (self.0).0[9], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[7], (self.0).0[10], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[7], (self.0).0[11], &mut carry); + let r19 = carry; + let mut carry = 0; + let r17 = fa::mac_with_carry(r17, (self.0).0[8], (self.0).0[9], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[8], (self.0).0[10], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[8], (self.0).0[11], &mut carry); + let r20 = carry; + let mut carry = 0; + let r19 = fa::mac_with_carry(r19, (self.0).0[9], (self.0).0[10], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[9], (self.0).0[11], &mut carry); + let r21 = carry; + let mut carry = 0; + let r21 = fa::mac_with_carry(r21, (self.0).0[10], (self.0).0[11], &mut carry); + let r22 = carry; + + let tmp0 = r1 >> 63; + let r1 = r1 << 1; + let tmp1 = r2 >> 63; + let r2 = r2 << 1; + let r2 = r2 | tmp0; + let tmp0 = tmp1; + let tmp1 = r3 >> 63; + let r3 = r3 << 1; + let r3 = r3 | tmp0; + let tmp0 = tmp1; + let tmp1 = r4 >> 63; + let r4 = r4 << 1; + let r4 = r4 | tmp0; + let tmp0 = tmp1; + let tmp1 = r5 >> 63; + let r5 = r5 << 1; + let r5 = r5 | tmp0; + let tmp0 = tmp1; + let tmp1 = r6 >> 63; + let r6 = r6 << 1; + let r6 = r6 | tmp0; + let tmp0 = tmp1; + let tmp1 = r7 >> 63; + let r7 = r7 << 1; + let r7 = r7 | tmp0; + let tmp0 = tmp1; + let tmp1 = r8 >> 63; + let r8 = r8 << 1; + let r8 = r8 | tmp0; + let tmp0 = tmp1; + let tmp1 = r9 >> 63; + let r9 = r9 << 1; + let r9 = r9 | tmp0; + let tmp0 = tmp1; + let tmp1 = r10 >> 63; + let r10 = r10 << 1; + let r10 = r10 | tmp0; + let tmp0 = tmp1; + let tmp1 = r11 >> 63; + let r11 = r11 << 1; + let r11 = r11 | tmp0; + let tmp0 = tmp1; + let tmp1 = r12 >> 63; + let r12 = r12 << 1; + let r12 = r12 | tmp0; + let tmp0 = tmp1; + let tmp1 = r13 >> 63; + let r13 = r13 << 1; + let r13 = r13 | tmp0; + let tmp0 = tmp1; + let tmp1 = r14 >> 63; + let r14 = r14 << 1; + let r14 = r14 | tmp0; + let tmp0 = tmp1; + let tmp1 = r15 >> 63; + let r15 = r15 << 1; + let r15 = r15 | tmp0; + let tmp0 = tmp1; + let tmp1 = r16 >> 63; + let r16 = r16 << 1; + let r16 = r16 | tmp0; + let tmp0 = tmp1; + let tmp1 = r17 >> 63; + let r17 = r17 << 1; + let r17 = r17 | tmp0; + let tmp0 = tmp1; + let tmp1 = r18 >> 63; + let r18 = r18 << 1; + let r18 = r18 | tmp0; + let tmp0 = tmp1; + let tmp1 = r19 >> 63; + let r19 = r19 << 1; + let r19 = r19 | tmp0; + let tmp0 = tmp1; + let tmp1 = r20 >> 63; + let r20 = r20 << 1; + let r20 = r20 | tmp0; + let tmp0 = tmp1; + let tmp1 = r21 >> 63; + let r21 = r21 << 1; + let r21 = r21 | tmp0; + let tmp0 = tmp1; + let tmp1 = r22 >> 63; + let r22 = r22 << 1; + let r22 = r22 | tmp0; + let tmp0 = tmp1; + let r23 = tmp0; + + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry); + let r1 = fa::adc(r1, 0, &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry); + let r3 = fa::adc(r3, 0, &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry); + let r5 = fa::adc(r5, 0, &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry); + let r7 = fa::adc(r7, 0, &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4], (self.0).0[4], &mut carry); + let r9 = fa::adc(r9, 0, &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[5], (self.0).0[5], &mut carry); + let r11 = fa::adc(r11, 0, &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[6], (self.0).0[6], &mut carry); + let r13 = fa::adc(r13, 0, &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[7], (self.0).0[7], &mut carry); + let r15 = fa::adc(r15, 0, &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[8], (self.0).0[8], &mut carry); + let r17 = fa::adc(r17, 0, &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[9], (self.0).0[9], &mut carry); + let r19 = fa::adc(r19, 0, &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[10], (self.0).0[10], &mut carry); + let r21 = fa::adc(r21, 0, &mut carry); + let r22 = fa::mac_with_carry(r22, (self.0).0[11], (self.0).0[11], &mut carry); + let r23 = fa::adc(r23, 0, &mut carry); + + self.mont_reduce( + r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, + r19, r20, r21, r22, r23, + ); + self + } + + #[inline] + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // Guajardo Kumar Paar Pelzl + // Efficient Software-Implementation of Finite Fields with Applications to + // Cryptography + // Algorithm 16 (BEA for Inversion in Fp) + + let one = BigInteger::from(1); + + let mut u = self.0; + let mut v = P::MODULUS; + let mut b = Fp768::

(P::R2, PhantomData); // Avoids unnecessary reduction step. + let mut c = Self::zero(); + + while u != one && v != one { + while u.is_even() { + u.div2(); + + if b.0.is_even() { + b.0.div2(); + } else { + b.0.add_nocarry(&P::MODULUS); + b.0.div2(); + } + } + + while v.is_even() { + v.div2(); + + if c.0.is_even() { + c.0.div2(); + } else { + c.0.add_nocarry(&P::MODULUS); + c.0.div2(); + } + } + + if v < u { + u.sub_noborrow(&v); + b.sub_assign(&c); + } else { + v.sub_noborrow(&u); + c.sub_assign(&b); + } + } + + if u == one { + Some(b) + } else { + Some(c) + } + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + #[inline] + fn frobenius_map(&mut self, _: usize) { + // No-op: No effect in a prime field. + } +} + +impl PrimeField for Fp768

{ + type Params = P; + type BigInt = BigInteger; + + #[inline] + fn from_repr(r: BigInteger) -> Self { + let mut r = Fp768(r, PhantomData); + if r.is_valid() { + r.mul_assign(&Fp768(P::R2, PhantomData)); + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr(&self) -> BigInteger { + let mut r = *self; + r.mont_reduce( + (self.0).0[0], + (self.0).0[1], + (self.0).0[2], + (self.0).0[3], + (self.0).0[4], + (self.0).0[5], + (self.0).0[6], + (self.0).0[7], + (self.0).0[8], + (self.0).0[9], + (self.0).0[10], + (self.0).0[11], + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ); + r.0 + } + + #[inline] + fn from_repr_raw(r: BigInteger) -> Self { + let r = Fp768(r, PhantomData); + if r.is_valid() { + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr_raw(&self) -> BigInteger { + let r = *self; + r.0 + } + + #[inline] + fn from_random_bytes(bytes: &[u8]) -> Option { + use std::io::Read; + let mut result = Self::zero(); + if result.0.read_le((&bytes[..]).by_ref()).is_ok() { + result.0.as_mut()[11] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + if result.is_valid() { + Some(result) + } else { + None + } + } else { + None + } + } + + #[inline] + fn multiplicative_generator() -> Self { + Fp768::

(P::GENERATOR, PhantomData) + } + + #[inline] + fn root_of_unity() -> Self { + Fp768::

(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn size_in_bits() -> usize { + P::MODULUS_BITS as usize + } + + #[inline] + fn trace() -> BigInteger { + P::T + } + + #[inline] + fn trace_minus_one_div_two() -> BigInteger { + P::T_MINUS_ONE_DIV_TWO + } + + #[inline] + fn modulus_minus_one_div_two() -> BigInteger { + P::MODULUS_MINUS_ONE_DIV_TWO + } +} + +impl SquareRootField for Fp768

{ + #[inline] + fn legendre(&self) -> LegendreSymbol { + use crate::fields::LegendreSymbol::*; + + // s = self^((MODULUS - 1) // 2) + let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); + if s.is_zero() { + Zero + } else if s.is_one() { + QuadraticResidue + } else { + QuadraticNonResidue + } + } + + #[inline] + fn sqrt(&self) -> Option { + sqrt_impl!(Self, P, self) + } + + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + if let Some(sqrt) = self.sqrt() { + *self = sqrt; + Some(self) + } else { + None + } + } +} + +impl Ord for Fp768

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + self.into_repr().cmp(&other.into_repr()) + } +} + +impl PartialOrd for Fp768

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp768

{ + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + self.into_repr().write(writer) + } +} + +impl FromBytes for Fp768

{ + #[inline] + fn read(reader: R) -> IoResult { + BigInteger::read(reader).map(Fp768::from_repr) + } +} + +impl FromStr for Fp768

{ + type Err = (); + + /// Interpret a string of numbers as a (congruent) prime field element. + /// Does not accept unnecessary leading zeroes or a blank string. + fn from_str(s: &str) -> Result { + if s.is_empty() { + println!("Is empty!"); + return Err(()); + } + + if s == "0" { + return Ok(Self::zero()); + } + + let mut res = Self::zero(); + + let ten = Self::from_repr(::BigInt::from(10)); + + let mut first_digit = true; + + for c in s.chars() { + match c.to_digit(10) { + Some(c) => { + if first_digit { + if c == 0 { + return Err(()); + } + + first_digit = false; + } + + res.mul_assign(&ten); + res.add_assign(&Self::from_repr(::BigInt::from( + u64::from(c), + ))); + }, + None => { + println!("Not valid digit!"); + return Err(()); + }, + } + } + if !res.is_valid() { + Err(()) + } else { + Ok(res) + } + } +} + +impl Display for Fp768

{ + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "Fp768({})", self.into_repr()) + } +} + +impl Neg for Fp768

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + if !self.is_zero() { + let mut tmp = P::MODULUS.clone(); + tmp.sub_noborrow(&self.0); + Fp768::

(tmp, PhantomData) + } else { + self + } + } +} + +impl Rand for Fp768

{ + #[inline] + fn rand(rng: &mut R) -> Self { + loop { + let mut tmp = Fp768::

(BigInteger::rand(rng), PhantomData); + + // Mask away the unused bits at the beginning. + tmp.0.as_mut()[11] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + + if tmp.is_valid() { + return tmp; + } + } + } +} + +impl<'a, P: Fp768Parameters> Add<&'a Fp768

> for Fp768

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self.clone(); + result.add_assign(other); + result + } +} + +impl<'a, P: Fp768Parameters> Sub<&'a Fp768

> for Fp768

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self.clone(); + result.sub_assign(other); + result + } +} + +impl<'a, P: Fp768Parameters> Mul<&'a Fp768

> for Fp768

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(other); + result + } +} + +impl<'a, P: Fp768Parameters> Div<&'a Fp768

> for Fp768

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp768Parameters> AddAssign<&'a Self> for Fp768

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + // This cannot exceed the backing capacity. + self.0.add_nocarry(&other.0); + // However, it may need to be reduced + self.reduce(); + } +} + +impl<'a, P: Fp768Parameters> SubAssign<&'a Self> for Fp768

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + // If `other` is larger than `self`, add the modulus to self first. + if other.0 > self.0 { + self.0.add_nocarry(&P::MODULUS); + } + + self.0.sub_noborrow(&other.0); + } +} + +impl<'a, P: Fp768Parameters> MulAssign<&'a Self> for Fp768

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[0], &mut carry); + let r1 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[1], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[2], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[3], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[4], &mut carry); + let r5 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[5], &mut carry); + let r6 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[6], &mut carry); + let r7 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[7], &mut carry); + let r8 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[8], &mut carry); + let r9 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[9], &mut carry); + let r10 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[10], &mut carry); + let r11 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[11], &mut carry); + let r12 = carry; + let mut carry = 0; + let r1 = fa::mac_with_carry(r1, (self.0).0[1], (other.0).0[0], &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1], (other.0).0[1], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[1], (other.0).0[2], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1], (other.0).0[3], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1], (other.0).0[4], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[1], (other.0).0[5], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[1], (other.0).0[6], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[1], (other.0).0[7], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[1], (other.0).0[8], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[1], (other.0).0[9], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[1], (other.0).0[10], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[1], (other.0).0[11], &mut carry); + let r13 = carry; + let mut carry = 0; + let r2 = fa::mac_with_carry(r2, (self.0).0[2], (other.0).0[0], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[2], (other.0).0[1], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2], (other.0).0[2], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[2], (other.0).0[3], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2], (other.0).0[4], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[2], (other.0).0[5], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[2], (other.0).0[6], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[2], (other.0).0[7], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[2], (other.0).0[8], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[2], (other.0).0[9], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[2], (other.0).0[10], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[2], (other.0).0[11], &mut carry); + let r14 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[3], (other.0).0[0], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[3], (other.0).0[1], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[3], (other.0).0[2], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3], (other.0).0[3], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[3], (other.0).0[4], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[3], (other.0).0[5], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[3], (other.0).0[6], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[3], (other.0).0[7], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[3], (other.0).0[8], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[3], (other.0).0[9], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[3], (other.0).0[10], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[3], (other.0).0[11], &mut carry); + let r15 = carry; + let mut carry = 0; + let r4 = fa::mac_with_carry(r4, (self.0).0[4], (other.0).0[0], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[4], (other.0).0[1], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[4], (other.0).0[2], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[4], (other.0).0[3], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4], (other.0).0[4], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[4], (other.0).0[5], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[4], (other.0).0[6], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[4], (other.0).0[7], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[4], (other.0).0[8], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[4], (other.0).0[9], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[4], (other.0).0[10], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[4], (other.0).0[11], &mut carry); + let r16 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[5], (other.0).0[0], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[5], (other.0).0[1], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[5], (other.0).0[2], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[5], (other.0).0[3], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[5], (other.0).0[4], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[5], (other.0).0[5], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[5], (other.0).0[6], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[5], (other.0).0[7], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[5], (other.0).0[8], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[5], (other.0).0[9], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[5], (other.0).0[10], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[5], (other.0).0[11], &mut carry); + let r17 = carry; + let mut carry = 0; + let r6 = fa::mac_with_carry(r6, (self.0).0[6], (other.0).0[0], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[6], (other.0).0[1], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[6], (other.0).0[2], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[6], (other.0).0[3], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[6], (other.0).0[4], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[6], (other.0).0[5], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[6], (other.0).0[6], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[6], (other.0).0[7], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[6], (other.0).0[8], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[6], (other.0).0[9], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[6], (other.0).0[10], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[6], (other.0).0[11], &mut carry); + let r18 = carry; + let mut carry = 0; + let r7 = fa::mac_with_carry(r7, (self.0).0[7], (other.0).0[0], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[7], (other.0).0[1], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[7], (other.0).0[2], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[7], (other.0).0[3], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[7], (other.0).0[4], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[7], (other.0).0[5], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[7], (other.0).0[6], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[7], (other.0).0[7], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[7], (other.0).0[8], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[7], (other.0).0[9], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[7], (other.0).0[10], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[7], (other.0).0[11], &mut carry); + let r19 = carry; + let mut carry = 0; + let r8 = fa::mac_with_carry(r8, (self.0).0[8], (other.0).0[0], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[8], (other.0).0[1], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[8], (other.0).0[2], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[8], (other.0).0[3], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[8], (other.0).0[4], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[8], (other.0).0[5], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[8], (other.0).0[6], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[8], (other.0).0[7], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[8], (other.0).0[8], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[8], (other.0).0[9], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[8], (other.0).0[10], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[8], (other.0).0[11], &mut carry); + let r20 = carry; + let mut carry = 0; + let r9 = fa::mac_with_carry(r9, (self.0).0[9], (other.0).0[0], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[9], (other.0).0[1], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[9], (other.0).0[2], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[9], (other.0).0[3], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[9], (other.0).0[4], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[9], (other.0).0[5], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[9], (other.0).0[6], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[9], (other.0).0[7], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[9], (other.0).0[8], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[9], (other.0).0[9], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[9], (other.0).0[10], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[9], (other.0).0[11], &mut carry); + let r21 = carry; + let mut carry = 0; + let r10 = fa::mac_with_carry(r10, (self.0).0[10], (other.0).0[0], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[10], (other.0).0[1], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[10], (other.0).0[2], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[10], (other.0).0[3], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[10], (other.0).0[4], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[10], (other.0).0[5], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[10], (other.0).0[6], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[10], (other.0).0[7], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[10], (other.0).0[8], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[10], (other.0).0[9], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[10], (other.0).0[10], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[10], (other.0).0[11], &mut carry); + let r22 = carry; + let mut carry = 0; + let r11 = fa::mac_with_carry(r11, (self.0).0[11], (other.0).0[0], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[11], (other.0).0[1], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[11], (other.0).0[2], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[11], (other.0).0[3], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[11], (other.0).0[4], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[11], (other.0).0[5], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[11], (other.0).0[6], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[11], (other.0).0[7], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[11], (other.0).0[8], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[11], (other.0).0[9], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[11], (other.0).0[10], &mut carry); + let r22 = fa::mac_with_carry(r22, (self.0).0[11], (other.0).0[11], &mut carry); + let r23 = carry; + self.mont_reduce( + r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, + r19, r20, r21, r22, r23, + ); + } +} + +impl<'a, P: Fp768Parameters> DivAssign<&'a Self> for Fp768

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} diff --git a/algebra/src/fields/models/fp_832.rs b/algebra/src/fields/models/fp_832.rs new file mode 100644 index 000000000..4a27fde1d --- /dev/null +++ b/algebra/src/fields/models/fp_832.rs @@ -0,0 +1,1121 @@ +use crate::{ + biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger832 as BigInteger}, + bytes::{FromBytes, ToBytes}, + fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, +}; +use rand::Rand; +use std::{ + cmp::{Ord, Ordering, PartialOrd}, + fmt::{Display, Formatter, Result as FmtResult}, + io::{Read, Result as IoResult, Write}, + marker::PhantomData, + ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, + str::FromStr, +}; + +pub trait Fp832Parameters: FpParameters {} + +#[derive(Derivative)] +#[derivative( + Default(bound = "P: Fp832Parameters"), + Hash(bound = "P: Fp832Parameters"), + Clone(bound = "P: Fp832Parameters"), + Copy(bound = "P: Fp832Parameters"), + Debug(bound = "P: Fp832Parameters"), + PartialEq(bound = "P: Fp832Parameters"), + Eq(bound = "P: Fp832Parameters") +)] +pub struct Fp832( + pub(crate) BigInteger, + #[derivative(Debug = "ignore")] PhantomData

, +); + +impl Fp832

{ + #[inline] + pub const fn new(element: BigInteger) -> Self { + Fp832::

(element, PhantomData) + } + + #[inline] + pub(crate) fn is_valid(&self) -> bool { + self.0 < P::MODULUS + } + + #[inline] + fn reduce(&mut self) { + if !self.is_valid() { + self.0.sub_noborrow(&P::MODULUS); + } + } + + fn mont_reduce( + &mut self, + r0: u64, + mut r1: u64, + mut r2: u64, + mut r3: u64, + mut r4: u64, + mut r5: u64, + mut r6: u64, + mut r7: u64, + mut r8: u64, + mut r9: u64, + mut r10: u64, + mut r11: u64, + mut r12: u64, + mut r13: u64, + mut r14: u64, + mut r15: u64, + mut r16: u64, + mut r17: u64, + mut r18: u64, + mut r19: u64, + mut r20: u64, + mut r21: u64, + mut r22: u64, + mut r23: u64, + mut r24: u64, + mut r25: u64, + ) { + let k = r0.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); + r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[4], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[5], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[6], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[7], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[8], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[9], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[10], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[11], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[12], &mut carry); + r13 = fa::adc(r13, 0, &mut carry); + let carry2 = carry; + let k = r1.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); + r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[4], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[5], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[6], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[7], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[8], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[9], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[10], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[11], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[12], &mut carry); + r14 = fa::adc(r14, carry2, &mut carry); + let carry2 = carry; + let k = r2.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); + r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[4], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[5], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[6], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[7], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[8], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[9], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[10], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[11], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[12], &mut carry); + r15 = fa::adc(r15, carry2, &mut carry); + let carry2 = carry; + let k = r3.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); + r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[4], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[5], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[6], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[7], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[8], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[9], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[10], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[11], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[12], &mut carry); + r16 = fa::adc(r16, carry2, &mut carry); + let carry2 = carry; + let k = r4.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r4, k, P::MODULUS.0[0], &mut carry); + r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[1], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[2], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[3], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[4], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[5], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[6], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[7], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[8], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[9], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[10], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[11], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[12], &mut carry); + r17 = fa::adc(r17, carry2, &mut carry); + let carry2 = carry; + let k = r5.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r5, k, P::MODULUS.0[0], &mut carry); + r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[1], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[2], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[3], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[4], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[5], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[6], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[7], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[8], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[9], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[10], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[11], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[12], &mut carry); + r18 = fa::adc(r18, carry2, &mut carry); + let carry2 = carry; + let k = r6.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r6, k, P::MODULUS.0[0], &mut carry); + r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[1], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[2], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[3], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[4], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[5], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[6], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[7], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[8], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[9], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[10], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[11], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[12], &mut carry); + r19 = fa::adc(r19, carry2, &mut carry); + let carry2 = carry; + let k = r7.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r7, k, P::MODULUS.0[0], &mut carry); + r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[1], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[2], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[3], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[4], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[5], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[6], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[7], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[8], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[9], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[10], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[11], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[12], &mut carry); + r20 = fa::adc(r20, carry2, &mut carry); + let carry2 = carry; + let k = r8.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r8, k, P::MODULUS.0[0], &mut carry); + r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[1], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[2], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[3], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[4], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[5], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[6], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[7], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[8], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[9], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[10], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[11], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[12], &mut carry); + r21 = fa::adc(r21, carry2, &mut carry); + let carry2 = carry; + let k = r9.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r9, k, P::MODULUS.0[0], &mut carry); + r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[1], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[2], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[3], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[4], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[5], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[6], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[7], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[8], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[9], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[10], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[11], &mut carry); + r21 = fa::mac_with_carry(r21, k, P::MODULUS.0[12], &mut carry); + r22 = fa::adc(r22, carry2, &mut carry); + let carry2 = carry; + let k = r10.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r10, k, P::MODULUS.0[0], &mut carry); + r11 = fa::mac_with_carry(r11, k, P::MODULUS.0[1], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[2], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[3], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[4], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[5], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[6], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[7], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[8], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[9], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[10], &mut carry); + r21 = fa::mac_with_carry(r21, k, P::MODULUS.0[11], &mut carry); + r22 = fa::mac_with_carry(r22, k, P::MODULUS.0[12], &mut carry); + r23 = fa::adc(r23, carry2, &mut carry); + let carry2 = carry; + let k = r11.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r11, k, P::MODULUS.0[0], &mut carry); + r12 = fa::mac_with_carry(r12, k, P::MODULUS.0[1], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[2], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[3], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[4], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[5], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[6], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[7], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[8], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[9], &mut carry); + r21 = fa::mac_with_carry(r21, k, P::MODULUS.0[10], &mut carry); + r22 = fa::mac_with_carry(r22, k, P::MODULUS.0[11], &mut carry); + r23 = fa::mac_with_carry(r23, k, P::MODULUS.0[12], &mut carry); + r24 = fa::adc(r24, carry2, &mut carry); + let carry2 = carry; + let k = r12.wrapping_mul(P::INV); + let mut carry = 0; + fa::mac_with_carry(r12, k, P::MODULUS.0[0], &mut carry); + r13 = fa::mac_with_carry(r13, k, P::MODULUS.0[1], &mut carry); + r14 = fa::mac_with_carry(r14, k, P::MODULUS.0[2], &mut carry); + r15 = fa::mac_with_carry(r15, k, P::MODULUS.0[3], &mut carry); + r16 = fa::mac_with_carry(r16, k, P::MODULUS.0[4], &mut carry); + r17 = fa::mac_with_carry(r17, k, P::MODULUS.0[5], &mut carry); + r18 = fa::mac_with_carry(r18, k, P::MODULUS.0[6], &mut carry); + r19 = fa::mac_with_carry(r19, k, P::MODULUS.0[7], &mut carry); + r20 = fa::mac_with_carry(r20, k, P::MODULUS.0[8], &mut carry); + r21 = fa::mac_with_carry(r21, k, P::MODULUS.0[9], &mut carry); + r22 = fa::mac_with_carry(r22, k, P::MODULUS.0[10], &mut carry); + r23 = fa::mac_with_carry(r23, k, P::MODULUS.0[11], &mut carry); + r24 = fa::mac_with_carry(r24, k, P::MODULUS.0[12], &mut carry); + r25 = fa::adc(r25, carry2, &mut carry); + (self.0).0[0] = r13; + (self.0).0[1] = r14; + (self.0).0[2] = r15; + (self.0).0[3] = r16; + (self.0).0[4] = r17; + (self.0).0[5] = r18; + (self.0).0[6] = r19; + (self.0).0[7] = r20; + (self.0).0[8] = r21; + (self.0).0[9] = r22; + (self.0).0[10] = r23; + (self.0).0[11] = r24; + (self.0).0[12] = r25; + self.reduce(); + } +} + +impl Field for Fp832

{ + #[inline] + fn zero() -> Self { + Fp832::

(BigInteger::from(0), PhantomData) + } + + #[inline] + fn is_zero(&self) -> bool { + self.0.is_zero() + } + + #[inline] + fn double(&self) -> Self { + let mut temp = *self; + temp.double_in_place(); + temp + } + + #[inline] + fn double_in_place(&mut self) -> &mut Self { + // This cannot exceed the backing capacity. + self.0.mul2(); + // However, it may need to be reduced. + self.reduce(); + self + } + + #[inline] + fn one() -> Self { + Fp832::

(P::R, PhantomData) + } + + #[inline] + fn is_one(&self) -> bool { + self.0 == P::R + } + + #[inline] + fn characteristic<'a>() -> &'a [u64] { + P::MODULUS.as_ref() + } + + #[inline] + fn square(&self) -> Self { + let mut temp = self.clone(); + temp.square_in_place(); + temp + } + + fn square_in_place(&mut self) -> &mut Self { + let mut carry = 0; + let r1 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[1usize], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[2usize], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[3usize], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[4usize], &mut carry); + let r5 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[5usize], &mut carry); + let r6 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[6usize], &mut carry); + let r7 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[7usize], &mut carry); + let r8 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[8usize], &mut carry); + let r9 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[9usize], &mut carry); + let r10 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[10usize], &mut carry); + let r11 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[11usize], &mut carry); + let r12 = fa::mac_with_carry(0, (self.0).0[0usize], (self.0).0[12usize], &mut carry); + let r13 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[1usize], (self.0).0[2usize], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1usize], (self.0).0[3usize], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1usize], (self.0).0[4usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[1usize], (self.0).0[5usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[1usize], (self.0).0[6usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[1usize], (self.0).0[7usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[1usize], (self.0).0[8usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[1usize], (self.0).0[9usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[1usize], (self.0).0[10usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[1usize], (self.0).0[11usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[1usize], (self.0).0[12usize], &mut carry); + let r14 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[2usize], (self.0).0[3usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2usize], (self.0).0[4usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[2usize], (self.0).0[5usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[2usize], (self.0).0[6usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[2usize], (self.0).0[7usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[2usize], (self.0).0[8usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[2usize], (self.0).0[9usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[2usize], (self.0).0[10usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[2usize], (self.0).0[11usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[2usize], (self.0).0[12usize], &mut carry); + let r15 = carry; + let mut carry = 0; + let r7 = fa::mac_with_carry(r7, (self.0).0[3usize], (self.0).0[4usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[3usize], (self.0).0[5usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[3usize], (self.0).0[6usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[3usize], (self.0).0[7usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[3usize], (self.0).0[8usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[3usize], (self.0).0[9usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[3usize], (self.0).0[10usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[3usize], (self.0).0[11usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[3usize], (self.0).0[12usize], &mut carry); + let r16 = carry; + let mut carry = 0; + let r9 = fa::mac_with_carry(r9, (self.0).0[4usize], (self.0).0[5usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[4usize], (self.0).0[6usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[4usize], (self.0).0[7usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[4usize], (self.0).0[8usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[4usize], (self.0).0[9usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[4usize], (self.0).0[10usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[4usize], (self.0).0[11usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[4usize], (self.0).0[12usize], &mut carry); + let r17 = carry; + let mut carry = 0; + let r11 = fa::mac_with_carry(r11, (self.0).0[5usize], (self.0).0[6usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[5usize], (self.0).0[7usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[5usize], (self.0).0[8usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[5usize], (self.0).0[9usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[5usize], (self.0).0[10usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[5usize], (self.0).0[11usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[5usize], (self.0).0[12usize], &mut carry); + let r18 = carry; + let mut carry = 0; + let r13 = fa::mac_with_carry(r13, (self.0).0[6usize], (self.0).0[7usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[6usize], (self.0).0[8usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[6usize], (self.0).0[9usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[6usize], (self.0).0[10usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[6usize], (self.0).0[11usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[6usize], (self.0).0[12usize], &mut carry); + let r19 = carry; + let mut carry = 0; + let r15 = fa::mac_with_carry(r15, (self.0).0[7usize], (self.0).0[8usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[7usize], (self.0).0[9usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[7usize], (self.0).0[10usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[7usize], (self.0).0[11usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[7usize], (self.0).0[12usize], &mut carry); + let r20 = carry; + let mut carry = 0; + let r17 = fa::mac_with_carry(r17, (self.0).0[8usize], (self.0).0[9usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[8usize], (self.0).0[10usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[8usize], (self.0).0[11usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[8usize], (self.0).0[12usize], &mut carry); + let r21 = carry; + let mut carry = 0; + let r19 = fa::mac_with_carry(r19, (self.0).0[9usize], (self.0).0[10usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[9usize], (self.0).0[11usize], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[9usize], (self.0).0[12usize], &mut carry); + let r22 = carry; + let mut carry = 0; + let r21 = fa::mac_with_carry(r21, (self.0).0[10usize], (self.0).0[11usize], &mut carry); + let r22 = fa::mac_with_carry(r22, (self.0).0[10usize], (self.0).0[12usize], &mut carry); + let r23 = carry; + let mut carry = 0; + let r23 = fa::mac_with_carry(r23, (self.0).0[11usize], (self.0).0[12usize], &mut carry); + let r24 = carry; + let r25 = r24 >> 63; + let r24 = (r24 << 1) | (r23 >> 63); + let r23 = (r23 << 1) | (r22 >> 63); + let r22 = (r22 << 1) | (r21 >> 63); + let r21 = (r21 << 1) | (r20 >> 63); + let r20 = (r20 << 1) | (r19 >> 63); + let r19 = (r19 << 1) | (r18 >> 63); + let r18 = (r18 << 1) | (r17 >> 63); + let r17 = (r17 << 1) | (r16 >> 63); + let r16 = (r16 << 1) | (r15 >> 63); + let r15 = (r15 << 1) | (r14 >> 63); + let r14 = (r14 << 1) | (r13 >> 63); + let r13 = (r13 << 1) | (r12 >> 63); + let r12 = (r12 << 1) | (r11 >> 63); + let r11 = (r11 << 1) | (r10 >> 63); + let r10 = (r10 << 1) | (r9 >> 63); + let r9 = (r9 << 1) | (r8 >> 63); + let r8 = (r8 << 1) | (r7 >> 63); + let r7 = (r7 << 1) | (r6 >> 63); + let r6 = (r6 << 1) | (r5 >> 63); + let r5 = (r5 << 1) | (r4 >> 63); + let r4 = (r4 << 1) | (r3 >> 63); + let r3 = (r3 << 1) | (r2 >> 63); + let r2 = (r2 << 1) | (r1 >> 63); + let r1 = r1 << 1; + + let mut r_s = [ + 0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, + r19, r20, r21, r22, r23, r24, r25, + ]; + + let mut carry = 0; + for i in 0..13 { + r_s[2 * i] = fa::mac_with_carry(r_s[2 * i], (self.0).0[i], (self.0).0[i], &mut carry); + r_s[2 * i + 1] = fa::adc(r_s[2 * i + 1], 0, &mut carry); + } + self.mont_reduce( + r_s[0], r_s[1], r_s[2], r_s[3], r_s[4], r_s[5], r_s[6], r_s[7], r_s[8], r_s[9], + r_s[10], r_s[11], r_s[12], r_s[13], r_s[14], r_s[15], r_s[16], r_s[17], r_s[18], + r_s[19], r_s[20], r_s[21], r_s[22], r_s[23], r_s[24], r_s[25], + ); + self + } + + #[inline] + fn inverse(&self) -> Option { + if self.is_zero() { + None + } else { + // Guajardo Kumar Paar Pelzl + // Efficient Software-Implementation of Finite Fields with Applications to + // Cryptography + // Algorithm 16 (BEA for Inversion in Fp) + + let one = BigInteger::from(1); + + let mut u = self.0; + let mut v = P::MODULUS; + let mut b = Fp832::

(P::R2, PhantomData); // Avoids unnecessary reduction step. + let mut c = Self::zero(); + + while u != one && v != one { + while u.is_even() { + u.div2(); + + if b.0.is_even() { + b.0.div2(); + } else { + b.0.add_nocarry(&P::MODULUS); + b.0.div2(); + } + } + + while v.is_even() { + v.div2(); + + if c.0.is_even() { + c.0.div2(); + } else { + c.0.add_nocarry(&P::MODULUS); + c.0.div2(); + } + } + + if v < u { + u.sub_noborrow(&v); + b.sub_assign(&c); + } else { + v.sub_noborrow(&u); + c.sub_assign(&b); + } + } + + if u == one { + Some(b) + } else { + Some(c) + } + } + } + + fn inverse_in_place(&mut self) -> Option<&mut Self> { + if let Some(inverse) = self.inverse() { + *self = inverse; + Some(self) + } else { + None + } + } + + #[inline] + fn frobenius_map(&mut self, _: usize) { + // No-op: No effect in a prime field. + } +} + +impl PrimeField for Fp832

{ + type Params = P; + type BigInt = BigInteger; + + #[inline] + fn from_repr(r: BigInteger) -> Self { + let mut r = Fp832(r, PhantomData); + if r.is_valid() { + r.mul_assign(&Fp832(P::R2, PhantomData)); + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr(&self) -> BigInteger { + let mut r = *self; + r.mont_reduce( + (self.0).0[0], + (self.0).0[1], + (self.0).0[2], + (self.0).0[3], + (self.0).0[4], + (self.0).0[5], + (self.0).0[6], + (self.0).0[7], + (self.0).0[8], + (self.0).0[9], + (self.0).0[10], + (self.0).0[11], + (self.0).0[12], + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ); + r.0 + } + + #[inline] + fn from_repr_raw(r: BigInteger) -> Self { + let r = Fp832(r, PhantomData); + if r.is_valid() { + r + } else { + Self::zero() + } + } + + #[inline] + fn into_repr_raw(&self) -> BigInteger { + let r = *self; + r.0 + } + + #[inline] + fn from_random_bytes(bytes: &[u8]) -> Option { + use std::io::Read; + let mut result = Self::zero(); + if result.0.read_le((&bytes[..]).by_ref()).is_ok() { + result.0.as_mut()[12] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + if result.is_valid() { + Some(result) + } else { + None + } + } else { + None + } + } + + #[inline] + fn multiplicative_generator() -> Self { + Fp832::

(P::GENERATOR, PhantomData) + } + + #[inline] + fn root_of_unity() -> Self { + Fp832::

(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn size_in_bits() -> usize { + P::MODULUS_BITS as usize + } + + #[inline] + fn trace() -> BigInteger { + P::T + } + + #[inline] + fn trace_minus_one_div_two() -> BigInteger { + P::T_MINUS_ONE_DIV_TWO + } + + #[inline] + fn modulus_minus_one_div_two() -> BigInteger { + P::MODULUS_MINUS_ONE_DIV_TWO + } +} + +impl SquareRootField for Fp832

{ + #[inline] + fn legendre(&self) -> LegendreSymbol { + use crate::fields::LegendreSymbol::*; + + // s = self^((MODULUS - 1) // 2) + let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); + if s.is_zero() { + Zero + } else if s.is_one() { + QuadraticResidue + } else { + QuadraticNonResidue + } + } + + #[inline] + fn sqrt(&self) -> Option { + sqrt_impl!(Self, P, self) + } + + fn sqrt_in_place(&mut self) -> Option<&mut Self> { + if let Some(sqrt) = self.sqrt() { + *self = sqrt; + Some(self) + } else { + None + } + } +} + +impl Ord for Fp832

{ + #[inline(always)] + fn cmp(&self, other: &Self) -> Ordering { + self.into_repr().cmp(&other.into_repr()) + } +} + +impl PartialOrd for Fp832

{ + #[inline(always)] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl ToBytes for Fp832

{ + #[inline] + fn write(&self, writer: W) -> IoResult<()> { + self.into_repr().write(writer) + } +} + +impl FromBytes for Fp832

{ + #[inline] + fn read(reader: R) -> IoResult { + BigInteger::read(reader).map(Fp832::from_repr) + } +} + +impl FromStr for Fp832

{ + type Err = (); + + /// Interpret a string of numbers as a (congruent) prime field element. + /// Does not accept unnecessary leading zeroes or a blank string. + fn from_str(s: &str) -> Result { + if s.is_empty() { + println!("Is empty!"); + return Err(()); + } + + if s == "0" { + return Ok(Self::zero()); + } + + let mut res = Self::zero(); + + let ten = Self::from_repr(::BigInt::from(10)); + + let mut first_digit = true; + + for c in s.chars() { + match c.to_digit(10) { + Some(c) => { + if first_digit { + if c == 0 { + return Err(()); + } + + first_digit = false; + } + + res.mul_assign(&ten); + res.add_assign(&Self::from_repr(::BigInt::from( + u64::from(c), + ))); + }, + None => { + println!("Not valid digit!"); + return Err(()); + }, + } + } + if !res.is_valid() { + Err(()) + } else { + Ok(res) + } + } +} + +impl Display for Fp832

{ + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "Fp832({})", self.into_repr()) + } +} + +impl Neg for Fp832

{ + type Output = Self; + #[inline] + #[must_use] + fn neg(self) -> Self { + if !self.is_zero() { + let mut tmp = P::MODULUS.clone(); + tmp.sub_noborrow(&self.0); + Fp832::

(tmp, PhantomData) + } else { + self + } + } +} + +impl Rand for Fp832

{ + #[inline] + fn rand(rng: &mut R) -> Self { + loop { + let mut tmp = Fp832::

(BigInteger::rand(rng), PhantomData); + + // Mask away the unused bits at the beginning. + tmp.0.as_mut()[12] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; + + if tmp.is_valid() { + return tmp; + } + } + } +} + +impl<'a, P: Fp832Parameters> Add<&'a Fp832

> for Fp832

{ + type Output = Self; + + #[inline] + fn add(self, other: &Self) -> Self { + let mut result = self.clone(); + result.add_assign(other); + result + } +} + +impl<'a, P: Fp832Parameters> Sub<&'a Fp832

> for Fp832

{ + type Output = Self; + + #[inline] + fn sub(self, other: &Self) -> Self { + let mut result = self.clone(); + result.sub_assign(other); + result + } +} + +impl<'a, P: Fp832Parameters> Mul<&'a Fp832

> for Fp832

{ + type Output = Self; + + #[inline] + fn mul(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(other); + result + } +} + +impl<'a, P: Fp832Parameters> Div<&'a Fp832

> for Fp832

{ + type Output = Self; + + #[inline] + fn div(self, other: &Self) -> Self { + let mut result = self.clone(); + result.mul_assign(&other.inverse().unwrap()); + result + } +} + +impl<'a, P: Fp832Parameters> AddAssign<&'a Self> for Fp832

{ + #[inline] + fn add_assign(&mut self, other: &Self) { + // This cannot exceed the backing capacity. + self.0.add_nocarry(&other.0); + // However, it may need to be reduced + self.reduce(); + } +} + +impl<'a, P: Fp832Parameters> SubAssign<&'a Self> for Fp832

{ + #[inline] + fn sub_assign(&mut self, other: &Self) { + // If `other` is larger than `self`, add the modulus to self first. + if other.0 > self.0 { + self.0.add_nocarry(&P::MODULUS); + } + + self.0.sub_noborrow(&other.0); + } +} + +impl<'a, P: Fp832Parameters> MulAssign<&'a Self> for Fp832

{ + #[inline] + fn mul_assign(&mut self, other: &Self) { + let mut carry = 0; + let r0 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[0usize], &mut carry); + let r1 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[1usize], &mut carry); + let r2 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[2usize], &mut carry); + let r3 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[3usize], &mut carry); + let r4 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[4usize], &mut carry); + let r5 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[5usize], &mut carry); + let r6 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[6usize], &mut carry); + let r7 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[7usize], &mut carry); + let r8 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[8usize], &mut carry); + let r9 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[9usize], &mut carry); + let r10 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[10usize], &mut carry); + let r11 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[11usize], &mut carry); + let r12 = fa::mac_with_carry(0, (self.0).0[0usize], (other.0).0[12usize], &mut carry); + let r13 = carry; + let mut carry = 0; + let r1 = fa::mac_with_carry(r1, (self.0).0[1usize], (other.0).0[0usize], &mut carry); + let r2 = fa::mac_with_carry(r2, (self.0).0[1usize], (other.0).0[1usize], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[1usize], (other.0).0[2usize], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[1usize], (other.0).0[3usize], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[1usize], (other.0).0[4usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[1usize], (other.0).0[5usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[1usize], (other.0).0[6usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[1usize], (other.0).0[7usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[1usize], (other.0).0[8usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[1usize], (other.0).0[9usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[1usize], (other.0).0[10usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[1usize], (other.0).0[11usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[1usize], (other.0).0[12usize], &mut carry); + let r14 = carry; + let mut carry = 0; + let r2 = fa::mac_with_carry(r2, (self.0).0[2usize], (other.0).0[0usize], &mut carry); + let r3 = fa::mac_with_carry(r3, (self.0).0[2usize], (other.0).0[1usize], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[2usize], (other.0).0[2usize], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[2usize], (other.0).0[3usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[2usize], (other.0).0[4usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[2usize], (other.0).0[5usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[2usize], (other.0).0[6usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[2usize], (other.0).0[7usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[2usize], (other.0).0[8usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[2usize], (other.0).0[9usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[2usize], (other.0).0[10usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[2usize], (other.0).0[11usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[2usize], (other.0).0[12usize], &mut carry); + let r15 = carry; + let mut carry = 0; + let r3 = fa::mac_with_carry(r3, (self.0).0[3usize], (other.0).0[0usize], &mut carry); + let r4 = fa::mac_with_carry(r4, (self.0).0[3usize], (other.0).0[1usize], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[3usize], (other.0).0[2usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[3usize], (other.0).0[3usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[3usize], (other.0).0[4usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[3usize], (other.0).0[5usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[3usize], (other.0).0[6usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[3usize], (other.0).0[7usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[3usize], (other.0).0[8usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[3usize], (other.0).0[9usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[3usize], (other.0).0[10usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[3usize], (other.0).0[11usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[3usize], (other.0).0[12usize], &mut carry); + let r16 = carry; + let mut carry = 0; + let r4 = fa::mac_with_carry(r4, (self.0).0[4usize], (other.0).0[0usize], &mut carry); + let r5 = fa::mac_with_carry(r5, (self.0).0[4usize], (other.0).0[1usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[4usize], (other.0).0[2usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[4usize], (other.0).0[3usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[4usize], (other.0).0[4usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[4usize], (other.0).0[5usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[4usize], (other.0).0[6usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[4usize], (other.0).0[7usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[4usize], (other.0).0[8usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[4usize], (other.0).0[9usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[4usize], (other.0).0[10usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[4usize], (other.0).0[11usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[4usize], (other.0).0[12usize], &mut carry); + let r17 = carry; + let mut carry = 0; + let r5 = fa::mac_with_carry(r5, (self.0).0[5usize], (other.0).0[0usize], &mut carry); + let r6 = fa::mac_with_carry(r6, (self.0).0[5usize], (other.0).0[1usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[5usize], (other.0).0[2usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[5usize], (other.0).0[3usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[5usize], (other.0).0[4usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[5usize], (other.0).0[5usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[5usize], (other.0).0[6usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[5usize], (other.0).0[7usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[5usize], (other.0).0[8usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[5usize], (other.0).0[9usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[5usize], (other.0).0[10usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[5usize], (other.0).0[11usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[5usize], (other.0).0[12usize], &mut carry); + let r18 = carry; + let mut carry = 0; + let r6 = fa::mac_with_carry(r6, (self.0).0[6usize], (other.0).0[0usize], &mut carry); + let r7 = fa::mac_with_carry(r7, (self.0).0[6usize], (other.0).0[1usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[6usize], (other.0).0[2usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[6usize], (other.0).0[3usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[6usize], (other.0).0[4usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[6usize], (other.0).0[5usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[6usize], (other.0).0[6usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[6usize], (other.0).0[7usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[6usize], (other.0).0[8usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[6usize], (other.0).0[9usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[6usize], (other.0).0[10usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[6usize], (other.0).0[11usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[6usize], (other.0).0[12usize], &mut carry); + let r19 = carry; + let mut carry = 0; + let r7 = fa::mac_with_carry(r7, (self.0).0[7usize], (other.0).0[0usize], &mut carry); + let r8 = fa::mac_with_carry(r8, (self.0).0[7usize], (other.0).0[1usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[7usize], (other.0).0[2usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[7usize], (other.0).0[3usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[7usize], (other.0).0[4usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[7usize], (other.0).0[5usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[7usize], (other.0).0[6usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[7usize], (other.0).0[7usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[7usize], (other.0).0[8usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[7usize], (other.0).0[9usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[7usize], (other.0).0[10usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[7usize], (other.0).0[11usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[7usize], (other.0).0[12usize], &mut carry); + let r20 = carry; + let mut carry = 0; + let r8 = fa::mac_with_carry(r8, (self.0).0[8usize], (other.0).0[0usize], &mut carry); + let r9 = fa::mac_with_carry(r9, (self.0).0[8usize], (other.0).0[1usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[8usize], (other.0).0[2usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[8usize], (other.0).0[3usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[8usize], (other.0).0[4usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[8usize], (other.0).0[5usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[8usize], (other.0).0[6usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[8usize], (other.0).0[7usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[8usize], (other.0).0[8usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[8usize], (other.0).0[9usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[8usize], (other.0).0[10usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[8usize], (other.0).0[11usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[8usize], (other.0).0[12usize], &mut carry); + let r21 = carry; + let mut carry = 0; + let r9 = fa::mac_with_carry(r9, (self.0).0[9usize], (other.0).0[0usize], &mut carry); + let r10 = fa::mac_with_carry(r10, (self.0).0[9usize], (other.0).0[1usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[9usize], (other.0).0[2usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[9usize], (other.0).0[3usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[9usize], (other.0).0[4usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[9usize], (other.0).0[5usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[9usize], (other.0).0[6usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[9usize], (other.0).0[7usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[9usize], (other.0).0[8usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[9usize], (other.0).0[9usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[9usize], (other.0).0[10usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[9usize], (other.0).0[11usize], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[9usize], (other.0).0[12usize], &mut carry); + let r22 = carry; + let mut carry = 0; + let r10 = fa::mac_with_carry(r10, (self.0).0[10usize], (other.0).0[0usize], &mut carry); + let r11 = fa::mac_with_carry(r11, (self.0).0[10usize], (other.0).0[1usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[10usize], (other.0).0[2usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[10usize], (other.0).0[3usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[10usize], (other.0).0[4usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[10usize], (other.0).0[5usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[10usize], (other.0).0[6usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[10usize], (other.0).0[7usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[10usize], (other.0).0[8usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[10usize], (other.0).0[9usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[10usize], (other.0).0[10usize], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[10usize], (other.0).0[11usize], &mut carry); + let r22 = fa::mac_with_carry(r22, (self.0).0[10usize], (other.0).0[12usize], &mut carry); + let r23 = carry; + let mut carry = 0; + let r11 = fa::mac_with_carry(r11, (self.0).0[11usize], (other.0).0[0usize], &mut carry); + let r12 = fa::mac_with_carry(r12, (self.0).0[11usize], (other.0).0[1usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[11usize], (other.0).0[2usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[11usize], (other.0).0[3usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[11usize], (other.0).0[4usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[11usize], (other.0).0[5usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[11usize], (other.0).0[6usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[11usize], (other.0).0[7usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[11usize], (other.0).0[8usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[11usize], (other.0).0[9usize], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[11usize], (other.0).0[10usize], &mut carry); + let r22 = fa::mac_with_carry(r22, (self.0).0[11usize], (other.0).0[11usize], &mut carry); + let r23 = fa::mac_with_carry(r23, (self.0).0[11usize], (other.0).0[12usize], &mut carry); + let r24 = carry; + let mut carry = 0; + let r12 = fa::mac_with_carry(r12, (self.0).0[12usize], (other.0).0[0usize], &mut carry); + let r13 = fa::mac_with_carry(r13, (self.0).0[12usize], (other.0).0[1usize], &mut carry); + let r14 = fa::mac_with_carry(r14, (self.0).0[12usize], (other.0).0[2usize], &mut carry); + let r15 = fa::mac_with_carry(r15, (self.0).0[12usize], (other.0).0[3usize], &mut carry); + let r16 = fa::mac_with_carry(r16, (self.0).0[12usize], (other.0).0[4usize], &mut carry); + let r17 = fa::mac_with_carry(r17, (self.0).0[12usize], (other.0).0[5usize], &mut carry); + let r18 = fa::mac_with_carry(r18, (self.0).0[12usize], (other.0).0[6usize], &mut carry); + let r19 = fa::mac_with_carry(r19, (self.0).0[12usize], (other.0).0[7usize], &mut carry); + let r20 = fa::mac_with_carry(r20, (self.0).0[12usize], (other.0).0[8usize], &mut carry); + let r21 = fa::mac_with_carry(r21, (self.0).0[12usize], (other.0).0[9usize], &mut carry); + let r22 = fa::mac_with_carry(r22, (self.0).0[12usize], (other.0).0[10usize], &mut carry); + let r23 = fa::mac_with_carry(r23, (self.0).0[12usize], (other.0).0[11usize], &mut carry); + let r24 = fa::mac_with_carry(r24, (self.0).0[12usize], (other.0).0[12usize], &mut carry); + let r25 = carry; + self.mont_reduce( + r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, + r19, r20, r21, r22, r23, r24, r25, + ); + } +} + +impl<'a, P: Fp832Parameters> DivAssign<&'a Self> for Fp832

{ + #[inline] + fn div_assign(&mut self, other: &Self) { + self.mul_assign(&other.inverse().unwrap()); + } +} diff --git a/algebra/src/fields/models/mod.rs b/algebra/src/fields/models/mod.rs new file mode 100644 index 000000000..56ed1f214 --- /dev/null +++ b/algebra/src/fields/models/mod.rs @@ -0,0 +1,27 @@ +pub mod fp_256; +pub use self::fp_256::*; + +pub mod fp_320; +pub use self::fp_320::*; + +pub mod fp_384; +pub use self::fp_384::*; + +pub mod fp_768; +pub use self::fp_768::*; + +pub mod fp_832; +pub use self::fp_832::*; + +pub mod fp2; +pub use self::fp2::*; + +pub mod fp3; +pub use self::fp3::*; + +pub mod fp6_2over3; +pub use self::fp6_2over3::*; + +pub mod fp6_3over2; + +pub mod fp12_2over3over2; diff --git a/algebra/src/fields/sw6/fq.rs b/algebra/src/fields/sw6/fq.rs new file mode 100644 index 000000000..eee568a0c --- /dev/null +++ b/algebra/src/fields/sw6/fq.rs @@ -0,0 +1,157 @@ +use crate::{ + biginteger::BigInteger832 as BigInteger, + fields::{Fp832, Fp832Parameters, FpParameters}, +}; + +pub type Fq = Fp832; + +pub struct FqParameters; + +impl Fp832Parameters for FqParameters {} +impl FpParameters for FqParameters { + type BigInt = BigInteger; + + /// MODULUS = 22369874298875696930346742206501054934775599465297184582183496627646774052458024540232479018147881220178054575403841904557897715222633333372134756426301062487682326574958588001132586331462553235407484089304633076250782629492557320825577 + const MODULUS: BigInteger = BigInteger([ + 0xdace79b57b942ae9, + 0x545d85c16dfd424a, + 0xee135c065f4d26b7, + 0x9c2f764a12c4024b, + 0x1ad533049cfe6a39, + 0x52a3fb77c79c1320, + 0xab3596c8617c5792, + 0x830c728d80f9d78b, + 0x6a7223ee72023d07, + 0xbc5d176b746af026, + 0xe959283d8f526663, + 0xc4d2263babf8941f, + 0x3848, + ]); + + const MODULUS_BITS: u32 = 782; + + const CAPACITY: u32 = Self::MODULUS_BITS - 1; + + const REPR_SHAVE_BITS: u32 = 50; + + const R: BigInteger = BigInteger([ + 11190988450819017841u64, + 16170411717126802030u64, + 2265463223430229059u64, + 16946880912571045974u64, + 11155248462028513229u64, + 12855672356664541314u64, + 8489376931127408159u64, + 2655797810825538098u64, + 9648483887143916718u64, + 17514963461276738952u64, + 16777089214204267338u64, + 15649035958020076168u64, + 8659u64, + ]); + + const R2: BigInteger = BigInteger([ + 13983406830510863714u64, + 17863856572171232656u64, + 1698388424046564526u64, + 1773634430448388392u64, + 8684647957094413275u64, + 3992637317298078843u64, + 18420879196616862245u64, + 3238482510270583127u64, + 7928200707794018216u64, + 10024831010452223910u64, + 9613847725664942650u64, + 15361265984156787358u64, + 7833u64, + ]); + + const INV: u64 = 14469047335842394791u64; + + /// GENERATOR = 13 + const GENERATOR: BigInteger = BigInteger([ + 16669393626057438558u64, + 1640520694378723217u64, + 1598646156981121135u64, + 12401834967100173388u64, + 2356467520877704673u64, + 14759118825104212161u64, + 5556628239575210651u64, + 5317520392768798654u64, + 16398429955031064995u64, + 3556102264904210145u64, + 8166834915717907988u64, + 11926665585800594452u64, + 11716u64, + ]); + + const TWO_ADICITY: u32 = 3; + + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 18044746167194862600u64, + 63590321303744709u64, + 5009346151370959890u64, + 2859114157767503991u64, + 8301813204852325413u64, + 5629414263664332594u64, + 2637340888701394641u64, + 17433538052687852753u64, + 2230763098934759248u64, + 3785382115983092023u64, + 8895511354022222370u64, + 15792083141709071785u64, + 1328u64, + ]); + + const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x6d673cdabdca1574, + 0xaa2ec2e0b6fea125, + 0xf709ae032fa6935b, + 0xce17bb2509620125, + 0xd6a99824e7f351c, + 0x2951fdbbe3ce0990, + 0xd59acb6430be2bc9, + 0xc1863946c07cebc5, + 0x353911f739011e83, + 0xde2e8bb5ba357813, + 0xf4ac941ec7a93331, + 0x6269131dd5fc4a0f, + 0x1c24, + ]); + + // (T - 1)/2 = + // 1398117143679731058146671387906315933423474966581074036386468539227923378278626533764529938634242576261128410962740119034868607201414583335758422276643816405480145410934911750070786645716409577212967755581539567265673914343284832551598 + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0xadace79b57b942ae, + 0x7545d85c16dfd424, + 0xbee135c065f4d26b, + 0x99c2f764a12c4024, + 0x1ad533049cfe6a3, + 0x252a3fb77c79c132, + 0xbab3596c8617c579, + 0x7830c728d80f9d78, + 0x66a7223ee72023d0, + 0x3bc5d176b746af02, + 0xfe959283d8f52666, + 0x8c4d2263babf8941, + 0x384, + ]); + + // T = + // 2796234287359462116293342775812631866846949933162148072772937078455846756557253067529059877268485152522256821925480238069737214402829166671516844553287632810960290821869823500141573291432819154425935511163079134531347828686569665103197 + const T: BigInteger = BigInteger([ + 0x5b59cf36af72855d, + 0xea8bb0b82dbfa849, + 0x7dc26b80cbe9a4d6, + 0x3385eec942588049, + 0x35aa660939fcd47, + 0x4a547f6ef8f38264, + 0x7566b2d90c2f8af2, + 0xf0618e51b01f3af1, + 0xcd4e447dce4047a0, + 0x778ba2ed6e8d5e04, + 0xfd2b2507b1ea4ccc, + 0x189a44c7757f1283, + 0x709, + ]); +} diff --git a/algebra/src/fields/sw6/fq3.rs b/algebra/src/fields/sw6/fq3.rs new file mode 100644 index 000000000..be2444395 --- /dev/null +++ b/algebra/src/fields/sw6/fq3.rs @@ -0,0 +1,201 @@ +use crate::{ + biginteger::BigInteger832 as BigInteger, + fields::{ + fp3::{Fp3, Fp3Parameters}, + sw6::fq::Fq, + }, +}; + +pub type Fq3 = Fp3; + +pub struct Fq3Parameters; + +impl Fp3Parameters for Fq3Parameters { + type Fp = Fq; + + /// NONRESIDUE = 13 + const NONRESIDUE: Fq = Fq::new(BigInteger([ + 0xe755952f4650755e, + 0x16c44ce1331ef791, + 0x162f8835b467306f, + 0xac1c2b31e1062c4c, + 0x20b3dab9a2a935e1, + 0xccd2ec5fd01e00c1, + 0x4d1d1bf190c8da9b, + 0x49cba09fb0e13fbe, + 0xe392ed2957c061a3, + 0x3159d02b3c93d6e1, + 0x71566d160a9f8614, + 0xa5840728fc854414, + 0x2dc4, + ])); + + const TWO_ADICITY: u32 = 3; + + const T_MINUS_ONE_DIV_TWO: &'static [u64] = &[ + 0x62730e2cd2029617, + 0x660647f735cb88cf, + 0x274359d60784f69d, + 0x83067194eb102629, + 0x54ea4a12a9381160, + 0xade0b24e398dac25, + 0xb476ae9f927e81cb, + 0x220fd4a9178adc3b, + 0x57e0cb9b0569745b, + 0xba15024addc8f52e, + 0x145b9bc116144ab6, + 0x6bc2260726e88b15, + 0x51da6bf151066474, + 0x9fd1b3190f6320cf, + 0x2097bfb7bf4167b0, + 0x27c35b1e7e628e09, + 0x94f80c9d623dd9bb, + 0x20bfa6d5bf31e7d3, + 0x19fb862c049d3a8, + 0xdf4c5efe04c0cec1, + 0x32c9a8abe9b50297, + 0x268d5c2076b44f0a, + 0x76027ec67b23ca21, + 0x248d61e0c45d270, + 0x419cd0d1d6be027e, + 0xbcd8dc3b1986ef18, + 0x73093d8719c862c2, + 0x651d60f8f9f6fcd9, + 0x8dabebe38a09b261, + 0xfa85b5a9e180cd3f, + 0x6a97fc618f319fb7, + 0xce08b93a5652a8e1, + 0x37525cbc4ba24cf9, + 0xb104c580df9d2150, + 0x1407c1bfe240a89d, + 0x34c96a73372daf9a, + 0x2b87fda171, + ]; + + const QUADRATIC_NONRESIDUE_TO_T: (Fq, Fq, Fq) = ( + Fq::new(BigInteger([ + 0x59987c0ef8e31739, + 0x59578d750d6f57dd, + 0x9672547570dddab8, + 0x1a1f630e1d6dbdd5, + 0xde15f46e52d7613e, + 0x6a1b6e4f80179926, + 0x461ad119d93123b, + 0x12054e3654907ed9, + 0x85ea06b12bf811a0, + 0xc01d53d07347f9ec, + 0x70c424eb666c3922, + 0x1796ce4ed605d49e, + 0x68b, + ])), + Fq::new(BigInteger([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])), + Fq::new(BigInteger([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])), + ); + + const FROBENIUS_COEFF_FP3_C1: [Fq; 3] = [ + Fq::new(BigInteger([ + 0x9b4e60b420910c71, + 0xe068d7c83f284a6e, + 0x1f708acc7c452c43, + 0xeb2f6a66cca51856, + 0x9acf675f886e9fcd, + 0xb26885e567cc8082, + 0x75d05357183eb61f, + 0x24db4a09b5842a32, + 0x85e64cf9ba4b14ae, + 0xf311a6784358a588, + 0xe8d431c061aecb4a, + 0xd92c8b4aab19f288, + 0x21d3, + ])), + Fq::new(BigInteger([ + 0xe793e750fc0c0fdc, + 0x28cd75f5634a867e, + 0xde5e9b1261eb3c33, + 0x68a0fb1c17595903, + 0x19626d2c9f392e46, + 0xc4d95794cb378b83, + 0x54870f1f582d67c9, + 0xf3f1a0ac4aceb56d, + 0x811361215ea4fd47, + 0x32cd6ee17d95bd00, + 0x725f9881049a9c52, + 0x5acb70be0613a307, + 0x11bb, + ])), + Fq::new(BigInteger([ + 0x57ec31b05ef70e9c, + 0x4b273803cb8a715d, + 0xf0443627811cbe40, + 0x485f10c72ec590f1, + 0x66a35e7875569c25, + 0xdb621dfd9498071a, + 0xe0de3451f11039a8, + 0x6a3f87d780a6f7eb, + 0x637875d359122b11, + 0x967e0211b37c8d9d, + 0x8e255dfc2908fec6, + 0x90da2a32facafe8f, + 0x4b9, + ])), + ]; + + const FROBENIUS_COEFF_FP3_C2: [Fq; 3] = [ + Fq::new(BigInteger([ + 0x9b4e60b420910c71, + 0xe068d7c83f284a6e, + 0x1f708acc7c452c43, + 0xeb2f6a66cca51856, + 0x9acf675f886e9fcd, + 0xb26885e567cc8082, + 0x75d05357183eb61f, + 0x24db4a09b5842a32, + 0x85e64cf9ba4b14ae, + 0xf311a6784358a588, + 0xe8d431c061aecb4a, + 0xd92c8b4aab19f288, + 0x21d3, + ])), + Fq::new(BigInteger([ + 0x57ec31b05ef70e9c, + 0x4b273803cb8a715d, + 0xf0443627811cbe40, + 0x485f10c72ec590f1, + 0x66a35e7875569c25, + 0xdb621dfd9498071a, + 0xe0de3451f11039a8, + 0x6a3f87d780a6f7eb, + 0x637875d359122b11, + 0x967e0211b37c8d9d, + 0x8e255dfc2908fec6, + 0x90da2a32facafe8f, + 0x4b9, + ])), + Fq::new(BigInteger([ + 0xe793e750fc0c0fdc, + 0x28cd75f5634a867e, + 0xde5e9b1261eb3c33, + 0x68a0fb1c17595903, + 0x19626d2c9f392e46, + 0xc4d95794cb378b83, + 0x54870f1f582d67c9, + 0xf3f1a0ac4aceb56d, + 0x811361215ea4fd47, + 0x32cd6ee17d95bd00, + 0x725f9881049a9c52, + 0x5acb70be0613a307, + 0x11bb, + ])), + ]; + + #[inline(always)] + fn mul_fp_by_nonresidue(fe: &Self::Fp) -> Self::Fp { + use crate::fields::Field; + + let original = *fe; + let mut four_fe = fe.double(); + four_fe.double_in_place(); + let eight_fe = four_fe.double(); + eight_fe + &four_fe + &original + } +} diff --git a/algebra/src/fields/sw6/fq6.rs b/algebra/src/fields/sw6/fq6.rs new file mode 100644 index 000000000..9ac90fce9 --- /dev/null +++ b/algebra/src/fields/sw6/fq6.rs @@ -0,0 +1,136 @@ +use crate::{ + biginteger::BigInteger832 as BigInteger, + fields::{ + fp6_2over3::{Fp6, Fp6Parameters}, + sw6::{ + fq::Fq, + fq3::{Fq3, Fq3Parameters}, + }, + }, +}; + +pub type Fq6 = Fp6; + +pub struct Fq6Parameters; + +impl Fp6Parameters for Fq6Parameters { + type Fp3Params = Fq3Parameters; + + /// NONRESIDUE = 13 + const NONRESIDUE: Fq3 = Fq3::new( + Fq::new(BigInteger([ + 0xe755952f4650755e, + 0x16c44ce1331ef791, + 0x162f8835b467306f, + 0xac1c2b31e1062c4c, + 0x20b3dab9a2a935e1, + 0xccd2ec5fd01e00c1, + 0x4d1d1bf190c8da9b, + 0x49cba09fb0e13fbe, + 0xe392ed2957c061a3, + 0x3159d02b3c93d6e1, + 0x71566d160a9f8614, + 0xa5840728fc854414, + 0x2dc4, + ])), + Fq::new(BigInteger([ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + ])), + Fq::new(BigInteger([ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + ])), + ); + + const FROBENIUS_COEFF_FP6_C1: [Fq; 6] = [ + Fq::new(BigInteger([ + 0x9b4e60b420910c71, + 0xe068d7c83f284a6e, + 0x1f708acc7c452c43, + 0xeb2f6a66cca51856, + 0x9acf675f886e9fcd, + 0xb26885e567cc8082, + 0x75d05357183eb61f, + 0x24db4a09b5842a32, + 0x85e64cf9ba4b14ae, + 0xf311a6784358a588, + 0xe8d431c061aecb4a, + 0xd92c8b4aab19f288, + 0x21d3, + ])), + Fq::new(BigInteger([ + 0x82e248051c9d1c4d, + 0x9364dbda272d0ed, + 0xfdcf25dede306877, + 0x53d06582e3fe7159, + 0xb431d48c27a7ce14, + 0x7741dd7a33040c05, + 0xca576276706c1de9, + 0x18cceab60052df9f, + 0x6f9ae1b18f011f6, + 0x25df1559c0ee6289, + 0x5b33ca416649679d, + 0x33f7fc08b12d9590, + 0x338f, + ])), + Fq::new(BigInteger([ + 0xe793e750fc0c0fdc, + 0x28cd75f5634a867e, + 0xde5e9b1261eb3c33, + 0x68a0fb1c17595903, + 0x19626d2c9f392e46, + 0xc4d95794cb378b83, + 0x54870f1f582d67c9, + 0xf3f1a0ac4aceb56d, + 0x811361215ea4fd47, + 0x32cd6ee17d95bd00, + 0x725f9881049a9c52, + 0x5acb70be0613a307, + 0x11bb, + ])), + Fq::new(BigInteger([ + 0x3f8019015b031e78, + 0x73f4adf92ed4f7dc, + 0xcea2d139e307fa73, + 0xb1000be3461ee9f5, + 0x8005cba5148fca6b, + 0xa03b75925fcf929d, + 0x35654371493da172, + 0x5e312883cb75ad59, + 0xe48bd6f4b7b72859, + 0xc94b70f331124a9d, + 0x84f67d2da39b18, + 0xeba59af100dea197, + 0x1674, + ])), + Fq::new(BigInteger([ + 0x57ec31b05ef70e9c, + 0x4b273803cb8a715d, + 0xf0443627811cbe40, + 0x485f10c72ec590f1, + 0x66a35e7875569c25, + 0xdb621dfd9498071a, + 0xe0de3451f11039a8, + 0x6a3f87d780a6f7eb, + 0x637875d359122b11, + 0x967e0211b37c8d9d, + 0x8e255dfc2908fec6, + 0x90da2a32facafe8f, + 0x4b9, + ])), + Fq::new(BigInteger([ + 0xf33a92647f881b0d, + 0x2b900fcc0ab2bbcb, + 0xfb4c0f3fd61ea84, + 0x338e7b2dfb6aa948, + 0x172c5d7fdc53bf3, + 0x8dcaa3e2fc64879d, + 0x56ae87a9094eefc8, + 0x8f1ad1e1362b221e, + 0xe95ec2cd135d3fbf, + 0x898fa889f6d53325, + 0x76f98fbc8ab7ca11, + 0x6a06b57da5e4f118, + 0x268d, + ])), + ]; +} diff --git a/algebra/src/fields/sw6/fr.rs b/algebra/src/fields/sw6/fr.rs new file mode 100644 index 000000000..55a87296c --- /dev/null +++ b/algebra/src/fields/sw6/fr.rs @@ -0,0 +1 @@ +pub use crate::fields::bls12_377::fq::{Fq as Fr, FqParameters as FrParameters}; diff --git a/algebra/src/fields/sw6/mod.rs b/algebra/src/fields/sw6/mod.rs new file mode 100644 index 000000000..7bfd333df --- /dev/null +++ b/algebra/src/fields/sw6/mod.rs @@ -0,0 +1,14 @@ +pub mod fr; +pub use self::fr::*; + +pub mod fq; +pub use self::fq::*; + +pub mod fq3; +pub use self::fq3::*; + +pub mod fq6; +pub use self::fq6::*; + +#[cfg(test)] +mod tests; diff --git a/algebra/src/fields/sw6/tests.rs b/algebra/src/fields/sw6/tests.rs new file mode 100644 index 000000000..79d077186 --- /dev/null +++ b/algebra/src/fields/sw6/tests.rs @@ -0,0 +1,50 @@ +use crate::fields::tests::{field_test, frobenius_test, primefield_test, sqrt_field_test}; + +#[test] +fn test_sw6_fr() { + use crate::fields::sw6::Fr; + + let a: Fr = rand::random(); + let b: Fr = rand::random(); + field_test(a, b); + sqrt_field_test(a); + primefield_test::(); +} + +#[test] +fn test_sw6_fq() { + use crate::fields::sw6::Fq; + + let a: Fq = rand::random(); + let b: Fq = rand::random(); + field_test(a, b); + primefield_test::(); + sqrt_field_test(a); +} + +#[test] +fn test_sw6_fq3() { + use crate::fields::{ + sw6::{Fq, Fq3}, + PrimeField, + }; + + let a: Fq3 = rand::random(); + let b: Fq3 = rand::random(); + field_test(a, b); + sqrt_field_test(a); + frobenius_test::(Fq::characteristic().0, 13); +} + +#[test] +fn test_sw6_fq6() { + use crate::fields::{ + sw6::{Fq, Fq6}, + PrimeField, + }; + + let a: Fq6 = rand::random(); + let b: Fq6 = rand::random(); + field_test(a, b); + frobenius_test::(Fq::characteristic().0, 13); +} diff --git a/algebra/src/fields/tests.rs b/algebra/src/fields/tests.rs new file mode 100644 index 000000000..495224914 --- /dev/null +++ b/algebra/src/fields/tests.rs @@ -0,0 +1,352 @@ +use crate::fields::{Field, LegendreSymbol, PrimeField, SquareRootField}; +use rand::{Rng, SeedableRng, XorShiftRng}; + +pub const ITERATIONS: u32 = 40; + +fn random_negation_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + let a = F::rand(rng); + let mut b = -a; + b += &a; + + assert!(b.is_zero()); + } +} + +fn random_addition_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + let a = F::rand(rng); + let b = F::rand(rng); + let c = F::rand(rng); + + let t0 = (a + &b) + &c; // (a + b) + c + + let t1 = (a + &c) + &b; // (a + c) + b + + let t2 = (b + &c) + &a; // (b + c) + a + + assert_eq!(t0, t1); + assert_eq!(t1, t2); + } +} + +fn random_subtraction_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + let a = F::rand(rng); + let b = F::rand(rng); + + let t0 = a - &b; // (a - b) + + let mut t1 = b; // (b - a) + t1 -= &a; + + let mut t2 = t0; // (a - b) + (b - a) = 0 + t2 += &t1; + + assert!(t2.is_zero()); + } +} + +fn random_multiplication_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + let a = F::rand(rng); + let b = F::rand(rng); + let c = F::rand(rng); + + let mut t0 = a; // (a * b) * c + t0 *= &b; + t0 *= &c; + + let mut t1 = a; // (a * c) * b + t1 *= &c; + t1 *= &b; + + let mut t2 = b; // (b * c) * a + t2 *= &c; + t2 *= &a; + + assert_eq!(t0, t1); + assert_eq!(t1, t2); + } +} + +fn random_inversion_tests(rng: &mut R) { + assert!(F::zero().inverse().is_none()); + + for _ in 0..ITERATIONS { + let mut a = F::rand(rng); + let b = a.inverse().unwrap(); // probablistically nonzero + a *= &b; + + assert_eq!(a, F::one()); + } +} + +fn random_doubling_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + let mut a = F::rand(rng); + let mut b = a; + a += &b; + b.double_in_place(); + + assert_eq!(a, b); + } +} + +fn random_squaring_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + let mut a = F::rand(rng); + let mut b = a; + a *= &b; + b.square_in_place(); + + assert_eq!(a, b); + } +} + +fn random_expansion_tests(rng: &mut R) { + for _ in 0..ITERATIONS { + // Compare (a + b)(c + d) and (a*c + b*c + a*d + b*d) + + let a = F::rand(rng); + let b = F::rand(rng); + let c = F::rand(rng); + let d = F::rand(rng); + + let mut t0 = a; + t0 += &b; + let mut t1 = c; + t1 += &d; + t0 *= &t1; + + let mut t2 = a; + t2 *= &c; + let mut t3 = b; + t3 *= &c; + let mut t4 = a; + t4 *= &d; + let mut t5 = b; + t5 *= &d; + + t2 += &t3; + t2 += &t4; + t2 += &t5; + + assert_eq!(t0, t2); + } + + for _ in 0..ITERATIONS { + // Compare (a + b)c and (a*c + b*c) + + let a = F::rand(rng); + let b = F::rand(rng); + let c = F::rand(rng); + + let t0 = (a + &b) * &c; + let t2 = a * &c + &(b * &c); + + assert_eq!(t0, t2); + } +} + +fn random_field_tests() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + random_negation_tests::(&mut rng); + random_addition_tests::(&mut rng); + random_subtraction_tests::(&mut rng); + random_multiplication_tests::(&mut rng); + random_inversion_tests::(&mut rng); + random_doubling_tests::(&mut rng); + random_squaring_tests::(&mut rng); + random_expansion_tests::(&mut rng); + + assert!(F::zero().is_zero()); + { + let z = -F::zero(); + assert!(z.is_zero()); + } + + assert!(F::zero().inverse().is_none()); + + // Multiplication by zero + { + let a = F::rand(&mut rng) * &F::zero(); + assert!(a.is_zero()); + } + + // Addition by zero + { + let mut a = F::rand(&mut rng); + let copy = a; + a += &F::zero(); + assert_eq!(a, copy); + } +} + +fn random_sqrt_tests() { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let a = F::rand(&mut rng); + let b = a.square(); + assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue); + + let b = b.sqrt().unwrap(); + assert!(a == b || a == -b); + } + + let mut c = F::one(); + for _ in 0..ITERATIONS { + let mut b = c.square(); + assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue); + + b = b.sqrt().unwrap(); + + if b != c { + b = -b; + } + + assert_eq!(b, c); + + c += &F::one(); + } +} + +pub fn from_str_test() { + { + let a = "84395729384759238745923745892374598234705297301958723458712394587103249587213984572934750213947582345792304758273458972349582734958273495872304598234"; + let b = "38495729084572938457298347502349857029384609283450692834058293405982304598230458230495820394850293845098234059823049582309485203948502938452093482039"; + let c = "3248875134290623212325429203829831876024364170316860259933542844758450336418538569901990710701240661702808867062612075657861768196242274635305077449545396068598317421057721935408562373834079015873933065667961469731886739181625866970316226171512545167081793907058686908697431878454091011239990119126"; + + let mut a = F::from_str(a).map_err(|_| ()).unwrap(); + let b = F::from_str(b).map_err(|_| ()).unwrap(); + let c = F::from_str(c).map_err(|_| ()).unwrap(); + + a *= &b; + + assert_eq!(a, c); + } + + { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let n: u64 = rng.gen(); + + let a = F::from_str(&format!("{}", n)).map_err(|_| ()).unwrap(); + let b = F::from_repr(n.into()); + + assert_eq!(a, b); + } + } + + assert!(F::from_str("").is_err()); + assert!(F::from_str("0").map_err(|_| ()).unwrap().is_zero()); + assert!(F::from_str("00").is_err()); + assert!(F::from_str("00000000000").is_err()); +} + +pub fn field_test(a: F, b: F) { + let zero = F::zero(); + assert_eq!(zero, zero); + assert_eq!(zero.is_zero(), true); + assert_eq!(zero.is_one(), false); + + let one = F::one(); + assert_eq!(one, one); + assert_eq!(one.is_zero(), false); + assert_eq!(one.is_one(), true); + assert_eq!(zero + &one, one); + + let two = one + &one; + assert_eq!(two, two); + assert_ne!(zero, two); + assert_ne!(one, two); + + // a == a + assert_eq!(a, a); + // a + 0 = a + assert_eq!(a + &zero, a); + // a - 0 = a + assert_eq!(a - &zero, a); + // a - a = 0 + assert_eq!(a - &a, zero); + // 0 - a = -a + assert_eq!(zero - &a, -a); + // a.double() = a + a + assert_eq!(a.double(), a + &a); + // b.double() = b + b + assert_eq!(b.double(), b + &b); + // a + b = b + a + assert_eq!(a + &b, b + &a); + // a - b = -(b - a) + assert_eq!(a - &b, -(b - &a)); + // (a + b) + a = a + (b + a) + assert_eq!((a + &b) + &a, a + &(b + &a)); + // (a + b).double() = (a + b) + (b + a) + assert_eq!((a + &b).double(), (a + &b) + &(b + &a)); + + // a * 0 = 0 + assert_eq!(a * &zero, zero); + // a * 1 = a + assert_eq!(a * &one, a); + // a * 2 = a.double() + assert_eq!(a * &two, a.double()); + // a * a^-1 = 1 + assert_eq!(a * &a.inverse().unwrap(), one); + // a * a = a^2 + assert_eq!(a * &a, a.square()); + // a * a * a = a^3 + assert_eq!(a * &(a * &a), a.pow([0x3, 0x0, 0x0, 0x0])); + // a * b = b * a + assert_eq!(a * &b, b * &a); + // (a * b) * a = a * (b * a) + assert_eq!((a * &b) * &a, a * &(b * &a)); + // (a + b)^2 = a^2 + 2ab + b^2 + assert_eq!( + (a + &b).square(), + a.square() + &((a * &b) + &(a * &b)) + &b.square() + ); + // (a - b)^2 = (-(b - a))^2 + assert_eq!((a - &b).square(), (-(b - &a)).square()); + + random_field_tests::(); +} + +pub fn primefield_test() { + let one = F::one(); + assert_eq!(F::from_repr(one.into_repr()), one); + assert_eq!(F::from_str("1").ok().unwrap(), one); +} + +pub fn sqrt_field_test(elem: F) { + let square = elem.square(); + let sqrt = square.sqrt().unwrap(); + assert!(sqrt == elem || sqrt == -elem); + if let Some(sqrt) = elem.sqrt() { + assert!(sqrt.square() == elem || sqrt.square() == -elem); + } + random_sqrt_tests::(); +} + +pub fn frobenius_test>(characteristic: C, maxpower: usize) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + for _ in 0..ITERATIONS { + let a = F::rand(&mut rng); + + let mut a_0 = a; + a_0.frobenius_map(0); + assert_eq!(a, a_0); + + let mut a_q = a.pow(&characteristic); + for power in 1..maxpower { + let mut a_qi = a; + a_qi.frobenius_map(power); + assert_eq!(a_qi, a_q); + + a_q = a_q.pow(&characteristic); + } + } +} diff --git a/algebra/src/groups/mod.rs b/algebra/src/groups/mod.rs new file mode 100644 index 000000000..4fa3b9d31 --- /dev/null +++ b/algebra/src/groups/mod.rs @@ -0,0 +1,69 @@ +use crate::BitIterator; +use rand::Rand; +use std::{ + fmt::{Debug, Display}, + hash::Hash, + ops::{Add, AddAssign, Neg, Sub, SubAssign}, +}; + +use crate::{ + bytes::{FromBytes, ToBytes}, + fields::PrimeField, +}; + +#[cfg(test)] +pub mod tests; + +pub trait Group: + ToBytes + + FromBytes + + Copy + + Clone + + Debug + + Display + + Default + + Send + + Sync + + 'static + + Eq + + Hash + + Neg + + Rand + + for<'a> Add<&'a Self, Output = Self> + + for<'a> Sub<&'a Self, Output = Self> + + for<'a> AddAssign<&'a Self> + + for<'a> SubAssign<&'a Self> +{ + type ScalarField: PrimeField + Into<::BigInt>; + + /// Returns the additive identity. + fn zero() -> Self; + + /// Returns `self == zero`. + fn is_zero(&self) -> bool; + + /// Returns `self + self`. + #[must_use] + fn double(&self) -> Self; + + /// Sets `self := self + self`. + fn double_in_place(&mut self) -> &mut Self; + + #[must_use] + fn mul<'a>(&self, other: &'a Self::ScalarField) -> Self { + let mut copy = *self; + copy.mul_assign(other); + copy + } + + fn mul_assign<'a>(&mut self, other: &'a Self::ScalarField) { + let mut res = Self::zero(); + for i in BitIterator::new(other.into_repr()) { + res.double_in_place(); + if i { + res += self + } + } + *self = res + } +} diff --git a/algebra/src/groups/tests.rs b/algebra/src/groups/tests.rs new file mode 100644 index 000000000..0b52d487e --- /dev/null +++ b/algebra/src/groups/tests.rs @@ -0,0 +1,73 @@ +use super::Group; +use crate::fields::Field; +use rand::{Rand, SeedableRng, XorShiftRng}; + +pub fn group_test(a: G, mut b: G) { + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + let zero = G::zero(); + let fr_zero = G::ScalarField::zero(); + let fr_one = G::ScalarField::one(); + let fr_two = fr_one + &fr_one; + assert_eq!(zero, zero); + assert_eq!(zero.is_zero(), true); + assert_eq!(a.mul(&fr_one), a); + assert_eq!(a.mul(&fr_two), a + &a); + assert_eq!(a.mul(&fr_zero), zero); + assert_eq!(a.mul(&fr_zero) - &a, -a); + assert_eq!(a.mul(&fr_one) - &a, zero); + assert_eq!(a.mul(&fr_two) - &a, a); + + // a == a + assert_eq!(a, a); + // a + 0 = a + assert_eq!(a + &zero, a); + // a - 0 = a + assert_eq!(a - &zero, a); + // a - a = 0 + assert_eq!(a - &a, zero); + // 0 - a = -a + assert_eq!(zero - &a, -a); + // a.double() = a + a + assert_eq!(a.double(), a + &a); + // b.double() = b + b + assert_eq!(b.double(), b + &b); + // a + b = b + a + assert_eq!(a + &b, b + &a); + // a - b = -(b - a) + assert_eq!(a - &b, -(b - &a)); + // (a + b) + a = a + (b + a) + assert_eq!((a + &b) + &a, a + &(b + &a)); + // (a + b).double() = (a + b) + (b + a) + assert_eq!((a + &b).double(), (a + &b) + &(b + &a)); + + // Check that double_in_place and double give the same result + let original_b = b; + b.double_in_place(); + assert_eq!(original_b.double(), b); + + let fr_rand1 = G::ScalarField::rand(&mut rng); + let fr_rand2 = G::ScalarField::rand(&mut rng); + let a_rand1 = a.mul(&fr_rand1); + let a_rand2 = a.mul(&fr_rand2); + let fr_three = fr_two + &fr_rand1; + let a_two = a.mul(&fr_two); + assert_eq!(a_two, a.double(), "(a * 2) != a.double()"); + let a_six = a.mul(&(fr_three * &fr_two)); + assert_eq!(a_two.mul(&fr_three), a_six, "(a * 2) * 3 != a * (2 * 3)"); + + assert_eq!( + a_rand1.mul(&fr_rand2), + a_rand2.mul(&fr_rand1), + "(a * r1) * r2 != (a * r2) * r1" + ); + assert_eq!( + a_rand2.mul(&fr_rand1), + a.mul(&(fr_rand1 * &fr_rand2)), + "(a * r2) * r1 != a * (r1 * r2)" + ); + assert_eq!( + a_rand1.mul(&fr_rand2), + a.mul(&(fr_rand1 * &fr_rand2)), + "(a * r1) * r2 != a * (r1 * r2)" + ); +} diff --git a/algebra/src/lib.rs b/algebra/src/lib.rs new file mode 100644 index 000000000..027c06477 --- /dev/null +++ b/algebra/src/lib.rs @@ -0,0 +1,66 @@ +#![deny( + unused_import_braces, + unused_qualifications, + trivial_casts, + trivial_numeric_casts +)] +#![deny( + unused_qualifications, + variant_size_differences, + stable_features, + unreachable_pub +)] +#![deny( + non_shorthand_field_patterns, + unused_attributes, + unused_imports, + unused_extern_crates +)] +#![deny( + renamed_and_removed_lints, + stable_features, + unused_allocation, + unused_comparisons, + bare_trait_objects +)] +#![deny( + const_err, + unused_must_use, + unused_mut, + unused_unsafe, + private_in_public, + unsafe_code +)] +#![forbid(unsafe_code)] +#![feature(const_fn)] + +#[macro_use] +extern crate derivative; + +#[cfg_attr(test, macro_use)] +pub mod bytes; +pub use self::bytes::*; + +pub mod biginteger; +pub use self::biginteger::*; + +pub mod curves; +pub use self::curves::*; + +pub mod fields; +pub use self::fields::*; + +pub mod groups; +pub use self::groups::*; + +#[cfg(feature = "parallel")] +pub mod msm; +#[cfg(feature = "parallel")] +pub use self::msm::*; + +#[cfg(feature = "parallel")] +pub mod fft; +#[cfg(feature = "parallel")] +pub use self::fft::*; + +pub mod utils; diff --git a/algebra/src/msm/fixed_base.rs b/algebra/src/msm/fixed_base.rs new file mode 100644 index 000000000..6e1ec0308 --- /dev/null +++ b/algebra/src/msm/fixed_base.rs @@ -0,0 +1,80 @@ +use crate::{BigInteger, FpParameters, PairingEngine, PrimeField, ProjectiveCurve}; +use rayon::prelude::*; + +pub struct FixedBaseMSM; + +impl FixedBaseMSM { + pub fn get_mul_window_size(num_scalars: usize) -> usize { + if num_scalars < 32 { + 3 + } else { + (f64::from(num_scalars as u32)).ln().ceil() as usize + } + } + + pub fn get_window_table( + scalar_size: usize, + window: usize, + g: T, + ) -> Vec> { + let in_window = 1 << window; + let outerc = (scalar_size + window - 1) / window; + let last_in_window = 1 << (scalar_size - (outerc - 1) * window); + + let mut multiples_of_g = vec![vec![T::zero(); in_window]; outerc]; + + let mut gouter = g; + for outer in 0..outerc { + let mut ginner = T::zero(); + let cur_in_window = if outer == outerc - 1 { + last_in_window + } else { + in_window + }; + for inner in 0..cur_in_window { + multiples_of_g[outer][inner] = ginner; + ginner = ginner + &gouter; + } + for _ in 0..window { + gouter.double_in_place(); + } + } + multiples_of_g + } + + pub fn windowed_mul( + scalar_size: usize, + window: usize, + multiples_of_g: &Vec>, + scalar: &E::Fr, + ) -> T { + let outerc = (scalar_size + window - 1) / window; + let mut scalar_val = scalar.into_repr().to_bits(); + scalar_val.reverse(); + + let mut res = multiples_of_g[0][0]; + for outer in 0..outerc { + let mut inner = 0usize; + for i in 0..window { + if outer * window + i < (::Params::MODULUS_BITS as usize) + && scalar_val[outer * window + i] + { + inner |= 1 << i; + } + } + res = res + &multiples_of_g[outer][inner]; + } + res + } + + pub fn batch_mul( + scalar_size: usize, + window: usize, + table: &Vec>, + v: &Vec, + ) -> Vec { + v.par_iter() + .map(|e| Self::windowed_mul::(scalar_size, window, table, e)) + .collect::>() + } +} diff --git a/algebra/src/msm/mod.rs b/algebra/src/msm/mod.rs new file mode 100644 index 000000000..38576f5e7 --- /dev/null +++ b/algebra/src/msm/mod.rs @@ -0,0 +1,4 @@ +mod fixed_base; +mod variable_base; +pub use fixed_base::*; +pub use variable_base::*; diff --git a/algebra/src/msm/variable_base.rs b/algebra/src/msm/variable_base.rs new file mode 100644 index 000000000..920103276 --- /dev/null +++ b/algebra/src/msm/variable_base.rs @@ -0,0 +1,137 @@ +use crate::{ + AffineCurve, BigInteger, Field, FpParameters, PairingCurve, PairingEngine, PrimeField, + ProjectiveCurve, +}; +use rayon::prelude::*; + +pub struct VariableBaseMSM; + +impl VariableBaseMSM { + fn msm_inner( + bases: &[G], + scalars: &[<::Fr as PrimeField>::BigInt], + ) -> ::Projective { + assert_eq!(bases.len(), scalars.len()); + let c = if scalars.len() < 32 { + 3 + } else { + (f64::from(scalars.len() as u32)).ln().ceil() as usize + }; + + let num_bits = + <::Fr as PrimeField>::Params::MODULUS_BITS as usize; + let fr_one = ::Fr::one().into_repr(); + + let zero = G::zero().into_projective(); + let window_starts: Vec<_> = (0..num_bits).step_by(c).collect(); + + // Each window is of size `c`. + // We divide up the bits 0..num_bits into windows of size `c`, and + // in parallel process each such window. + let window_sums: Vec<_> = window_starts + .into_par_iter() + .map(|w_start| { + let mut res = zero; + // We don't need the "zero" bucket, so we only have 2^c - 1 buckets + let mut buckets = vec![zero; (1 << c) - 1]; + for (&scalar, base) in scalars.iter().zip(bases) { + if scalar.is_zero() { + continue; + } + if scalar == fr_one { + // We only process unit scalars once in the first window. + if w_start == 0 { + res.add_assign_mixed(base); + } + } else { + let mut scalar = scalar; + + // We right-shift by w_start, thus getting rid of the + // lower bits. + scalar.divn(w_start as u32); + + // We mod the remaining bits by the window size. + let scalar = scalar.as_ref()[0] % (1 << c); + + // If the scalar is non-zero, we update the corresponding + // bucket. + // (Recall that `buckets` doesn't have a zero bucket.) + if scalar != 0 { + buckets[(scalar - 1) as usize].add_assign_mixed(&base); + } else { + continue; + } + } + } + let mut running_sum = G::Projective::zero(); + for b in buckets.iter().rev() { + running_sum += &b; + res += &running_sum; + } + + res + }) + .collect(); + + // We store the sum for the lowest window. + let lowest = *window_sums.first().unwrap(); + + // We're traversing windows from high to low. + let num_windows = window_sums.len(); + let mut total = zero; + for i in (1..num_windows).rev() { + total += &window_sums[i]; + for _ in 0..c { + total.double_in_place(); + } + } + total + &lowest + } + + pub fn multi_scalar_mul( + bases: &[G], + scalars: &[<::Fr as PrimeField>::BigInt], + ) -> ::Projective { + Self::msm_inner(bases, scalars) + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::curves::bls12_381::Bls12_381; + use rand::{self, Rand, SeedableRng, XorShiftRng}; + + fn naive_var_base_msm( + bases: &[G], + scalars: &[::BigInt], + ) -> G::Projective { + assert_eq!(bases.len(), scalars.len()); + + let mut acc = G::Projective::zero(); + + for (base, scalar) in bases.iter().zip(scalars.iter()) { + acc += &base.mul(*scalar); + } + acc + } + + #[test] + fn test_with_bls12() { + const SAMPLES: usize = 1 << 10; + + let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); + + let v = (0..SAMPLES) + .map(|_| ::Fr::rand(&mut rng).into_repr()) + .collect::>(); + let g = (0..SAMPLES) + .map(|_| ::G1Projective::rand(&mut rng).into_affine()) + .collect::>(); + + let naive = naive_var_base_msm(g.as_slice(), v.as_slice()); + let fast = VariableBaseMSM::multi_scalar_mul(g.as_slice(), v.as_slice()); + + assert_eq!(naive.into_affine(), fast.into_affine()); + } +} diff --git a/algebra/src/utils.rs b/algebra/src/utils.rs new file mode 100644 index 000000000..52c7f69e7 --- /dev/null +++ b/algebra/src/utils.rs @@ -0,0 +1,144 @@ +use crate::{ + bytes::FromBytes, + curves::{ + models::{ModelParameters, SWModelParameters, TEModelParameters}, + short_weierstrass_jacobian::{GroupAffine as SWAffine, GroupProjective as SWProjective}, + twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective}, + ProjectiveCurve, + }, + Fp2, Fp2Parameters, FpParameters, PairingEngine, PrimeField, SquareRootField, +}; +use failure::Error; + +pub trait ToEngineFr { + fn to_engine_fr(&self) -> Result, Error>; +} + +// Impl for base field +impl> ToEngineFr for F +where + F: PrimeField + SquareRootField + Into<::BigInt>, +{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + Ok(vec![*self]) + } +} + +// Impl for base field +impl> ToEngineFr for [F] +where + F: PrimeField + SquareRootField + Into<::BigInt>, +{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + Ok(self.to_vec()) + } +} + +impl ToEngineFr for () { + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + Ok(Vec::new()) + } +} + +// Impl for Fp2 +impl> ToEngineFr for Fp2

{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + let mut c0 = >::to_engine_fr(&self.c0)?; + let c1 = >::to_engine_fr(&self.c1)?; + c0.extend_from_slice(&c1); + Ok(c0) + } +} + +impl ToEngineFr for TEAffine +where + E: PairingEngine, + M: TEModelParameters, + ::BaseField: ToEngineFr, +{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + let mut x_fe = self.x.to_engine_fr()?; + let y_fe = self.y.to_engine_fr()?; + x_fe.extend_from_slice(&y_fe); + Ok(x_fe) + } +} + +impl ToEngineFr for TEProjective +where + E: PairingEngine, + M: TEModelParameters, + ::BaseField: ToEngineFr, +{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + let affine = self.into_affine(); + let mut x_fe = affine.x.to_engine_fr()?; + let y_fe = affine.y.to_engine_fr()?; + x_fe.extend_from_slice(&y_fe); + Ok(x_fe) + } +} + +impl ToEngineFr for SWAffine +where + E: PairingEngine, + M: SWModelParameters, + ::BaseField: ToEngineFr, +{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + let mut x_fe = self.x.to_engine_fr()?; + let y_fe = self.y.to_engine_fr()?; + x_fe.extend_from_slice(&y_fe); + Ok(x_fe) + } +} + +impl ToEngineFr for SWProjective +where + E: PairingEngine, + M: SWModelParameters, + ::BaseField: ToEngineFr, +{ + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + let affine = self.into_affine(); + let mut x_fe = affine.x.to_engine_fr()?; + let y_fe = affine.y.to_engine_fr()?; + x_fe.extend_from_slice(&y_fe); + Ok(x_fe) + } +} + +impl ToEngineFr for [u8] { + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + let max_size = ::Params::CAPACITY / 8; + let max_size = max_size as usize; + let fes = self + .chunks(max_size) + .map(|chunk| { + let mut chunk = chunk.to_vec(); + let len = chunk.len(); + for _ in len..(max_size + 1) { + chunk.push(0u8); + } + E::Fr::read(chunk.as_slice()) + }) + .collect::, _>>()?; + Ok(fes) + } +} + +impl ToEngineFr for [u8; 32] { + #[inline] + fn to_engine_fr(&self) -> Result, Error> { + ToEngineFr::::to_engine_fr(self.as_ref()) + } +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..0527c73ba --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,13 @@ +reorder_imports = true +wrap_comments = true +normalize_comments = true +format_strings = true +struct_field_align_threshold = 40 +use_try_shorthand = true +match_block_trailing_comma = true +use_field_init_shorthand = true +edition = "2018" +condense_wildcard_suffixes = true +merge_imports = true +imports_layout = "Mixed" +unstable_features = true