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