Squashed 'jubjub/' content from commit 9987ddf

git-subtree-dir: jubjub
git-subtree-split: 9987ddf8d17a87bd2b14627665768e4038b657c4
This commit is contained in:
Sean Bowe 2019-12-12 11:32:47 -07:00
commit d029ddea83
34 changed files with 4035 additions and 0 deletions

95
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,95 @@
name: CI checks
on: [push, pull_request]
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.36.0
override: true
# Ensure all code has been formatted with rustfmt
- run: rustup component add rustfmt
- name: Check formatting
uses: actions-rs/cargo@v1
with:
command: fmt
args: -- --check --color always
test:
name: Test on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.36.0
override: true
- name: cargo fetch
uses: actions-rs/cargo@v1
with:
command: fetch
- name: Build tests
uses: actions-rs/cargo@v1
with:
command: build
args: --verbose --release --tests
- name: Run tests
uses: actions-rs/cargo@v1
with:
command: test
args: --verbose --release
no-std:
name: Check no-std compatibility
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.36.0
override: true
- run: rustup target add thumbv6m-none-eabi
- name: cargo fetch
uses: actions-rs/cargo@v1
with:
command: fetch
- name: Build
uses: actions-rs/cargo@v1
with:
command: build
args: --verbose --target thumbv6m-none-eabi --no-default-features
doc-links:
name: Nightly lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: nightly
override: true
- name: cargo fetch
uses: actions-rs/cargo@v1
with:
command: fetch
# Ensure intra-documentation links all resolve correctly
# Requires #![deny(intra_doc_link_resolution_failure)] in crate.
- name: Check intra-doc links
uses: actions-rs/cargo@v1
with:
command: doc
args: --document-private-items

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target
**/*.rs.bk
Cargo.lock

14
COPYRIGHT Normal file
View File

@ -0,0 +1,14 @@
Copyrights in the "jubjub" library are retained by their contributors. No
copyright assignment is required to contribute to the "jubjub" library.
The "jubjub" library is licensed under either of
* Apache License, Version 2.0, (see ./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license (see ./LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.

33
Cargo.toml Normal file
View File

@ -0,0 +1,33 @@
[package]
authors = [
"Sean Bowe <ewillbefull@gmail.com>",
"Eirik Ogilvie-Wigley <eowigley@gmail.com>",
"Jack Grigg <thestr4d@gmail.com>",
]
description = "Implementation of the Jubjub elliptic curve group"
documentation = "https://docs.rs/jubjub/"
homepage = "https://github.com/zkcrypto/jubjub"
license = "MIT/Apache-2.0"
name = "jubjub"
repository = "https://github.com/zkcrypto/jubjub"
version = "0.3.0"
edition = "2018"
[dependencies.bls12_381]
version = "0.1"
default-features = false
[dependencies.subtle]
version = "^2.2.1"
default-features = false
[dev-dependencies.rand_core]
version = "0.5"
default-features = false
[dev-dependencies.rand_xorshift]
version = "0.2"
default-features = false
[features]
default = []

201
LICENSE-APACHE Normal file
View File

@ -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.

23
LICENSE-MIT Normal file
View File

@ -0,0 +1,23 @@
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.

53
README.md Normal file
View File

@ -0,0 +1,53 @@
# jubjub [![Crates.io](https://img.shields.io/crates/v/jubjub.svg)](https://crates.io/crates/jubjub) #
<img
width="15%"
align="right"
src="https://raw.githubusercontent.com/zcash/zips/master/protocol/jubjub.png"/>
This is a pure Rust implementation of the Jubjub elliptic curve group and its associated fields.
* **This implementation has not been reviewed or audited. Use at your own risk.**
* This implementation targets Rust `1.36` or later.
* All operations are constant time unless explicitly noted.
* This implementation does not require the Rust standard library.
## [Documentation](https://docs.rs/jubjub)
## Curve Description
Jubjub is the [twisted Edwards curve](https://en.wikipedia.org/wiki/Twisted_Edwards_curve) `-u^2 + v^2 = 1 + d.u^2.v^2` of rational points over `GF(q)` with a subgroup of prime order `r` and cofactor `8`.
```
q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
r = 0x0e7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7
d = -(10240/10241)
```
The choice of `GF(q)` is made to be the scalar field of the BLS12-381 elliptic curve construction.
Jubjub is birationally equivalent to a [Montgomery curve](https://en.wikipedia.org/wiki/Montgomery_curve) `y^2 = x^3 + Ax^2 + x` over the same field with `A = 40962`. This value of `A` is the smallest integer such that `(A - 2) / 4` is a small integer, `A^2 - 4` is nonsquare in `GF(q)`, and the Montgomery curve and its quadratic twist have small cofactors `8` and `4`, respectively. This is identical to the relationship between Curve25519 and ed25519.
Please see [./doc/evidence/](./doc/evidence/) for supporting evidence that Jubjub meets the [SafeCurves](https://safecurves.cr.yp.to/index.html) criteria. The tool in [./doc/derive/](./doc/derive/) will derive the curve parameters via the above criteria to demonstrate rigidity.
## Acknowledgements
Jubjub was designed by Sean Bowe. Daira Hopwood is responsible for its name and specification. The security evidence in [./doc/evidence/](./doc/evidence/) is the product of Daira Hopwood and based on SafeCurves by Daniel J. Bernstein and Tanja Lange. Peter Newell and Daira Hopwood are responsible for the Jubjub bird image.
Please see `Cargo.toml` for a list of primary authors of this codebase.
## License
Licensed under either of
* 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)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.

24
RELEASES.md Normal file
View File

@ -0,0 +1,24 @@
# 0.3.0
This release now depends on the `bls12_381` crate, which exposes the `Fq` field type that we re-export.
* The `Fq` and `Fr` field types now have better constant function support for various operations and constructors.
* We no longer depend on the `byteorder` crate.
* We've bumped our `rand_core` dev-dependency up to 0.5.
* We've removed the `std` and `nightly` features.
* We've bumped our dependency of `subtle` up to `^2.2.1`.
# 0.2.0
This release switches to `subtle 2.1` to bring in the `CtOption` type, and also makes a few useful API changes.
* Implemented `Mul<Fr>` for `AffineNielsPoint` and `ExtendedNielsPoint`
* Changed `AffinePoint::to_niels()` to be a `const` function so that constant curve points can be constructed without statics.
* Implemented `multiply_bits` for `AffineNielsPoint`, `ExtendedNielsPoint`
* Removed `CtOption` and replaced it with `CtOption` from `subtle` crate.
* Modified receivers of some methods to reduce stack usage
* Changed various `into_bytes` methods into `to_bytes`
# 0.1.0
Initial release.

51
benches/fq_bench.rs Normal file
View File

@ -0,0 +1,51 @@
#![feature(test)]
extern crate test;
use jubjub::*;
use test::Bencher;
#[bench]
fn bench_mul_assign(bencher: &mut Bencher) {
let mut n = Fq::one();
let b = -Fq::one();
bencher.iter(move || {
n *= &b;
});
}
#[bench]
fn bench_sub_assign(bencher: &mut Bencher) {
let mut n = Fq::one();
let b = -Fq::one();
bencher.iter(move || {
n -= &b;
});
}
#[bench]
fn bench_add_assign(bencher: &mut Bencher) {
let mut n = Fq::one();
let b = -Fq::one();
bencher.iter(move || {
n += &b;
});
}
#[bench]
fn bench_square_assign(bencher: &mut Bencher) {
let n = Fq::one();
bencher.iter(move || n.square());
}
#[bench]
fn bench_invert(bencher: &mut Bencher) {
let n = Fq::one();
bencher.iter(move || n.invert());
}
#[bench]
fn bench_sqrt(bencher: &mut Bencher) {
let n = Fq::one().double().double();
bencher.iter(move || n.sqrt());
}

51
benches/fr_bench.rs Normal file
View File

@ -0,0 +1,51 @@
#![feature(test)]
extern crate test;
use jubjub::*;
use test::Bencher;
#[bench]
fn bench_mul_assign(bencher: &mut Bencher) {
let mut n = Fr::one();
let b = -Fr::one();
bencher.iter(move || {
n *= &b;
});
}
#[bench]
fn bench_sub_assign(bencher: &mut Bencher) {
let mut n = Fr::one();
let b = -Fr::one();
bencher.iter(move || {
n -= &b;
});
}
#[bench]
fn bench_add_assign(bencher: &mut Bencher) {
let mut n = Fr::one();
let b = -Fr::one();
bencher.iter(move || {
n += &b;
});
}
#[bench]
fn bench_square_assign(bencher: &mut Bencher) {
let n = Fr::one();
bencher.iter(move || n.square());
}
#[bench]
fn bench_invert(bencher: &mut Bencher) {
let n = Fr::one();
bencher.iter(move || n.invert());
}
#[bench]
fn bench_sqrt(bencher: &mut Bencher) {
let n = Fr::one().double().double();
bencher.iter(move || n.sqrt());
}

58
benches/point_bench.rs Normal file
View File

@ -0,0 +1,58 @@
#![feature(test)]
extern crate test;
use jubjub::*;
use test::Bencher;
// Non-Niels
#[bench]
fn bench_point_doubling(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
bencher.iter(move || a.double());
}
#[bench]
fn bench_point_addition(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
let b = -ExtendedPoint::identity();
bencher.iter(move || a + b);
}
#[bench]
fn bench_point_subtraction(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
let b = -ExtendedPoint::identity();
bencher.iter(move || a + b);
}
// Niels
#[bench]
fn bench_cached_point_addition(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
let b = ExtendedPoint::identity().to_niels();
bencher.iter(move || &a + &b);
}
#[bench]
fn bench_cached_affine_point_subtraction(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
let b = AffinePoint::identity().to_niels();
bencher.iter(move || &a + &b);
}
#[bench]
fn bench_cached_point_subtraction(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
let b = ExtendedPoint::identity().to_niels();
bencher.iter(move || &a + &b);
}
#[bench]
fn bench_cached_affine_point_addition(bencher: &mut Bencher) {
let a = ExtendedPoint::identity();
let b = AffinePoint::identity().to_niels();
bencher.iter(move || &a + &b);
}

1
doc/derive/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sage.py

32
doc/derive/derive.sage Normal file
View File

@ -0,0 +1,32 @@
q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
Fq = GF(q)
# We wish to find a Montgomery curve with B = 1 and A the smallest such
# that (A - 2) / 4 is a small integer.
def get_A(n):
return (n * 4) + 2
# A = 2 is invalid (singular curve), so we start at i = 1 (A = 6)
i = 1
while True:
A = Fq(get_A(i))
i = i + 1
# We also want that A^2 - 4 is nonsquare.
if ((A^2) - 4).is_square():
continue
ec = EllipticCurve(Fq, [0, A, 0, 1, 0])
o = ec.order()
if (o % 8 == 0):
o = o // 8
if is_prime(o):
twist = ec.quadratic_twist()
otwist = twist.order()
if (otwist % 4 == 0):
otwist = otwist // 4
if is_prime(otwist):
print "A = %s" % A
exit(0)

102
doc/evidence/.gitignore vendored Normal file
View File

@ -0,0 +1,102 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv
venv/
ENV/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/

19
doc/evidence/LICENSE Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2017 The Zcash developers
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.

28
doc/evidence/README.md Normal file
View File

@ -0,0 +1,28 @@
Jubjub supporting evidence
--------------------------
This repository contains supporting evidence that the twisted Edwards curve
-x^2 + y^2 = 1 - (10240/10241).x^2.y^2 of rational points over
GF(52435875175126190479447740508185965837690552500527637822603658699938581184513),
[also called "Jubjub"](https://z.cash/technology/jubjub.html),
satisfies the [SafeCurves criteria](https://safecurves.cr.yp.to/index.html).
The script ``verify.sage`` is based on
[this script from the SafeCurves site](https://safecurves.cr.yp.to/verify.html),
modified
* to support twisted Edwards curves;
* to generate a file 'primes' containing the primes needed for primality proofs,
if it is not already present;
* to change the directory in which Pocklington proof files are generated
(``proof/`` rather than ``../../../proof``), and to create that directory
if it does not exist.
Prerequisites:
* apt-get install sagemath
* pip install sortedcontainers
Run ``sage verify.sage .``, or ``./run.sh`` to also print out the results.
Note that the "rigidity" criterion cannot be checked automatically.

1
doc/evidence/a Normal file
View File

@ -0,0 +1 @@
-1

1
doc/evidence/d Normal file
View File

@ -0,0 +1 @@
19257038036680949359750312669786877991949435402254120286184196891950884077233

1
doc/evidence/l Normal file
View File

@ -0,0 +1 @@
6554484396890773809930967563523245729705921265872317281365359162392183254199

1
doc/evidence/p Normal file
View File

@ -0,0 +1 @@
52435875175126190479447740508185965837690552500527637822603658699938581184513

1
doc/evidence/rigid Normal file
View File

@ -0,0 +1 @@
fully rigid

4
doc/evidence/run.sh Normal file
View File

@ -0,0 +1,4 @@
#!/bin/sh
sage verify.sage .
grep -Rn '.' verify-* |grep '^verify-.*:1:' |sed 's/:1:/ = /'

1
doc/evidence/shape Normal file
View File

@ -0,0 +1 @@
tedwards

444
doc/evidence/verify.sage Normal file
View File

@ -0,0 +1,444 @@
import os
import sys
from errno import ENOENT, EEXIST
from sortedcontainers import SortedSet
def readfile(fn):
fd = open(fn,'r')
r = fd.read()
fd.close()
return r
def writefile(fn,s):
fd = open(fn,'w')
fd.write(s)
fd.close()
def expand2(n):
s = ""
while n != 0:
j = 16
while 2**j < abs(n): j += 1
if 2**j - abs(n) > abs(n) - 2**(j-1): j -= 1
if abs(abs(n) - 2**j) > 2**(j - 10):
if n > 0:
if s != "": s += " + "
s += str(n)
else:
s += " - " + str(-n)
n = 0
elif n > 0:
if s != "": s += " + "
s += "2^" + str(j)
n -= 2**j
else:
s += " - 2^" + str(j)
n += 2**j
return s
def requirement(fn,istrue):
writefile(fn,str(istrue) + '\n')
return istrue
def verify():
try:
os.mkdir('proof')
except OSError as e:
if e.errno != EEXIST: raise
try:
s = set(map(Integer, readfile('primes').split()))
except IOError, e:
if e.errno != ENOENT: raise
s = set()
needtofactor = SortedSet()
V = SortedSet() # distinct verified primes
verify_primes(V, s, needtofactor)
verify_pass(V, needtofactor)
old = V
needtofactor.update(V)
while len(needtofactor) > len(old):
k = len(needtofactor) - len(old)
sys.stdout.write('Factoring %d integer%s' % (k, '' if k == 1 else 's'))
sys.stdout.flush()
for x in needtofactor:
if x not in old:
for (y, z) in factor(x):
s.add(y)
sys.stdout.write('.')
sys.stdout.flush()
print('')
old = needtofactor.copy()
verify_primes(V, s, needtofactor)
writefile('primes', '\n'.join(map(str, s)) + '\n')
writefile('verify-primes', '<html><body>\n' +
''.join(('2\n' if v == 2 else
'<a href=proof/%s.html>%s</a>\n' % (v,v)) for v in V) +
'</body></html>\n')
verify_pass(V, needtofactor)
def verify_primes(V, s, needtofactor):
for n in sorted(s):
if not n.is_prime() or n in V: continue
needtofactor.add(n-1)
if n == 2:
V.add(n)
continue
for trybase in primes(2,10000):
base = Integers(n)(trybase)
if base^(n-1) != 1: continue
proof = 'Primality proof for n = %s:\n' % n
proof += '<p>Take b = %s.\n' % base
proof += '<p>b^(n-1) mod n = 1.\n'
f = factor(1)
for v in reversed(V):
if f.prod()^2 <= n:
if n % v == 1:
u = base^((n-1)/v)-1
if u.is_unit():
if v == 2:
proof += '<p>2 is prime.\n'
else:
proof += '<p><a href=%s.html>%s is prime.</a>\n' % (v,v)
proof += '<br>b^((n-1)/%s)-1 mod n = %s, which is a unit, inverse %s.\n' % (v,u,1/u)
f *= factor(v)^(n-1).valuation(v)
if f.prod()^2 <= n: continue
if n % f.prod() != 1: continue
proof += '<p>(%s) divides n-1.\n' % f
proof += '<p>(%s)^2 > n.\n' % f
proof += "<p>n is prime by Pocklington's theorem.\n"
proof += '\n'
writefile('proof/%s.html' % n,proof)
V.add(n)
break
def verify_pass(V, needtofactor):
p = Integer(readfile('p'))
k = GF(p)
kz.<z> = k[]
l = Integer(readfile('l'))
x0 = Integer(readfile('x0'))
y0 = Integer(readfile('y0'))
x1 = Integer(readfile('x1'))
y1 = Integer(readfile('y1'))
shape = readfile('shape').strip()
rigid = readfile('rigid').strip()
safefield = True
safeeq = True
safebase = True
saferho = True
safetransfer = True
safedisc = True
saferigid = True
safeladder = True
safetwist = True
safecomplete = True
safeind = True
pstatus = 'Unverified'
if not p.is_prime(): pstatus = 'False'
needtofactor.add(p)
if p in V: pstatus = 'True'
if pstatus != 'True': safefield = False
writefile('verify-pisprime',pstatus + '\n')
pstatus = 'Unverified'
if not l.is_prime(): pstatus = 'False'
needtofactor.add(l)
if l in V: pstatus = 'True'
if pstatus != 'True': safebase = False
writefile('verify-lisprime',pstatus + '\n')
writefile('expand2-p','= %s\n' % expand2(p))
writefile('expand2-l','<br>= %s\n' % expand2(l))
writefile('hex-p',hex(p) + '\n')
writefile('hex-l',hex(l) + '\n')
writefile('hex-x0',hex(x0) + '\n')
writefile('hex-x1',hex(x1) + '\n')
writefile('hex-y0',hex(y0) + '\n')
writefile('hex-y1',hex(y1) + '\n')
gcdlpis1 = gcd(l,p) == 1
safetransfer &= requirement('verify-gcdlp1',gcdlpis1)
writefile('verify-movsafe','Unverified\n')
writefile('verify-embeddingdegree','Unverified\n')
if gcdlpis1 and l.is_prime():
u = Integers(l)(p)
d = l-1
needtofactor.add(d)
for v in V:
while d % v == 0: d /= v
if d == 1:
d = l-1
for v in V:
while d % v == 0:
if u^(d/v) != 1: break
d /= v
safetransfer &= requirement('verify-movsafe',(l-1)/d <= 100)
writefile('verify-embeddingdegree','<font size=1>%s</font><br>= (l-1)/%s\n' % (d,(l-1)/d))
t = p+1-l*round((p+1)/l)
if l^2 > 16*p:
writefile('verify-trace','%s\n' % t)
f = factor(1)
d = (p+1-t)/l
needtofactor.add(d)
for v in V:
while d % v == 0:
d //= v
f *= factor(v)
writefile('verify-cofactor','%s\n' % f)
else:
writefile('verify-trace','Unverified\n')
writefile('verify-cofactor','Unverified\n')
D = t^2-4*p
needtofactor.add(D)
for v in V:
while D % v^2 == 0: D /= v^2
if prod([v for v in V if D % v == 0]) != -D:
writefile('verify-disc','Unverified\n')
writefile('verify-discisbig','Unverified\n')
safedisc = False
else:
f = -prod([factor(v) for v in V if D % v == 0])
if D % 4 != 1:
D *= 4
f = factor(4) * f
Dbits = (log(-D)/log(2)).numerical_approx()
writefile('verify-disc','<font size=1>%s</font><br>= <font size=1>%s</font><br>&#x2248; -2^%.1f\n' % (D,f,Dbits))
safedisc &= requirement('verify-discisbig',D < -2^100)
pi4 = 0.78539816339744830961566084581987572105
rho = log(pi4*l)/log(4)
writefile('verify-rho','%.1f\n' % rho)
saferho &= requirement('verify-rhoabove100',rho.numerical_approx() >= 100)
twistl = 'Unverified'
d = p+1+t
needtofactor.add(d)
for v in V:
while d % v == 0: d /= v
if d == 1:
d = p+1+t
for v in V:
if d % v == 0:
if twistl == 'Unverified' or v > twistl: twistl = v
writefile('verify-twistl','%s\n' % twistl)
writefile('verify-twistembeddingdegree','Unverified\n')
writefile('verify-twistmovsafe','Unverified\n')
if twistl == 'Unverified':
writefile('hex-twistl','Unverified\n')
writefile('expand2-twistl','Unverified\n')
writefile('verify-twistcofactor','Unverified\n')
writefile('verify-gcdtwistlp1','Unverified\n')
writefile('verify-twistrho','Unverified\n')
safetwist = False
else:
writefile('hex-twistl',hex(twistl) + '\n')
writefile('expand2-twistl','<br>= %s\n' % expand2(twistl))
f = factor(1)
d = (p+1+t)/twistl
needtofactor.add(d)
for v in V:
while d % v == 0:
d //= v
f *= factor(v)
writefile('verify-twistcofactor','%s\n' % f)
gcdtwistlpis1 = gcd(twistl,p) == 1
safetwist &= requirement('verify-gcdtwistlp1',gcdtwistlpis1)
movsafe = 'Unverified'
embeddingdegree = 'Unverified'
if gcdtwistlpis1 and twistl.is_prime():
u = Integers(twistl)(p)
d = twistl-1
needtofactor.add(d)
for v in V:
while d % v == 0: d /= v
if d == 1:
d = twistl-1
for v in V:
while d % v == 0:
if u^(d/v) != 1: break
d /= v
safetwist &= requirement('verify-twistmovsafe',(twistl-1)/d <= 100)
writefile('verify-twistembeddingdegree',"<font size=1>%s</font><br>= (l'-1)/%s\n" % (d,(twistl-1)/d))
rho = log(pi4*twistl)/log(4)
writefile('verify-twistrho','%.1f\n' % rho)
safetwist &= requirement('verify-twistrhoabove100',rho.numerical_approx() >= 100)
precomp = 0
joint = l
needtofactor.add(p+1-t)
needtofactor.add(p+1+t)
for v in V:
d1 = p+1-t
d2 = p+1+t
while d1 % v == 0 or d2 % v == 0:
if d1 % v == 0: d1 //= v
if d2 % v == 0: d2 //= v
# best case for attack: cyclic; each power is usable
# also assume that kangaroo is as efficient as rho
if v + sqrt(pi4*joint/v) < sqrt(pi4*joint):
precomp += v
joint /= v
rho = log(precomp + sqrt(pi4 * joint))/log(2)
writefile('verify-jointrho','%.1f\n' % rho)
safetwist &= requirement('verify-jointrhoabove100',rho.numerical_approx() >= 100)
x0 = k(x0)
y0 = k(y0)
x1 = k(x1)
y1 = k(y1)
if shape in ('edwards', 'tedwards'):
d = Integer(readfile('d'))
a = 1
if shape == 'tedwards':
a = Integer(readfile('a'))
writefile('verify-shape','Twisted Edwards\n')
writefile('verify-equation','%sx^2+y^2 = 1%+dx^2y^2\n' % (a, d))
if a == 1:
writefile('verify-shape','Edwards\n')
writefile('verify-equation','x^2+y^2 = 1%+dx^2y^2\n' % d)
a = k(a)
d = k(d)
elliptic = a*d*(a-d)
level0 = a*x0^2+y0^2-1-d*x0^2*y0^2
level1 = a*x1^2+y1^2-1-d*x1^2*y1^2
if shape == 'montgomery':
writefile('verify-shape','Montgomery\n')
A = Integer(readfile('A'))
B = Integer(readfile('B'))
equation = '%sy^2 = x^3<wbr>%+dx^2+x' % (B,A)
if B == 1:
equation = 'y^2 = x^3<wbr>%+dx^2+x' % A
writefile('verify-equation',equation + '\n')
A = k(A)
B = k(B)
elliptic = B*(A^2-4)
level0 = B*y0^2-x0^3-A*x0^2-x0
level1 = B*y1^2-x1^3-A*x1^2-x1
if shape == 'shortw':
writefile('verify-shape','short Weierstrass\n')
a = Integer(readfile('a'))
b = Integer(readfile('b'))
writefile('verify-equation','y^2 = x^3<wbr>%+dx<wbr>%+d\n' % (a,b))
a = k(a)
b = k(b)
elliptic = 4*a^3+27*b^2
level0 = y0^2-x0^3-a*x0-b
level1 = y1^2-x1^3-a*x1-b
writefile('verify-elliptic',str(elliptic) + '\n')
safeeq &= requirement('verify-iselliptic',elliptic != 0)
safebase &= requirement('verify-isoncurve0',level0 == 0)
safebase &= requirement('verify-isoncurve1',level1 == 0)
if shape in ('edwards', 'tedwards'):
A = 2*(a+d)/(a-d)
B = 4/(a-d)
x0,y0 = (1+y0)/(1-y0),((1+y0)/(1-y0))/x0
x1,y1 = (1+y1)/(1-y1),((1+y1)/(1-y1))/x1
shape = 'montgomery'
if shape == 'montgomery':
a = (3-A^2)/(3*B^2)
b = (2*A^3-9*A)/(27*B^3)
x0,y0 = (x0+A/3)/B,y0/B
x1,y1 = (x1+A/3)/B,y1/B
shape = 'shortw'
try:
E = EllipticCurve([a,b])
numorder2 = 0
numorder4 = 0
for P in E(0).division_points(4):
if P != 0 and 2*P == 0:
numorder2 += 1
if 2*P != 0 and 4*P == 0:
numorder4 += 1
writefile('verify-numorder2',str(numorder2) + '\n')
writefile('verify-numorder4',str(numorder4) + '\n')
completesingle = False
completemulti = False
if numorder4 == 2 and numorder2 == 1:
# complete edwards form, and montgomery with unique point of order 2
completesingle = True
completemulti = True
# should extend this to allow complete twisted hessian
safecomplete &= requirement('verify-completesingle',completesingle)
safecomplete &= requirement('verify-completemulti',completemulti)
safecomplete &= requirement('verify-ltimesbase1is0',l * E([x1,y1]) == 0)
writefile('verify-ltimesbase1',str(l * E([x1,y1])) + '\n')
writefile('verify-cofactorbase01',str(((p+1-t)//l) * E([x0,y0]) == E([x1,y1])) + '\n')
except:
writefile('verify-numorder2','Unverified\n')
writefile('verify-numorder4','Unverified\n')
writefile('verify-ltimesbase1','Unverified\n')
writefile('verify-cofactorbase01','Unverified\n')
safecomplete = False
montladder = False
for r,e in (z^3+a*z+b).roots():
if (3*r^2+a).is_square():
montladder = True
safeladder &= requirement('verify-montladder',montladder)
indistinguishability = False
elligator2 = False
if (p+1-t) % 2 == 0:
if b != 0:
indistinguishability = True
elligator2 = True
safeind &= requirement('verify-indistinguishability',indistinguishability)
writefile('verify-ind-notes','Elligator 2: %s.\n' % ['No','Yes'][elligator2])
saferigid &= (rigid == 'fully rigid' or rigid == 'somewhat rigid')
safecurve = True
safecurve &= requirement('verify-safefield',safefield)
safecurve &= requirement('verify-safeeq',safeeq)
safecurve &= requirement('verify-safebase',safebase)
safecurve &= requirement('verify-saferho',saferho)
safecurve &= requirement('verify-safetransfer',safetransfer)
safecurve &= requirement('verify-safedisc',safedisc)
safecurve &= requirement('verify-saferigid',saferigid)
safecurve &= requirement('verify-safeladder',safeladder)
safecurve &= requirement('verify-safetwist',safetwist)
safecurve &= requirement('verify-safecomplete',safecomplete)
safecurve &= requirement('verify-safeind',safeind)
requirement('verify-safecurve',safecurve)
originaldir = os.open('.',os.O_RDONLY)
for i in range(1,len(sys.argv)):
os.fchdir(originaldir)
os.chdir(sys.argv[i])
verify()

1
doc/evidence/x0 Normal file
View File

@ -0,0 +1 @@
11076627216317271660298050606127911965867021807910416450833192264015104452986

1
doc/evidence/x1 Normal file
View File

@ -0,0 +1 @@
8076246640662884909881801758704306714034609987455869804520522091855516602923

1
doc/evidence/y0 Normal file
View File

@ -0,0 +1 @@
44412834903739585386157632289020980010620626017712148233229312325549216099227

1
doc/evidence/y1 Normal file
View File

@ -0,0 +1 @@
13262374693698910701929044844600465831413122818447359594527400194675274060458

1023
src/fr.rs Normal file

File diff suppressed because it is too large Load Diff

1323
src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

174
src/util.rs Normal file
View File

@ -0,0 +1,174 @@
/// Compute a + b + carry, returning the result and the new carry over.
#[inline(always)]
pub const fn adc(a: u64, b: u64, carry: u64) -> (u64, u64) {
let ret = (a as u128) + (b as u128) + (carry as u128);
(ret as u64, (ret >> 64) as u64)
}
/// Compute a - (b + borrow), returning the result and the new borrow.
#[inline(always)]
pub const fn sbb(a: u64, b: u64, borrow: u64) -> (u64, u64) {
let ret = (a as u128).wrapping_sub((b as u128) + ((borrow >> 63) as u128));
(ret as u64, (ret >> 64) as u64)
}
/// Compute a + (b * c) + carry, returning the result and the new carry over.
#[inline(always)]
pub const fn mac(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) {
let ret = (a as u128) + ((b as u128) * (c as u128)) + (carry as u128);
(ret as u64, (ret >> 64) as u64)
}
macro_rules! impl_add_binop_specify_output {
($lhs:ident, $rhs:ident, $output:ident) => {
impl<'b> Add<&'b $rhs> for $lhs {
type Output = $output;
#[inline]
fn add(self, rhs: &'b $rhs) -> $output {
&self + rhs
}
}
impl<'a> Add<$rhs> for &'a $lhs {
type Output = $output;
#[inline]
fn add(self, rhs: $rhs) -> $output {
self + &rhs
}
}
impl Add<$rhs> for $lhs {
type Output = $output;
#[inline]
fn add(self, rhs: $rhs) -> $output {
&self + &rhs
}
}
};
}
macro_rules! impl_sub_binop_specify_output {
($lhs:ident, $rhs:ident, $output:ident) => {
impl<'b> Sub<&'b $rhs> for $lhs {
type Output = $output;
#[inline]
fn sub(self, rhs: &'b $rhs) -> $output {
&self - rhs
}
}
impl<'a> Sub<$rhs> for &'a $lhs {
type Output = $output;
#[inline]
fn sub(self, rhs: $rhs) -> $output {
self - &rhs
}
}
impl Sub<$rhs> for $lhs {
type Output = $output;
#[inline]
fn sub(self, rhs: $rhs) -> $output {
&self - &rhs
}
}
};
}
macro_rules! impl_binops_additive_specify_output {
($lhs:ident, $rhs:ident, $output:ident) => {
impl_add_binop_specify_output!($lhs, $rhs, $output);
impl_sub_binop_specify_output!($lhs, $rhs, $output);
};
}
macro_rules! impl_binops_multiplicative_mixed {
($lhs:ident, $rhs:ident, $output:ident) => {
impl<'b> Mul<&'b $rhs> for $lhs {
type Output = $output;
#[inline]
fn mul(self, rhs: &'b $rhs) -> $output {
&self * rhs
}
}
impl<'a> Mul<$rhs> for &'a $lhs {
type Output = $output;
#[inline]
fn mul(self, rhs: $rhs) -> $output {
self * &rhs
}
}
impl Mul<$rhs> for $lhs {
type Output = $output;
#[inline]
fn mul(self, rhs: $rhs) -> $output {
&self * &rhs
}
}
};
}
macro_rules! impl_binops_additive {
($lhs:ident, $rhs:ident) => {
impl_binops_additive_specify_output!($lhs, $rhs, $lhs);
impl SubAssign<$rhs> for $lhs {
#[inline]
fn sub_assign(&mut self, rhs: $rhs) {
*self = &*self - &rhs;
}
}
impl AddAssign<$rhs> for $lhs {
#[inline]
fn add_assign(&mut self, rhs: $rhs) {
*self = &*self + &rhs;
}
}
impl<'b> SubAssign<&'b $rhs> for $lhs {
#[inline]
fn sub_assign(&mut self, rhs: &'b $rhs) {
*self = &*self - rhs;
}
}
impl<'b> AddAssign<&'b $rhs> for $lhs {
#[inline]
fn add_assign(&mut self, rhs: &'b $rhs) {
*self = &*self + rhs;
}
}
};
}
macro_rules! impl_binops_multiplicative {
($lhs:ident, $rhs:ident) => {
impl_binops_multiplicative_mixed!($lhs, $rhs, $lhs);
impl MulAssign<$rhs> for $lhs {
#[inline]
fn mul_assign(&mut self, rhs: $rhs) {
*self = &*self * &rhs;
}
}
impl<'b> MulAssign<&'b $rhs> for $lhs {
#[inline]
fn mul_assign(&mut self, rhs: &'b $rhs) {
*self = &*self * rhs;
}
}
};
}

29
tests/common.rs Normal file
View File

@ -0,0 +1,29 @@
use jubjub::*;
use rand_core::{RngCore, SeedableRng};
use rand_xorshift::XorShiftRng;
pub const NUM_BLACK_BOX_CHECKS: u32 = 2000;
pub fn new_rng() -> XorShiftRng {
XorShiftRng::from_seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
}
pub trait MyRandom {
fn new_random<T: RngCore>(rng: &mut T) -> Self;
}
impl MyRandom for Fq {
fn new_random<T: RngCore>(rng: &mut T) -> Self {
let mut random_bytes = [0u8; 64];
rng.fill_bytes(&mut random_bytes);
Fq::from_bytes_wide(&random_bytes)
}
}
impl MyRandom for Fr {
fn new_random<T: RngCore>(rng: &mut T) -> Self {
let mut random_bytes = [0u8; 64];
rng.fill_bytes(&mut random_bytes);
Fr::from_bytes_wide(&random_bytes)
}
}

120
tests/fq_blackbox.rs Normal file
View File

@ -0,0 +1,120 @@
mod common;
use common::{new_rng, MyRandom, NUM_BLACK_BOX_CHECKS};
use jubjub::*;
#[test]
fn test_to_and_from_bytes() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
assert_eq!(a, Fq::from_bytes(&Fq::to_bytes(&a)).unwrap());
}
}
#[test]
fn test_additive_associativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
let b = Fq::new_random(&mut rng);
let c = Fq::new_random(&mut rng);
assert_eq!((a + b) + c, a + (b + c))
}
}
#[test]
fn test_additive_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
assert_eq!(a, a + Fq::zero());
assert_eq!(a, Fq::zero() + a);
}
}
#[test]
fn test_subtract_additive_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
assert_eq!(a, a - Fq::zero());
assert_eq!(a, Fq::zero() - -&a);
}
}
#[test]
fn test_additive_inverse() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
let a_neg = -&a;
assert_eq!(Fq::zero(), a + a_neg);
assert_eq!(Fq::zero(), a_neg + a);
}
}
#[test]
fn test_additive_commutativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
let b = Fq::new_random(&mut rng);
assert_eq!(a + b, b + a);
}
}
#[test]
fn test_multiplicative_associativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
let b = Fq::new_random(&mut rng);
let c = Fq::new_random(&mut rng);
assert_eq!((a * b) * c, a * (b * c))
}
}
#[test]
fn test_multiplicative_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
assert_eq!(a, a * Fq::one());
assert_eq!(a, Fq::one() * a);
}
}
#[test]
fn test_multiplicative_inverse() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
if a == Fq::zero() {
continue;
}
let a_inv = a.invert().unwrap();
assert_eq!(Fq::one(), a * a_inv);
assert_eq!(Fq::one(), a_inv * a);
}
}
#[test]
fn test_multiplicative_commutativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
let b = Fq::new_random(&mut rng);
assert_eq!(a * b, b * a);
}
}
#[test]
fn test_multiply_additive_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fq::new_random(&mut rng);
assert_eq!(Fq::zero(), Fq::zero() * a);
assert_eq!(Fq::zero(), a * Fq::zero());
}
}

120
tests/fr_blackbox.rs Normal file
View File

@ -0,0 +1,120 @@
mod common;
use common::{new_rng, MyRandom, NUM_BLACK_BOX_CHECKS};
use jubjub::*;
#[test]
fn test_to_and_from_bytes() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
assert_eq!(a, Fr::from_bytes(&Fr::to_bytes(&a)).unwrap());
}
}
#[test]
fn test_additive_associativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
let b = Fr::new_random(&mut rng);
let c = Fr::new_random(&mut rng);
assert_eq!((a + b) + c, a + (b + c))
}
}
#[test]
fn test_additive_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
assert_eq!(a, a + Fr::zero());
assert_eq!(a, Fr::zero() + a);
}
}
#[test]
fn test_subtract_additive_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
assert_eq!(a, a - Fr::zero());
assert_eq!(a, Fr::zero() - -&a);
}
}
#[test]
fn test_additive_inverse() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
let a_neg = -&a;
assert_eq!(Fr::zero(), a + a_neg);
assert_eq!(Fr::zero(), a_neg + a);
}
}
#[test]
fn test_additive_commutativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
let b = Fr::new_random(&mut rng);
assert_eq!(a + b, b + a);
}
}
#[test]
fn test_multiplicative_associativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
let b = Fr::new_random(&mut rng);
let c = Fr::new_random(&mut rng);
assert_eq!((a * b) * c, a * (b * c))
}
}
#[test]
fn test_multiplicative_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
assert_eq!(a, a * Fr::one());
assert_eq!(a, Fr::one() * a);
}
}
#[test]
fn test_multiplicative_inverse() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
if a == Fr::zero() {
continue;
}
let a_inv = a.invert().unwrap();
assert_eq!(Fr::one(), a * a_inv);
assert_eq!(Fr::one(), a_inv * a);
}
}
#[test]
fn test_multiplicative_commutativity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
let b = Fr::new_random(&mut rng);
assert_eq!(a * b, b * a);
}
}
#[test]
fn test_multiply_additive_identity() {
let mut rng = new_rng();
for _ in 0..NUM_BLACK_BOX_CHECKS {
let a = Fr::new_random(&mut rng);
assert_eq!(Fr::zero(), Fr::zero() * a);
assert_eq!(Fr::zero(), a * Fr::zero());
}
}