├── .github
├── CODEOWNERS
├── PULL_REQUEST_TEMPLATE.md
├── linters
│ ├── .markdown-lint.yml
│ └── .markdownlint.yml
└── workflows
│ ├── ci.yml
│ ├── linkify_changelog.yml
│ └── mdlinter.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── crypto-primitives
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── benches
│ ├── comm.rs
│ ├── crh.rs
│ ├── merkle_tree.rs
│ ├── prf.rs
│ └── signature.rs
└── src
│ ├── commitment
│ ├── blake2s
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── constraints.rs
│ ├── injective_map
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── mod.rs
│ └── pedersen
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── crh
│ ├── bowe_hopwood
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── constraints.rs
│ ├── injective_map
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── mod.rs
│ ├── pedersen
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── poseidon
│ │ ├── constraints.rs
│ │ └── mod.rs
│ └── sha256
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── encryption
│ ├── constraints.rs
│ ├── elgamal
│ │ ├── constraints.rs
│ │ └── mod.rs
│ └── mod.rs
│ ├── lib.rs
│ ├── macros.rs
│ ├── merkle_tree
│ ├── constraints.rs
│ ├── mod.rs
│ └── tests
│ │ ├── constraints.rs
│ │ ├── mod.rs
│ │ └── test_utils.rs
│ ├── prf
│ ├── blake2s
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── constraints.rs
│ └── mod.rs
│ ├── signature
│ ├── constraints.rs
│ ├── mod.rs
│ └── schnorr
│ │ ├── constraints.rs
│ │ └── mod.rs
│ ├── snark
│ ├── constraints.rs
│ └── mod.rs
│ └── sponge
│ ├── absorb.rs
│ ├── constraints
│ ├── absorb.rs
│ └── mod.rs
│ ├── merlin
│ └── mod.rs
│ ├── mod.rs
│ ├── poseidon
│ ├── constraints.rs
│ ├── grain_lfsr.rs
│ ├── mod.rs
│ ├── tests.rs
│ └── traits.rs
│ └── test.rs
├── macros
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
└── src
│ └── lib.rs
└── scripts
└── linkify_changelog.py
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @arkworks-rs/maintainers
2 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
6 |
7 | ## Description
8 |
9 |
12 |
13 | closes: #XXXX
14 |
15 | ---
16 |
17 | Before we can merge this PR, please make sure that all the following items have been
18 | checked off. If any of the checklist items are not applicable, please leave them but
19 | write a little note why.
20 |
21 | - [ ] Targeted PR against correct branch (main)
22 | - [ ] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work.
23 | - [ ] Wrote unit tests
24 | - [ ] Updated relevant documentation in the code
25 | - [ ] Added a relevant changelog entry to the `Pending` section in `CHANGELOG.md`
26 | - [ ] Re-reviewed `Files changed` in the Github PR explorer
27 |
--------------------------------------------------------------------------------
/.github/linters/.markdown-lint.yml:
--------------------------------------------------------------------------------
1 | # See https://github.com/DavidAnson/markdownlint#rules--aliases for list of markdown lint codes
2 | default: true
3 | # MD01 lint blocks having header's incrementing by more than # at a time.
4 | MD001: false
5 | MD007: { indent: 4 }
6 | # MD013 blocks long lines
7 | MD013: false
8 | MD024: { siblings_only: true }
9 | MD025: false
10 | # MD033 lint blocks HTML in MD
11 | MD033: false
12 | # MD036 no-emphasis-as-heading
13 | MD036: false
14 | MD041: false
15 |
--------------------------------------------------------------------------------
/.github/linters/.markdownlint.yml:
--------------------------------------------------------------------------------
1 | # See https://github.com/DavidAnson/markdownlint#rules--aliases for list of markdown lint codes
2 | default: true
3 | # MD01 lint blocks having header's incrementing by more than # at a time.
4 | MD001: false
5 | MD007: { indent: 4 }
6 | # MD013 blocks long lines
7 | MD013: false
8 | MD024: { siblings_only: true }
9 | MD025: false
10 | # MD033 lint blocks HTML in MD
11 | MD033: false
12 | # MD036 no-emphasis-as-heading
13 | MD036: false
14 | MD041: false
15 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | merge_group:
4 | pull_request:
5 | push:
6 | branches:
7 | - master
8 | env:
9 | RUST_BACKTRACE: 1
10 |
11 | jobs:
12 | style:
13 | name: Check Style
14 | runs-on: ubuntu-latest
15 | steps:
16 |
17 | - name: Checkout
18 | uses: actions/checkout@v1
19 | - name: Install Rust
20 | uses: actions-rs/toolchain@v1
21 | with:
22 | profile: minimal
23 | toolchain: stable
24 | override: true
25 | components: rustfmt
26 |
27 | - name: cargo fmt --check
28 | uses: actions-rs/cargo@v1
29 | with:
30 | command: fmt
31 | args: --all -- --check
32 |
33 | test:
34 | name: Test
35 | runs-on: ubuntu-latest
36 | env:
37 | RUSTFLAGS: -Dwarnings
38 | strategy:
39 | matrix:
40 | rust:
41 | - stable
42 | - nightly
43 | steps:
44 | - name: Checkout
45 | uses: actions/checkout@v2
46 |
47 | - name: Install Rust (${{ matrix.rust }})
48 | uses: actions-rs/toolchain@v1
49 | with:
50 | profile: minimal
51 | toolchain: ${{ matrix.rust }}
52 | override: true
53 |
54 | - uses: actions/cache@v4
55 | with:
56 | path: |
57 | ~/.cargo/registry
58 | ~/.cargo/git
59 | target
60 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
61 |
62 | - name: Check examples
63 | uses: actions-rs/cargo@v1
64 | with:
65 | command: check
66 | args: --examples --all
67 |
68 | - name: Check examples with all features on stable
69 | uses: actions-rs/cargo@v1
70 | with:
71 | command: check
72 | args: --examples --all-features --all
73 | if: matrix.rust == 'stable'
74 |
75 | - name: Check benchmarks on nightly
76 | uses: actions-rs/cargo@v1
77 | with:
78 | command: check
79 | args: --all-features --examples --all --benches
80 | if: matrix.rust == 'nightly'
81 |
82 | - name: Test
83 | uses: actions-rs/cargo@v1
84 | with:
85 | command: test
86 | args: "--all \
87 | --all-features \
88 | --exclude cp-benches "
89 |
90 | check_no_std:
91 | name: Check no_std
92 | runs-on: ubuntu-latest
93 | steps:
94 | - name: Checkout
95 | uses: actions/checkout@v2
96 |
97 | - name: Install Rust
98 | uses: actions-rs/toolchain@v1
99 | with:
100 | toolchain: stable
101 | target: thumbv6m-none-eabi
102 | override: true
103 |
104 | - name: Install Rust ARM64
105 | uses: actions-rs/toolchain@v1
106 | with:
107 | toolchain: stable
108 | target: aarch64-unknown-none
109 | override: true
110 |
111 | - uses: actions/cache@v4
112 | with:
113 | path: |
114 | ~/.cargo/registry
115 | ~/.cargo/git
116 | target
117 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
118 |
119 | - name: crypto-primitives
120 | run: |
121 | cargo build --no-default-features --features=r1cs,merkle_tree,prf,encryption,signature,snark --target aarch64-unknown-none
122 | cargo check --all --no-default-features --features=r1cs,merkle_tree,prf,encryption,signature,snark --target aarch64-unknown-none
123 |
--------------------------------------------------------------------------------
/.github/workflows/linkify_changelog.yml:
--------------------------------------------------------------------------------
1 | name: Linkify Changelog
2 |
3 | on:
4 | workflow_dispatch
5 |
6 | jobs:
7 | linkify:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - name: Checkout
11 | uses: actions/checkout@v2
12 | - name: Add links
13 | run: python3 scripts/linkify_changelog.py CHANGELOG.md
14 | - name: Commit
15 | run: |
16 | git config user.name github-actions
17 | git config user.email github-actions@github.com
18 | git add .
19 | git commit -m "Linkify Changelog"
20 | git push
--------------------------------------------------------------------------------
/.github/workflows/mdlinter.yml:
--------------------------------------------------------------------------------
1 | name: Lint
2 | on:
3 | merge_group:
4 | branches: [master, main]
5 | push:
6 | branches: [master, main]
7 | pull_request:
8 | branches: [master, main]
9 |
10 | ###############
11 | # Set the Job #
12 | ###############
13 | jobs:
14 | build:
15 | # Name the Job
16 | name: Lint Code Base
17 | # Set the agent to run on
18 | runs-on: ubuntu-latest
19 |
20 | ##################
21 | # Load all steps #
22 | ##################
23 | steps:
24 | ##########################
25 | # Checkout the code base #
26 | ##########################
27 | - name: Checkout Code
28 | uses: actions/checkout@v4
29 | with:
30 | # Full git history is needed to get a proper list of changed files within `super-linter`
31 | fetch-depth: 0
32 |
33 | ################################
34 | # Run Linter against code base #
35 | ################################
36 | - name: Lint Code Base
37 | uses: github/super-linter/slim@v4
38 | env:
39 | VALIDATE_ALL_CODEBASE: false
40 | DEFAULT_BRANCH: master
41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
42 | VALIDATE_PROTOBUF: false
43 | VALIDATE_JSCPD: false
44 | # use Python Pylint as the only linter to avoid conflicts
45 | VALIDATE_PYTHON_BLACK: false
46 | VALIDATE_PYTHON_FLAKE8: false
47 | VALIDATE_PYTHON_ISORT: false
48 | VALIDATE_PYTHON_MYPY: false
49 | VALIDATE_YAML: false
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 | Cargo.lock
3 | .DS_Store
4 | .idea
5 | *.iml
6 | *.ipynb_checkpoints
7 | *.pyc
8 | *.sage.py
9 | params
10 | *.swp
11 | *.swo
12 | .vscode
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # CHANGELOG
2 |
3 | ## Pending
4 |
5 | ### Breaking changes
6 |
7 | ### Features
8 |
9 | ### Improvements
10 |
11 | ### Bugfixes
12 |
13 | ## v0.5.0
14 |
15 | - [\#120](https://github.com/arkworks-rs/crypto-primitives/pull/120) Add input size check to `bowe_hopwood::CRHGadget::evaluate`.
16 |
17 | ### Breaking changes
18 |
19 | ### Features
20 |
21 | - [\#107](https://github.com/arkworks-rs/crypto-primitives/pull/107) Impl `CanonicalSerialize` and `CanonicalDeserialize` for `ark_crypto_primitives::crh::pedersen::Parameters`
22 |
23 | ### Improvements
24 |
25 | ### Bugfixes
26 |
27 | ## v0.4.0
28 |
29 | ### Breaking changes
30 |
31 | - [\#56](https://github.com/arkworks-rs/crypto-primitives/pull/56) Compress the output of the Bowe-Hopwood-Pedersen CRH to a single field element, in line with the Zcash specification.
32 | - [\#60](https://github.com/arkworks-rs/crypto-primitives/pull/60) Merkle tree's `Config` requires a user-defined converter to turn leaf hash output to inner hash output.
33 | - [\#60](https://github.com/arkworks-rs/crypto-primitives/pull/60) Rename the CRH trait as `CRHScheme` and the CRHGadget trait to `CRHSchemeGadget`.
34 | - [\#60](https://github.com/arkworks-rs/crypto-primitives/pull/60) Use `ark-sponge` to instantiate Poseidon.
35 | - [\#76](https://github.com/arkworks-rs/crypto-primitives/pull/79) Fix Pedersen padding bug.
36 | - [\#77](https://github.com/arkworks-rs/crypto-primitives/pull/77) Implement SHA-256 CRH.
37 | - [\#86](https://github.com/arkworks-rs/crypto-primitives/pull/86)
38 | - Moves `ark-sponge` here.
39 | - Updates dependencies and version number to `0.4`.
40 | - Adds feature flags to enable downstream users to select exactly those components that they're interested in.
41 | - [\#103](https://github.com/arkworks-rs/crypto-primitives/pull/103) Removes `cp-benches` and moves contents to `benches`
42 | - [\#104](https://github.com/arkworks-rs/crypto-primitives/pull/104) Updates `digest`, `blake2`, `sha2` to `0.10`. Changes API for `Blake2sWithParameterBlock`.
43 |
44 | ### Features
45 |
46 | - [\#59](https://github.com/arkworks-rs/crypto-primitives/pull/59) Implement `TwoToOneCRHScheme` for Bowe-Hopwood CRH.
47 | - [\#60](https://github.com/arkworks-rs/crypto-primitives/pull/60) Merkle tree no longer requires CRH to input and output bytes. Leaf can be any raw input of CRH, such as field elements.
48 | - [\#67](https://github.com/arkworks-rs/crypto-primitives/pull/67) User can access or replace leaf index variable in `PathVar`.
49 |
50 | ### Improvements
51 |
52 | ### Bugfixes
53 |
54 | ## v0.3.0
55 |
56 | ### Breaking changes
57 |
58 | - [\#30](https://github.com/arkworks-rs/crypto-primitives/pull/30) Refactor the Merkle tree to separate the leaf hash and two-to-one hash.
59 |
60 | ### Features
61 |
62 | - [\#38](https://github.com/arkworks-rs/crypto-primitives/pull/38) Add a signature verification trait `SigVerifyGadget`.
63 | - [\#44](https://github.com/arkworks-rs/crypto-primitives/pull/44) Add basic ElGamal encryption gadgets.
64 | - [\#48](https://github.com/arkworks-rs/crypto-primitives/pull/48) Add `CanonicalSerialize` and `CanonicalDeserialize` to `Path` and `CRH` outputs.
65 |
66 | ### Improvements
67 |
68 | ### Bugfixes
69 |
70 | ## v0.2.0
71 |
72 | ### Breaking changes
73 |
74 | ### Features
75 |
76 | - [\#2](https://github.com/arkworks-rs/crypto-primitives/pull/2) Add the `SNARK` gadget traits.
77 | - [\#3](https://github.com/arkworks-rs/crypto-primitives/pull/3) Add unchecked allocation for `ProofVar` and `VerifyingKeyVar`.
78 | - [\#4](https://github.com/arkworks-rs/crypto-primitives/pull/4) Add `verifier_size` to `SNARKGadget`.
79 | - [\#6](https://github.com/arkworks-rs/crypto-primitives/pull/6) Add `IntoIterator` for SNARK input gadgets.
80 | - [\#28](https://github.com/arkworks-rs/crypto-primitives/pull/28) Adds Poseidon CRH w/ constraints.
81 |
82 | ### Improvements
83 |
84 | ### Bugfixes
85 |
86 | ## v0.1.0 (Initial release of arkworks/crypto-primitives)
87 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | members = [
3 | "crypto-primitives",
4 | "macros",
5 | ]
6 | resolver = "2"
7 |
8 | [workspace.package]
9 | version = "0.5.0"
10 | authors = [ "arkworks contributors" ]
11 | description = "A library of useful cryptographic primitives"
12 | homepage = "https://arkworks.rs"
13 | repository = "https://github.com/arkworks-rs/crypto-primitives"
14 | documentation = "https://docs.rs/ark-crypto-primitives/"
15 | keywords = [ "r1cs", "pedersen", "blake2s", "snark", "schnorr" ]
16 | categories = ["cryptography"]
17 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
18 | license = "MIT/Apache-2.0"
19 | edition = "2021"
20 |
21 | [profile.release]
22 | opt-level = 3
23 | lto = "thin"
24 | incremental = true
25 | panic = 'abort'
26 |
27 | [profile.bench]
28 | opt-level = 3
29 | debug = false
30 | rpath = false
31 | lto = "thin"
32 | incremental = true
33 | debug-assertions = false
34 |
35 | [profile.dev]
36 | opt-level = 0
37 | panic = 'abort'
38 |
39 | [profile.test]
40 | opt-level = 3
41 | lto = "thin"
42 | incremental = true
43 | debug-assertions = true
44 | debug = true
45 |
46 | # [patch.crates-io]
47 | # ark-r1cs-std = { git = "https://github.com/arkworks-rs/r1cs-std/" }
48 | # ark-ff = { git = "https://github.com/arkworks-rs/algebra/" }
49 | # ark-ec = { git = "https://github.com/arkworks-rs/algebra/" }
50 | # ark-poly = { git = "https://github.com/arkworks-rs/algebra/" }
51 | # ark-serialize = { git = "https://github.com/arkworks-rs/algebra/" }
52 | # ark-std = { git = "https://github.com/arkworks-rs/std/" }
53 |
54 | # ark-ed-on-bls12-377 = { git = "https://github.com/arkworks-rs/algebra/" }
55 | # ark-ed-on-bls12-381 = { git = "https://github.com/arkworks-rs/algebra/" }
56 | # ark-bls12-377 = { git = "https://github.com/arkworks-rs/algebra/" }
57 | # ark-mnt4-298 = { git = "https://github.com/arkworks-rs/algebra/" }
58 | # ark-mnt6-298 = { git = "https://github.com/arkworks-rs/algebra/" }
59 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
ark-crypto-primitives
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | The arkworks ecosystem consist of Rust libraries for designing and working with __zero knowledge succinct non-interactive arguments (zkSNARKs)__. This repository contains efficient implementations of cryptographic primitives such as collision-resistant hash functions, hiding commitments, pseudo-random functions, signatures, and, optionally, R1CS constraints for these.
11 |
12 | This library is released under the MIT License and the Apache v2 License (see [License](#license)).
13 |
14 | **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.
15 |
16 | ## Build guide
17 |
18 | The library compiles on the `stable` toolchain of the Rust compiler. To install the latest version of Rust, first install `rustup` by following the instructions [here](https://rustup.rs/), or via your platform's package manager. Once `rustup` is installed, install the Rust toolchain by invoking:
19 |
20 | ```bash
21 | rustup install stable
22 | ```
23 |
24 | After that, use `cargo`, the standard Rust build tool, to build the library:
25 |
26 | ```bash
27 | git clone https://github.com/arkworks-rs/crypto-primitives.git
28 | cargo build --release
29 | ```
30 |
31 | This library comes with unit tests for each of the provided crates. Run the tests with:
32 |
33 | ```bash
34 | cargo test
35 | ```
36 |
37 | ## License
38 |
39 | This library is licensed under either of the following licenses, at your discretion.
40 |
41 | * Apache License Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or [apache.org license link](http://www.apache.org/licenses/LICENSE-2.0))
42 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or [opensource.org license link](http://opensource.org/licenses/MIT))
43 |
44 | Unless you explicitly state otherwise, any contribution submitted for inclusion in this library by you shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions.
45 |
46 | ## Acknowledgements
47 |
48 | This work was supported by:
49 | a Google Faculty Award;
50 | the National Science Foundation;
51 | the UC Berkeley Center for Long-Term Cybersecurity;
52 | and donations from the Ethereum Foundation, the Interchain Foundation, and Qtum.
53 |
54 | An earlier version of this library was developed as part of the paper *"[ZEXE: Enabling Decentralized Private Computation][zexe]"*.
55 |
56 | [zexe]: https://ia.cr/2018/962
57 |
--------------------------------------------------------------------------------
/crypto-primitives/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "ark-crypto-primitives"
3 | description.workspace = true
4 | documentation.workspace = true
5 | keywords.workspace = true
6 | version.workspace = true
7 | authors.workspace = true
8 | homepage.workspace = true
9 | repository.workspace = true
10 | categories.workspace = true
11 | include.workspace = true
12 | license.workspace = true
13 | edition.workspace = true
14 |
15 | ################################# Dependencies ################################
16 |
17 | [dependencies]
18 | ark-crypto-primitives-macros = { version = "0.5.0", path = "../macros" }
19 |
20 | ark-ff = { version = "0.5.0", default-features = false }
21 | ark-ec = { version = "0.5.0", default-features = false }
22 | ark-std = { version = "0.5.0", default-features = false }
23 | ark-relations = { version = "0.5.0", default-features = false }
24 | ark-serialize = { version = "0.5.0", default-features = false, features = [ "derive" ] }
25 |
26 | blake2 = { version = "0.10", default-features = false }
27 | sha2 = { version = "0.10", default-features = false }
28 | digest = { version = "0.10", default-features = false }
29 | merlin = { version = "3.0.0", default-features = false, optional = true }
30 |
31 | ark-r1cs-std = { version = "0.5.0", optional = true, default-features = false }
32 | ark-snark = { version = "0.5.0", default-features = false }
33 |
34 | rayon = { version = "1.0", optional = true }
35 | derivative = { version = "2.0", features = ["use_core"] }
36 | tracing = { version = "0.1", default-features = false, features = [ "attributes" ], optional = true }
37 | hashbrown = { version = "0.14", default-features = false, features = ["inline-more", "allocator-api2"], optional = true }
38 |
39 | [features]
40 | default = ["std"]
41 | std = [ "ark-ff/std", "ark-ec/std", "ark-std/std", "ark-relations/std" ]
42 | print-trace = [ "ark-std/print-trace" ]
43 | parallel = [ "std", "rayon", "ark-ec/parallel", "ark-std/parallel", "ark-ff/parallel" ]
44 | r1cs = [ "ark-r1cs-std", "tracing" ]
45 | crh = [ "sponge" ]
46 | sponge = [ "merlin" ]
47 | commitment = [ "crh" ]
48 | merkle_tree = ["crh", "hashbrown"]
49 | encryption = []
50 | prf = []
51 | snark = []
52 | signature = []
53 | asm = [ "ark-ff/asm" ]
54 |
55 | [target.'cfg(all(target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr"))'.dependencies]
56 | ahash = { version = "0.8", default-features = false}
57 |
58 | [target.'cfg(not(all(target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr")))'.dependencies]
59 | fnv = { version = "1.0", default-features = false }
60 |
61 | [dev-dependencies]
62 | ark-ed-on-bls12-377 = { version = "0.5.0", default-features = false }
63 | ark-ed-on-bls12-381 = { version = "0.5.0", default-features = false, features = [ "r1cs" ] }
64 | ark-bls12-377 = { version = "0.5.0", default-features = false, features = [ "curve", "r1cs" ] }
65 | ark-mnt4-298 = { version = "0.5.0", default-features = false, features = [ "curve", "r1cs" ] }
66 | ark-mnt6-298 = { version = "0.5.0", default-features = false, features = [ "r1cs" ] }
67 | criterion = { version = "0.5" }
68 |
69 | ################################# Benchmarks ##################################
70 |
71 | [[bench]]
72 | name = "pedersen_crh"
73 | path = "benches/crh.rs"
74 | harness = false
75 | required-features = [ "crh" ]
76 |
77 | [[bench]]
78 | name = "pedersen_comm"
79 | path = "benches/comm.rs"
80 | harness = false
81 | required-features = [ "commitment" ]
82 |
83 | [[bench]]
84 | name = "blake2s_prf"
85 | path = "benches/prf.rs"
86 | harness = false
87 | required-features = [ "prf" ]
88 |
89 | [[bench]]
90 | name = "schnorr_sig"
91 | path = "benches/signature.rs"
92 | harness = false
93 | required-features = [ "signature" ]
94 |
95 | [[bench]]
96 | name = "merkle_tree"
97 | path = "benches/merkle_tree.rs"
98 | harness = false
99 | required-features = [ "merkle_tree" ]
100 |
--------------------------------------------------------------------------------
/crypto-primitives/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | ../LICENSE-APACHE
--------------------------------------------------------------------------------
/crypto-primitives/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | ../LICENSE-MIT
--------------------------------------------------------------------------------
/crypto-primitives/benches/comm.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate criterion;
3 |
4 | use ark_crypto_primitives::commitment::{pedersen::*, CommitmentScheme};
5 | use ark_ed_on_bls12_377::EdwardsProjective as Edwards;
6 | use ark_std::UniformRand;
7 | use criterion::Criterion;
8 |
9 | #[derive(Clone, PartialEq, Eq, Hash)]
10 | pub struct CommWindow;
11 |
12 | impl Window for CommWindow {
13 | const WINDOW_SIZE: usize = 250;
14 | const NUM_WINDOWS: usize = 8;
15 | }
16 |
17 | fn pedersen_comm_setup(c: &mut Criterion) {
18 | c.bench_function("Pedersen Commitment Setup", move |b| {
19 | b.iter(|| {
20 | let mut rng = &mut ark_std::test_rng();
21 | Commitment::::setup(&mut rng).unwrap()
22 | })
23 | });
24 | }
25 |
26 | fn pedersen_comm_eval(c: &mut Criterion) {
27 | let mut rng = &mut ark_std::test_rng();
28 | let parameters = Commitment::::setup(&mut rng).unwrap();
29 | let input = vec![5u8; 128];
30 | c.bench_function("Pedersen Commitment Eval", move |b| {
31 | b.iter(|| {
32 | let rng = &mut ark_std::test_rng();
33 | let commitment_randomness = Randomness::rand(rng);
34 | Commitment::::commit(¶meters, &input, &commitment_randomness)
35 | .unwrap()
36 | })
37 | });
38 | }
39 |
40 | criterion_group! {
41 | name = comm_setup;
42 | config = Criterion::default().sample_size(10);
43 | targets = pedersen_comm_setup
44 | }
45 |
46 | criterion_group! {
47 | name = comm_eval;
48 | config = Criterion::default().sample_size(10);
49 | targets = pedersen_comm_eval
50 | }
51 |
52 | criterion_main!(comm_setup, comm_eval);
53 |
--------------------------------------------------------------------------------
/crypto-primitives/benches/crh.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate criterion;
3 |
4 | use ark_crypto_primitives::crh::{
5 | pedersen::{Window, CRH as PedersenCRH},
6 | CRHScheme,
7 | };
8 | use ark_ed_on_bls12_377::EdwardsProjective as Edwards;
9 | use criterion::Criterion;
10 |
11 | #[derive(Clone, PartialEq, Eq, Hash)]
12 | pub struct HashWindow;
13 |
14 | impl Window for HashWindow {
15 | const WINDOW_SIZE: usize = 250;
16 | const NUM_WINDOWS: usize = 8;
17 | }
18 |
19 | fn pedersen_crh_setup(c: &mut Criterion) {
20 | c.bench_function("Pedersen CRH Setup", move |b| {
21 | b.iter(|| {
22 | let mut rng = &mut ark_std::test_rng();
23 | PedersenCRH::::setup(&mut rng).unwrap()
24 | })
25 | });
26 | }
27 |
28 | fn pedersen_crh_eval(c: &mut Criterion) {
29 | let mut rng = &mut ark_std::test_rng();
30 | let parameters = PedersenCRH::::setup(&mut rng).unwrap();
31 | let input = vec![5u8; 128];
32 | c.bench_function("Pedersen CRH Eval", move |b| {
33 | b.iter(|| PedersenCRH::::evaluate(¶meters, input.clone()).unwrap())
34 | });
35 | }
36 |
37 | criterion_group! {
38 | name = crh_setup;
39 | config = Criterion::default().sample_size(10);
40 | targets = pedersen_crh_setup
41 | }
42 |
43 | criterion_group! {
44 | name = crh_eval;
45 | config = Criterion::default().sample_size(10);
46 | targets = pedersen_crh_eval
47 | }
48 |
49 | criterion_main!(crh_setup, crh_eval);
50 |
--------------------------------------------------------------------------------
/crypto-primitives/benches/merkle_tree.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate criterion;
3 |
4 | static NUM_LEAVES: i32 = 1 << 20;
5 |
6 | mod bytes_mt_benches {
7 | use ark_crypto_primitives::crh::*;
8 | use ark_crypto_primitives::merkle_tree::*;
9 | use ark_crypto_primitives::to_uncompressed_bytes;
10 | use ark_ff::BigInteger256;
11 | use ark_serialize::CanonicalSerialize;
12 | use ark_std::{test_rng, UniformRand};
13 | use criterion::Criterion;
14 | use std::borrow::Borrow;
15 | use std::iter::zip;
16 |
17 | use crate::NUM_LEAVES;
18 |
19 | type LeafH = sha2::Sha256;
20 | type CompressH = sha2::Sha256;
21 |
22 | struct Sha256MerkleTreeParams;
23 |
24 | impl Config for Sha256MerkleTreeParams {
25 | type Leaf = [u8];
26 |
27 | type LeafDigest = ::Output;
28 | type LeafInnerDigestConverter = ByteDigestConverter;
29 | type InnerDigest = ::Output;
30 |
31 | type LeafHash = LeafH;
32 | type TwoToOneHash = CompressH;
33 | }
34 | type Sha256MerkleTree = MerkleTree;
35 |
36 | pub fn merkle_tree_create(c: &mut Criterion) {
37 | let mut rng = test_rng();
38 | let leaves: Vec<_> = (0..NUM_LEAVES)
39 | .map(|_| {
40 | let rnd = BigInteger256::rand(&mut rng);
41 | to_uncompressed_bytes!(rnd).unwrap()
42 | })
43 | .collect();
44 | let leaf_crh_params = ::setup(&mut rng).unwrap();
45 | let two_to_one_params = ::setup(&mut rng)
46 | .unwrap()
47 | .clone();
48 | c.bench_function("Merkle Tree Create (Leaves as [u8])", move |b| {
49 | b.iter(|| {
50 | Sha256MerkleTree::new(
51 | &leaf_crh_params.clone(),
52 | &two_to_one_params.clone(),
53 | &leaves,
54 | )
55 | .unwrap();
56 | })
57 | });
58 | }
59 |
60 | pub fn merkle_tree_generate_proof(c: &mut Criterion) {
61 | let mut rng = test_rng();
62 | let leaves: Vec<_> = (0..NUM_LEAVES)
63 | .map(|_| {
64 | let rnd = BigInteger256::rand(&mut rng);
65 | to_uncompressed_bytes!(rnd).unwrap()
66 | })
67 | .collect();
68 | let leaf_crh_params = ::setup(&mut rng).unwrap();
69 | let two_to_one_params = ::setup(&mut rng)
70 | .unwrap()
71 | .clone();
72 |
73 | let tree = Sha256MerkleTree::new(
74 | &leaf_crh_params.clone(),
75 | &two_to_one_params.clone(),
76 | &leaves,
77 | )
78 | .unwrap();
79 | c.bench_function("Merkle Tree Generate Proof (Leaves as [u8])", move |b| {
80 | b.iter(|| {
81 | for (i, _) in leaves.iter().enumerate() {
82 | tree.generate_proof(i).unwrap();
83 | }
84 | })
85 | });
86 | }
87 |
88 | pub fn merkle_tree_verify_proof(c: &mut Criterion) {
89 | let mut rng = test_rng();
90 | let leaves: Vec<_> = (0..NUM_LEAVES)
91 | .map(|_| {
92 | let rnd = BigInteger256::rand(&mut rng);
93 | to_uncompressed_bytes!(rnd).unwrap()
94 | })
95 | .collect();
96 | let leaf_crh_params = ::setup(&mut rng).unwrap();
97 | let two_to_one_params = ::setup(&mut rng)
98 | .unwrap()
99 | .clone();
100 |
101 | let tree = Sha256MerkleTree::new(
102 | &leaf_crh_params.clone(),
103 | &two_to_one_params.clone(),
104 | &leaves,
105 | )
106 | .unwrap();
107 |
108 | let root = tree.root();
109 |
110 | let proofs: Vec<_> = leaves
111 | .iter()
112 | .enumerate()
113 | .map(|(i, _)| tree.generate_proof(i).unwrap())
114 | .collect();
115 |
116 | c.bench_function("Merkle Tree Verify Proof (Leaves as [u8])", move |b| {
117 | b.iter(|| {
118 | for (proof, leaf) in zip(proofs.clone(), leaves.clone()) {
119 | proof
120 | .verify(&leaf_crh_params, &two_to_one_params, &root, leaf.as_slice())
121 | .unwrap();
122 | }
123 | })
124 | });
125 | }
126 |
127 | pub fn merkle_tree_generate_multi_proof(c: &mut Criterion) {
128 | let mut rng = test_rng();
129 | let leaves: Vec<_> = (0..NUM_LEAVES)
130 | .map(|_| {
131 | let rnd = BigInteger256::rand(&mut rng);
132 | to_uncompressed_bytes!(rnd).unwrap()
133 | })
134 | .collect();
135 | let leaf_crh_params = ::setup(&mut rng).unwrap();
136 | let two_to_one_params = ::setup(&mut rng)
137 | .unwrap()
138 | .clone();
139 |
140 | let tree = Sha256MerkleTree::new(
141 | &leaf_crh_params.clone(),
142 | &two_to_one_params.clone(),
143 | &leaves,
144 | )
145 | .unwrap();
146 | c.bench_function(
147 | "Merkle Tree Generate Multi Proof (Leaves as [u8])",
148 | move |b| {
149 | b.iter(|| {
150 | tree.generate_multi_proof((0..leaves.len()).collect::>())
151 | .unwrap();
152 | })
153 | },
154 | );
155 | }
156 |
157 | pub fn merkle_tree_verify_multi_proof(c: &mut Criterion) {
158 | let mut rng = test_rng();
159 | let leaves: Vec<_> = (0..NUM_LEAVES)
160 | .map(|_| {
161 | let rnd = BigInteger256::rand(&mut rng);
162 | to_uncompressed_bytes!(rnd).unwrap()
163 | })
164 | .collect();
165 | let leaf_crh_params = ::setup(&mut rng).unwrap();
166 | let two_to_one_params = ::setup(&mut rng)
167 | .unwrap()
168 | .clone();
169 |
170 | let tree = Sha256MerkleTree::new(
171 | &leaf_crh_params.clone(),
172 | &two_to_one_params.clone(),
173 | &leaves,
174 | )
175 | .unwrap();
176 |
177 | let root = tree.root();
178 |
179 | let multi_proof = tree
180 | .generate_multi_proof((0..leaves.len()).collect::>())
181 | .unwrap();
182 |
183 | c.bench_function(
184 | "Merkle Tree Verify Multi Proof (Leaves as [u8])",
185 | move |b| {
186 | b.iter(|| {
187 | multi_proof.verify(&leaf_crh_params, &two_to_one_params, &root, leaves.clone())
188 | })
189 | },
190 | );
191 | }
192 |
193 | criterion_group! {
194 | name = mt_create;
195 | config = Criterion::default().sample_size(100);
196 | targets = merkle_tree_create
197 | }
198 |
199 | criterion_group! {
200 | name = mt_proof;
201 | config = Criterion::default().sample_size(100);
202 | targets = merkle_tree_generate_proof, merkle_tree_generate_multi_proof
203 | }
204 |
205 | criterion_group! {
206 | name = mt_verify;
207 | config = Criterion::default().sample_size(10);
208 | targets = merkle_tree_verify_proof, merkle_tree_verify_multi_proof
209 | }
210 | }
211 |
212 | criterion_main!(
213 | bytes_mt_benches::mt_create,
214 | bytes_mt_benches::mt_proof,
215 | bytes_mt_benches::mt_verify
216 | );
217 |
--------------------------------------------------------------------------------
/crypto-primitives/benches/prf.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate criterion;
3 |
4 | use ark_crypto_primitives::prf::*;
5 | use ark_std::rand::Rng;
6 | use criterion::Criterion;
7 |
8 | fn blake2s_prf_eval(c: &mut Criterion) {
9 | let rng = &mut ark_std::test_rng();
10 | let input: [u8; 32] = rng.gen();
11 | let seed: [u8; 32] = rng.gen();
12 | c.bench_function("Blake2s PRF Eval", move |b| {
13 | b.iter(|| Blake2s::evaluate(&seed, &input).unwrap())
14 | });
15 | }
16 |
17 | criterion_group! {
18 | name = prf_eval;
19 | config = Criterion::default().sample_size(50);
20 | targets = blake2s_prf_eval
21 | }
22 |
23 | criterion_main!(prf_eval);
24 |
--------------------------------------------------------------------------------
/crypto-primitives/benches/signature.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate criterion;
3 |
4 | use ark_crypto_primitives::signature::{schnorr::*, SignatureScheme};
5 | use ark_ed_on_bls12_377::EdwardsProjective as Edwards;
6 | use ark_std::rand::Rng;
7 | use blake2::Blake2s256 as Blake2s;
8 | use criterion::Criterion;
9 |
10 | type SchnorrEdwards = Schnorr;
11 | fn schnorr_signature_setup(c: &mut Criterion) {
12 | c.bench_function("SchnorrEdwards: Setup", move |b| {
13 | b.iter(|| {
14 | let mut rng = &mut ark_std::test_rng();
15 | SchnorrEdwards::setup(&mut rng).unwrap()
16 | })
17 | });
18 | }
19 |
20 | fn schnorr_signature_keygen(c: &mut Criterion) {
21 | let mut rng = &mut ark_std::test_rng();
22 | let parameters = SchnorrEdwards::setup(&mut rng).unwrap();
23 |
24 | c.bench_function("SchnorrEdwards: KeyGen", move |b| {
25 | b.iter(|| {
26 | let mut rng = &mut ark_std::test_rng();
27 | SchnorrEdwards::keygen(¶meters, &mut rng).unwrap()
28 | })
29 | });
30 | }
31 |
32 | fn schnorr_signature_sign(c: &mut Criterion) {
33 | let mut rng = &mut ark_std::test_rng();
34 | let parameters = SchnorrEdwards::setup(&mut rng).unwrap();
35 | let (_, sk) = SchnorrEdwards::keygen(¶meters, &mut rng).unwrap();
36 | let message = [100u8; 128];
37 |
38 | c.bench_function("SchnorrEdwards: Sign", move |b| {
39 | b.iter(|| {
40 | let mut rng = &mut ark_std::test_rng();
41 | SchnorrEdwards::sign(¶meters, &sk, &message, &mut rng).unwrap()
42 | })
43 | });
44 | }
45 |
46 | fn schnorr_signature_verify(c: &mut Criterion) {
47 | let mut rng = &mut ark_std::test_rng();
48 | let parameters = SchnorrEdwards::setup(&mut rng).unwrap();
49 | let (pk, sk) = SchnorrEdwards::keygen(¶meters, &mut rng).unwrap();
50 | let message = [100u8; 128];
51 | let signature = SchnorrEdwards::sign(¶meters, &sk, &message, &mut rng).unwrap();
52 |
53 | c.bench_function("SchnorrEdwards: Verify", move |b| {
54 | b.iter(|| SchnorrEdwards::verify(¶meters, &pk, &message, &signature).unwrap())
55 | });
56 | }
57 |
58 | fn schnorr_signature_randomize_pk(c: &mut Criterion) {
59 | let mut rng = &mut ark_std::test_rng();
60 | let parameters = SchnorrEdwards::setup(&mut rng).unwrap();
61 | let (pk, _) = SchnorrEdwards::keygen(¶meters, &mut rng).unwrap();
62 | let randomness: [u8; 32] = rng.gen();
63 |
64 | c.bench_function("SchnorrEdwards: Randomize PubKey", move |b| {
65 | b.iter(|| SchnorrEdwards::randomize_public_key(¶meters, &pk, &randomness).unwrap())
66 | });
67 | }
68 |
69 | fn schnorr_signature_randomize_signature(c: &mut Criterion) {
70 | let mut rng = &mut ark_std::test_rng();
71 | let parameters = SchnorrEdwards::setup(&mut rng).unwrap();
72 | let (_, sk) = SchnorrEdwards::keygen(¶meters, &mut rng).unwrap();
73 | let randomness: [u8; 32] = rng.gen();
74 | let message = [100u8; 128];
75 | let signature = SchnorrEdwards::sign(¶meters, &sk, &message, &mut rng).unwrap();
76 |
77 | c.bench_function("SchnorrEdwards: Randomize Signature", move |b| {
78 | b.iter(|| {
79 | SchnorrEdwards::randomize_signature(¶meters, &signature, &randomness).unwrap()
80 | })
81 | });
82 | }
83 | criterion_group! {
84 | name = schnorr_sig;
85 | config = Criterion::default().sample_size(20);
86 | targets = schnorr_signature_setup, schnorr_signature_keygen, schnorr_signature_sign,
87 | schnorr_signature_verify, schnorr_signature_randomize_pk, schnorr_signature_randomize_signature
88 | }
89 | criterion_main!(schnorr_sig);
90 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/blake2s/constraints.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | commitment::{blake2s, CommitmentGadget},
3 | prf::blake2s::constraints::{evaluate_blake2s, OutputVar},
4 | };
5 | use ark_ff::{Field, PrimeField};
6 | use ark_r1cs_std::prelude::*;
7 | use ark_relations::r1cs::{Namespace, SynthesisError};
8 | use ark_std::borrow::Borrow;
9 |
10 | #[derive(Clone)]
11 | pub struct ParametersVar;
12 |
13 | #[derive(Clone)]
14 | pub struct RandomnessVar(pub Vec>);
15 |
16 | pub struct CommGadget;
17 |
18 | impl CommitmentGadget for CommGadget {
19 | type OutputVar = OutputVar;
20 | type ParametersVar = ParametersVar;
21 | type RandomnessVar = RandomnessVar;
22 |
23 | #[tracing::instrument(target = "r1cs", skip(input, r))]
24 | fn commit(
25 | _: &Self::ParametersVar,
26 | input: &[UInt8],
27 | r: &Self::RandomnessVar,
28 | ) -> Result {
29 | let mut input_bits = Vec::with_capacity(512);
30 | for byte in input.iter().chain(r.0.iter()) {
31 | input_bits.extend_from_slice(&byte.to_bits_le()?);
32 | }
33 | let mut result = Vec::new();
34 | for int in evaluate_blake2s(&input_bits)?.into_iter() {
35 | let chunk = int.to_bytes_le()?;
36 | result.extend_from_slice(&chunk);
37 | }
38 | Ok(OutputVar(result))
39 | }
40 | }
41 |
42 | impl AllocVar<(), ConstraintF> for ParametersVar {
43 | #[tracing::instrument(target = "r1cs", skip(_cs, _f))]
44 | fn new_variable>(
45 | _cs: impl Into>,
46 | _f: impl FnOnce() -> Result,
47 | _mode: AllocationMode,
48 | ) -> Result {
49 | Ok(ParametersVar)
50 | }
51 | }
52 |
53 | impl AllocVar<[u8; 32], ConstraintF> for RandomnessVar {
54 | #[tracing::instrument(target = "r1cs", skip(cs, f))]
55 | fn new_variable>(
56 | cs: impl Into>,
57 | f: impl FnOnce() -> Result,
58 | mode: AllocationMode,
59 | ) -> Result {
60 | let bytes = f().map(|b| *b.borrow()).unwrap_or([0u8; 32]);
61 | match mode {
62 | AllocationMode::Constant => Ok(Self(UInt8::constant_vec(&bytes))),
63 | AllocationMode::Input => UInt8::new_input_vec(cs, &bytes).map(Self),
64 | AllocationMode::Witness => UInt8::new_witness_vec(cs, &bytes).map(Self),
65 | }
66 | }
67 | }
68 |
69 | #[cfg(test)]
70 | mod test {
71 | use crate::commitment::{
72 | blake2s::{
73 | constraints::{CommGadget, RandomnessVar},
74 | Commitment,
75 | },
76 | CommitmentGadget, CommitmentScheme,
77 | };
78 | use ark_ed_on_bls12_381::Fq as Fr;
79 | use ark_r1cs_std::prelude::*;
80 | use ark_relations::r1cs::ConstraintSystem;
81 | use ark_std::rand::Rng;
82 |
83 | #[test]
84 | fn commitment_gadget_test() {
85 | let cs = ConstraintSystem::::new_ref();
86 |
87 | let input = [1u8; 32];
88 |
89 | let rng = &mut ark_std::test_rng();
90 |
91 | type TestCOMM = Commitment;
92 | type TestCOMMGadget = CommGadget;
93 |
94 | let mut randomness = [0u8; 32];
95 | rng.fill(&mut randomness);
96 |
97 | let parameters = ();
98 | let primitive_result = Commitment::commit(¶meters, &input, &randomness).unwrap();
99 |
100 | let mut input_var = vec![];
101 | for byte in &input {
102 | input_var.push(UInt8::new_witness(cs.clone(), || Ok(*byte)).unwrap());
103 | }
104 |
105 | let mut randomness_var = vec![];
106 | for r_byte in randomness.iter() {
107 | randomness_var.push(UInt8::new_witness(cs.clone(), || Ok(r_byte)).unwrap());
108 | }
109 | let randomness_var = RandomnessVar(randomness_var);
110 |
111 | let parameters_var =
112 | >::ParametersVar::new_witness(
113 | ark_relations::ns!(cs, "gadget_parameters"),
114 | || Ok(¶meters),
115 | )
116 | .unwrap();
117 | let result_var = >::commit(
118 | ¶meters_var,
119 | &input_var,
120 | &randomness_var,
121 | )
122 | .unwrap();
123 |
124 | for i in 0..32 {
125 | assert_eq!(primitive_result[i], result_var.0[i].value().unwrap());
126 | }
127 | assert!(cs.is_satisfied().unwrap());
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/blake2s/mod.rs:
--------------------------------------------------------------------------------
1 | use crate::{commitment::CommitmentScheme, Error};
2 | use ark_std::rand::Rng;
3 | use blake2::Blake2s256 as b2s;
4 | use digest::Digest;
5 |
6 | pub struct Commitment;
7 |
8 | #[cfg(feature = "r1cs")]
9 | pub mod constraints;
10 |
11 | impl CommitmentScheme for Commitment {
12 | type Parameters = ();
13 | type Randomness = [u8; 32];
14 | type Output = [u8; 32];
15 |
16 | fn setup(_: &mut R) -> Result {
17 | Ok(())
18 | }
19 |
20 | fn commit(
21 | _: &Self::Parameters,
22 | input: &[u8],
23 | r: &Self::Randomness,
24 | ) -> Result {
25 | let mut h = b2s::new();
26 | h.update(input);
27 | h.update(r.as_ref());
28 | let mut result = [0u8; 32];
29 | result.copy_from_slice(&h.finalize());
30 | Ok(result)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/constraints.rs:
--------------------------------------------------------------------------------
1 | use crate::commitment::CommitmentScheme;
2 | use ark_ff::Field;
3 | use ark_r1cs_std::prelude::*;
4 | use ark_relations::r1cs::SynthesisError;
5 | use ark_std::fmt::Debug;
6 |
7 | pub trait CommitmentGadget {
8 | type OutputVar: EqGadget
9 | + ToBytesGadget
10 | + AllocVar
11 | + R1CSVar
12 | + Clone
13 | + Sized
14 | + Debug;
15 | type ParametersVar: AllocVar + Clone;
16 | type RandomnessVar: AllocVar + Clone;
17 |
18 | fn commit(
19 | parameters: &Self::ParametersVar,
20 | input: &[UInt8],
21 | r: &Self::RandomnessVar,
22 | ) -> Result;
23 | }
24 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/injective_map/constraints.rs:
--------------------------------------------------------------------------------
1 | use crate::commitment::{
2 | injective_map::{InjectiveMap, PedersenCommCompressor},
3 | pedersen::{
4 | constraints::{CommGadget, ParametersVar, RandomnessVar},
5 | Window,
6 | },
7 | };
8 | pub use crate::crh::injective_map::constraints::InjectiveMapGadget;
9 | use ark_ec::CurveGroup;
10 | use ark_ff::{Field, PrimeField};
11 | use ark_r1cs_std::{
12 | groups::{CurveVar, GroupOpsBounds},
13 | uint8::UInt8,
14 | };
15 | use ark_relations::r1cs::SynthesisError;
16 | use ark_std::marker::PhantomData;
17 |
18 | type ConstraintF = <::BaseField as Field>::BasePrimeField;
19 |
20 | pub struct CommitmentCompressorGadget
21 | where
22 | C: CurveGroup,
23 | I: InjectiveMap,
24 | W: Window,
25 | GG: CurveVar>,
26 | IG: InjectiveMapGadget,
27 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
28 | {
29 | _compressor: PhantomData,
30 | _compressor_gadget: PhantomData,
31 | _comm: PhantomData>,
32 | }
33 |
34 | impl
35 | crate::commitment::CommitmentGadget, ConstraintF>
36 | for CommitmentCompressorGadget
37 | where
38 | C: CurveGroup,
39 | I: InjectiveMap,
40 | GG: CurveVar>,
41 | ConstraintF: PrimeField,
42 | IG: InjectiveMapGadget,
43 | W: Window,
44 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
45 | {
46 | type OutputVar = IG::OutputVar;
47 | type ParametersVar = ParametersVar;
48 | type RandomnessVar = RandomnessVar>;
49 |
50 | fn commit(
51 | parameters: &Self::ParametersVar,
52 | input: &[UInt8>],
53 | r: &Self::RandomnessVar,
54 | ) -> Result {
55 | let result = CommGadget::::commit(parameters, input, r)?;
56 | IG::evaluate(&result)
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/injective_map/mod.rs:
--------------------------------------------------------------------------------
1 | pub use crate::crh::injective_map::InjectiveMap;
2 | use crate::{
3 | commitment::{pedersen, CommitmentScheme},
4 | Error,
5 | };
6 | use ark_ec::CurveGroup;
7 | use ark_std::{marker::PhantomData, rand::Rng};
8 |
9 | #[cfg(feature = "r1cs")]
10 | pub mod constraints;
11 |
12 | pub struct PedersenCommCompressor, W: pedersen::Window> {
13 | _group: PhantomData,
14 | _compressor: PhantomData,
15 | _comm: pedersen::Commitment,
16 | }
17 |
18 | impl, W: pedersen::Window> CommitmentScheme
19 | for PedersenCommCompressor
20 | {
21 | type Output = I::Output;
22 | type Parameters = pedersen::Parameters;
23 | type Randomness = pedersen::Randomness;
24 |
25 | fn setup(rng: &mut R) -> Result {
26 | let time = start_timer!(|| format!("PedersenCompressor::Setup"));
27 | let params = pedersen::Commitment::::setup(rng);
28 | end_timer!(time);
29 | params
30 | }
31 |
32 | fn commit(
33 | parameters: &Self::Parameters,
34 | input: &[u8],
35 | randomness: &Self::Randomness,
36 | ) -> Result {
37 | let eval_time = start_timer!(|| "PedersenCompressor::Eval");
38 | let result = I::injective_map(&pedersen::Commitment::::commit(
39 | parameters, input, randomness,
40 | )?)?;
41 | end_timer!(eval_time);
42 | Ok(result)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/mod.rs:
--------------------------------------------------------------------------------
1 | use crate::Error;
2 | use ark_ff::UniformRand;
3 | use ark_serialize::CanonicalSerialize;
4 | use ark_std::{fmt::Debug, hash::Hash, rand::Rng};
5 |
6 | pub mod blake2s;
7 | pub mod injective_map;
8 | pub mod pedersen;
9 |
10 | #[cfg(feature = "r1cs")]
11 | pub mod constraints;
12 | #[cfg(feature = "r1cs")]
13 | pub use constraints::*;
14 |
15 | pub trait CommitmentScheme {
16 | type Output: CanonicalSerialize + Clone + Default + Eq + Hash + Debug;
17 | type Parameters: Clone;
18 | type Randomness: CanonicalSerialize + Clone + Default + Eq + UniformRand + Debug;
19 |
20 | fn setup(r: &mut R) -> Result;
21 |
22 | fn commit(
23 | parameters: &Self::Parameters,
24 | input: &[u8],
25 | r: &Self::Randomness,
26 | ) -> Result;
27 | }
28 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/pedersen/constraints.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | commitment::pedersen::{Commitment, Parameters, Randomness},
3 | crh::pedersen::Window,
4 | };
5 | use ark_ec::CurveGroup;
6 | use ark_ff::{
7 | fields::{Field, PrimeField},
8 | Zero,
9 | };
10 | use ark_r1cs_std::prelude::*;
11 | use ark_relations::r1cs::{Namespace, SynthesisError};
12 | use ark_serialize::CanonicalSerialize;
13 | use ark_std::{borrow::Borrow, iter, marker::PhantomData};
14 |
15 | type ConstraintF = <::BaseField as Field>::BasePrimeField;
16 |
17 | #[derive(Derivative)]
18 | #[derivative(Clone(bound = "C: CurveGroup, GG: CurveVar>"))]
19 | pub struct ParametersVar>>
20 | where
21 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
22 | {
23 | params: Parameters,
24 | #[doc(hidden)]
25 | _group_var: PhantomData,
26 | }
27 |
28 | #[derive(Clone, Debug)]
29 | pub struct RandomnessVar(Vec>);
30 |
31 | pub struct CommGadget>, W: Window>
32 | where
33 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
34 | {
35 | #[doc(hidden)]
36 | _curve: PhantomData<*const C>,
37 | #[doc(hidden)]
38 | _group_var: PhantomData<*const GG>,
39 | #[doc(hidden)]
40 | _window: PhantomData<*const W>,
41 | }
42 |
43 | impl crate::commitment::CommitmentGadget, ConstraintF>
44 | for CommGadget
45 | where
46 | C: CurveGroup,
47 | GG: CurveVar>,
48 | W: Window,
49 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
50 | ConstraintF: PrimeField,
51 | {
52 | type OutputVar = GG;
53 | type ParametersVar = ParametersVar;
54 | type RandomnessVar = RandomnessVar>;
55 |
56 | #[tracing::instrument(target = "r1cs", skip(parameters, r))]
57 | fn commit(
58 | parameters: &Self::ParametersVar,
59 | input: &[UInt8>],
60 | r: &Self::RandomnessVar,
61 | ) -> Result {
62 | assert!((input.len() * 8) <= (W::WINDOW_SIZE * W::NUM_WINDOWS));
63 |
64 | // Convert input bytes to little-endian bits
65 | let mut input_in_bits: Vec> = input
66 | .iter()
67 | .flat_map(|byte| byte.to_bits_le().unwrap())
68 | .collect();
69 |
70 | // Pad input to `W::WINDOW_SIZE * W::NUM_WINDOWS`.
71 | let padding_size = (W::WINDOW_SIZE * W::NUM_WINDOWS) - input_in_bits.len();
72 | input_in_bits.extend(iter::repeat(Boolean::FALSE).take(padding_size));
73 |
74 | // Sanity checks
75 | assert_eq!(input_in_bits.len(), W::WINDOW_SIZE * W::NUM_WINDOWS);
76 | assert_eq!(parameters.params.generators.len(), W::NUM_WINDOWS);
77 |
78 | // Compute the unblinded commitment. Chunk the input bits into correctly sized windows
79 | let input_in_bits = input_in_bits.chunks(W::WINDOW_SIZE);
80 | let mut result =
81 | GG::precomputed_base_multiscalar_mul_le(¶meters.params.generators, input_in_bits)?;
82 |
83 | // Now add in the blinding factor h^r
84 | let rand_bits: Vec<_> =
85 | r.0.iter()
86 | .flat_map(|byte| byte.to_bits_le().unwrap())
87 | .collect();
88 | result.precomputed_base_scalar_mul_le(
89 | rand_bits
90 | .iter()
91 | .zip(¶meters.params.randomness_generator),
92 | )?;
93 |
94 | Ok(result)
95 | }
96 | }
97 |
98 | impl AllocVar, ConstraintF> for ParametersVar
99 | where
100 | C: CurveGroup,
101 | GG: CurveVar>,
102 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
103 | {
104 | fn new_variable>>(
105 | _cs: impl Into>>,
106 | f: impl FnOnce() -> Result,
107 | _mode: AllocationMode,
108 | ) -> Result {
109 | let params = f()?.borrow().clone();
110 | Ok(ParametersVar {
111 | params,
112 | _group_var: PhantomData,
113 | })
114 | }
115 | }
116 |
117 | impl AllocVar, F> for RandomnessVar
118 | where
119 | C: CurveGroup,
120 | F: PrimeField,
121 | {
122 | fn new_variable>>(
123 | cs: impl Into>,
124 | f: impl FnOnce() -> Result,
125 | mode: AllocationMode,
126 | ) -> Result {
127 | let mut r = Vec::new();
128 | let _ = &f()
129 | .map(|b| b.borrow().0)
130 | .unwrap_or(C::ScalarField::zero())
131 | .serialize_uncompressed(&mut r)
132 | .unwrap();
133 | match mode {
134 | AllocationMode::Constant => Ok(Self(UInt8::constant_vec(&r))),
135 | AllocationMode::Input => UInt8::new_input_vec(cs, &r).map(Self),
136 | AllocationMode::Witness => UInt8::new_witness_vec(cs, &r).map(Self),
137 | }
138 | }
139 | }
140 |
141 | #[cfg(test)]
142 | mod test {
143 | use ark_ed_on_bls12_381::{constraints::EdwardsVar, EdwardsProjective as JubJub, Fq, Fr};
144 | use ark_std::{test_rng, UniformRand};
145 |
146 | use crate::{
147 | commitment::{
148 | pedersen::{constraints::CommGadget, Commitment, Randomness},
149 | CommitmentGadget, CommitmentScheme,
150 | },
151 | crh::pedersen,
152 | };
153 | use ark_r1cs_std::prelude::*;
154 | use ark_relations::r1cs::ConstraintSystem;
155 |
156 | /// Checks that the primitive Pedersen commitment matches the gadget version
157 | #[test]
158 | fn commitment_gadget_test() {
159 | let cs = ConstraintSystem::::new_ref();
160 |
161 | #[derive(Clone, PartialEq, Eq, Hash)]
162 | pub(super) struct Window;
163 |
164 | impl pedersen::Window for Window {
165 | const WINDOW_SIZE: usize = 4;
166 | const NUM_WINDOWS: usize = 9;
167 | }
168 |
169 | let input = [1u8; 4];
170 |
171 | let rng = &mut test_rng();
172 |
173 | type TestCOMM = Commitment;
174 | type TestCOMMGadget = CommGadget;
175 |
176 | let randomness = Randomness(Fr::rand(rng));
177 |
178 | let parameters = Commitment::::setup(rng).unwrap();
179 | let primitive_result =
180 | Commitment::::commit(¶meters, &input, &randomness).unwrap();
181 |
182 | let mut input_var = vec![];
183 | for input_byte in input.iter() {
184 | input_var.push(UInt8::new_witness(cs.clone(), || Ok(*input_byte)).unwrap());
185 | }
186 |
187 | let randomness_var =
188 | >::RandomnessVar::new_witness(
189 | ark_relations::ns!(cs, "gadget_randomness"),
190 | || Ok(&randomness),
191 | )
192 | .unwrap();
193 | let parameters_var =
194 | >::ParametersVar::new_witness(
195 | ark_relations::ns!(cs, "gadget_parameters"),
196 | || Ok(¶meters),
197 | )
198 | .unwrap();
199 | let result_var =
200 | TestCOMMGadget::commit(¶meters_var, &input_var, &randomness_var).unwrap();
201 |
202 | let primitive_result = primitive_result;
203 | assert_eq!(primitive_result, result_var.value().unwrap());
204 | assert!(cs.is_satisfied().unwrap());
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/crypto-primitives/src/commitment/pedersen/mod.rs:
--------------------------------------------------------------------------------
1 | use super::CommitmentScheme;
2 | pub use crate::crh::pedersen::Window;
3 | use crate::{
4 | crh::{pedersen, CRHScheme},
5 | Error,
6 | };
7 | use ark_ec::CurveGroup;
8 | use ark_ff::{BitIteratorLE, Field, PrimeField, ToConstraintField};
9 | use ark_serialize::CanonicalSerialize;
10 | #[cfg(not(feature = "std"))]
11 | use ark_std::vec::Vec;
12 | use ark_std::{marker::PhantomData, rand::Rng, UniformRand};
13 |
14 | #[cfg(feature = "r1cs")]
15 | pub mod constraints;
16 |
17 | #[derive(Clone)]
18 | pub struct Parameters {
19 | pub randomness_generator: Vec,
20 | pub generators: Vec>,
21 | }
22 |
23 | pub struct Commitment {
24 | group: PhantomData,
25 | window: PhantomData,
26 | }
27 |
28 | #[derive(Derivative, CanonicalSerialize)]
29 | #[derivative(Clone, PartialEq, Debug, Eq, Default)]
30 | pub struct Randomness(pub C::ScalarField);
31 |
32 | impl UniformRand for Randomness {
33 | #[inline]
34 | fn rand(rng: &mut R) -> Self {
35 | Randomness(UniformRand::rand(rng))
36 | }
37 | }
38 |
39 | impl CommitmentScheme for Commitment {
40 | type Parameters = Parameters;
41 | type Randomness = Randomness;
42 | type Output = C::Affine;
43 |
44 | fn setup(rng: &mut R) -> Result {
45 | let time = start_timer!(|| format!(
46 | "PedersenCOMM::Setup: {} {}-bit windows; {{0,1}}^{{{}}} -> C",
47 | W::NUM_WINDOWS,
48 | W::WINDOW_SIZE,
49 | W::NUM_WINDOWS * W::WINDOW_SIZE
50 | ));
51 | let num_powers = ::MODULUS_BIT_SIZE as usize;
52 | let randomness_generator = pedersen::CRH::::generator_powers(num_powers, rng);
53 | let generators = pedersen::CRH::::create_generators(rng);
54 | end_timer!(time);
55 |
56 | Ok(Self::Parameters {
57 | randomness_generator,
58 | generators,
59 | })
60 | }
61 |
62 | fn commit(
63 | parameters: &Self::Parameters,
64 | input: &[u8],
65 | randomness: &Self::Randomness,
66 | ) -> Result {
67 | let commit_time = start_timer!(|| "PedersenCOMM::Commit");
68 | // If the input is too long, return an error.
69 | if input.len() > W::WINDOW_SIZE * W::NUM_WINDOWS {
70 | panic!("incorrect input length: {:?}", input.len());
71 | }
72 | // Pad the input to the necessary length.
73 | let mut padded_input = Vec::with_capacity(input.len());
74 | let mut input = input;
75 | if (input.len() * 8) < W::WINDOW_SIZE * W::NUM_WINDOWS {
76 | padded_input.extend_from_slice(input);
77 | let padded_length = (W::WINDOW_SIZE * W::NUM_WINDOWS) / 8;
78 | padded_input.resize(padded_length, 0u8);
79 | input = padded_input.as_slice();
80 | }
81 | assert_eq!(parameters.generators.len(), W::NUM_WINDOWS);
82 | let input = input.to_vec();
83 | // Invoke Pedersen CRH here, to prevent code duplication.
84 |
85 | let crh_parameters = pedersen::Parameters {
86 | generators: parameters.generators.clone(),
87 | };
88 | let mut result: C =
89 | pedersen::CRH::::evaluate(&crh_parameters, input.as_slice())?.into();
90 | let randomize_time = start_timer!(|| "Randomize");
91 |
92 | // Compute h^r.
93 | for (bit, power) in BitIteratorLE::new(randomness.0.into_bigint())
94 | .into_iter()
95 | .zip(¶meters.randomness_generator)
96 | {
97 | if bit {
98 | result += power
99 | }
100 | }
101 | end_timer!(randomize_time);
102 | end_timer!(commit_time);
103 |
104 | Ok(result.into())
105 | }
106 | }
107 |
108 | impl>
109 | ToConstraintField for Parameters
110 | {
111 | #[inline]
112 | fn to_field_elements(&self) -> Option> {
113 | Some(Vec::new())
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/crypto-primitives/src/crh/bowe_hopwood/mod.rs:
--------------------------------------------------------------------------------
1 | //! The [Bowe-Hopwood-Pedersen] hash is a optimized variant of the Pedersen CRH for
2 | //! specific Twisted Edwards (TE) curves. See [Section 5.4.17 of the Zcash protocol specification](https://raw.githubusercontent.com/zcash/zips/master/protocol/protocol.pdf#concretepedersenhash) for a formal description of this hash function, specialized for the Jubjub curve.
3 | //! The implementation in this repository is generic across choice of TE curves.
4 |
5 | use crate::{
6 | crh::{pedersen, CRHScheme, TwoToOneCRHScheme},
7 | Error,
8 | };
9 | use ark_ec::{
10 | twisted_edwards::Projective as TEProjective, twisted_edwards::TECurveConfig, AdditiveGroup,
11 | CurveGroup,
12 | };
13 | use ark_ff::fields::PrimeField;
14 | use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
15 | #[cfg(not(feature = "std"))]
16 | use ark_std::vec::Vec;
17 | use ark_std::{
18 | borrow::Borrow,
19 | cfg_chunks,
20 | fmt::{Debug, Formatter, Result as FmtResult},
21 | marker::PhantomData,
22 | rand::Rng,
23 | UniformRand,
24 | };
25 | #[cfg(feature = "parallel")]
26 | use rayon::prelude::*;
27 |
28 | #[cfg(feature = "r1cs")]
29 | pub mod constraints;
30 |
31 | pub const CHUNK_SIZE: usize = 3;
32 |
33 | #[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)]
34 | #[derivative(Clone(bound = ""), Default(bound = ""))]
35 | pub struct Parameters {
36 | pub generators: Vec>>,
37 | }
38 |
39 | pub struct CRH {
40 | group: PhantomData,
41 | window: PhantomData,
42 | }
43 |
44 | impl CRH {
45 | pub fn create_generators(rng: &mut R) -> Vec>> {
46 | let mut generators = Vec::new();
47 | for _ in 0..W::NUM_WINDOWS {
48 | let mut generators_for_segment = Vec::new();
49 | let mut base = TEProjective::rand(rng);
50 | for _ in 0..W::WINDOW_SIZE {
51 | generators_for_segment.push(base);
52 | for _ in 0..4 {
53 | base.double_in_place();
54 | }
55 | }
56 | generators.push(generators_for_segment);
57 | }
58 | generators
59 | }
60 | }
61 |
62 | pub struct TwoToOneCRH {
63 | group: PhantomData,
64 | window: PhantomData,
65 | }
66 |
67 | impl TwoToOneCRH {
68 | const INPUT_SIZE_BITS: usize = pedersen::CRH::, W>::INPUT_SIZE_BITS;
69 | const HALF_INPUT_SIZE_BITS: usize = Self::INPUT_SIZE_BITS / 2;
70 | pub fn create_generators(rng: &mut R) -> Vec>> {
71 | CRH::::create_generators(rng)
72 | }
73 | }
74 |
75 | impl CRHScheme for CRH {
76 | type Input = [u8];
77 |
78 | type Output = P::BaseField;
79 | type Parameters = Parameters
;
80 |
81 | fn setup(rng: &mut R) -> Result {
82 | fn calculate_num_chunks_in_segment() -> usize {
83 | let upper_limit = F::MODULUS_MINUS_ONE_DIV_TWO;
84 | let mut c = 0;
85 | let mut range = F::BigInt::from(2_u64);
86 | while range < upper_limit {
87 | range <<= 4;
88 | c += 1;
89 | }
90 |
91 | c
92 | }
93 |
94 | let maximum_num_chunks_in_segment = calculate_num_chunks_in_segment::();
95 | if W::WINDOW_SIZE > maximum_num_chunks_in_segment {
96 | panic!(
97 | "Bowe-Hopwood-PedersenCRH hash must have a window size resulting in scalars < (p-1)/2, \
98 | maximum segment size is {}",
99 | maximum_num_chunks_in_segment
100 | );
101 | }
102 |
103 | let time = start_timer!(|| format!(
104 | "Bowe-Hopwood-PedersenCRH::Setup: {} segments of {} 3-bit chunks; {{0,1}}^{{{}}} -> P",
105 | W::NUM_WINDOWS,
106 | W::WINDOW_SIZE,
107 | W::WINDOW_SIZE * W::NUM_WINDOWS * CHUNK_SIZE
108 | ));
109 | let generators = Self::create_generators(rng);
110 | end_timer!(time);
111 | Ok(Self::Parameters { generators })
112 | }
113 |
114 | fn evaluate>(
115 | parameters: &Self::Parameters,
116 | input: T,
117 | ) -> Result {
118 | let input = input.borrow();
119 | let eval_time = start_timer!(|| "BoweHopwoodPedersenCRH::Eval");
120 |
121 | if (input.len() * 8) > W::WINDOW_SIZE * W::NUM_WINDOWS * CHUNK_SIZE {
122 | panic!(
123 | "incorrect input bitlength {:?} for window params {:?}x{:?}x{}",
124 | input.len() * 8,
125 | W::WINDOW_SIZE,
126 | W::NUM_WINDOWS,
127 | CHUNK_SIZE,
128 | );
129 | }
130 |
131 | let mut padded_input = Vec::with_capacity(input.len());
132 | let input = pedersen::bytes_to_bits(input);
133 | // Pad the input if it is not the current length.
134 | padded_input.extend_from_slice(&input);
135 | if input.len() % CHUNK_SIZE != 0 {
136 | let remaining = CHUNK_SIZE - input.len() % CHUNK_SIZE;
137 | padded_input.extend_from_slice(&vec![false; remaining]);
138 | }
139 |
140 | assert_eq!(padded_input.len() % CHUNK_SIZE, 0);
141 |
142 | assert_eq!(
143 | parameters.generators.len(),
144 | W::NUM_WINDOWS,
145 | "Incorrect pp of size {:?} for window params {:?}x{:?}x{}",
146 | parameters.generators.len(),
147 | W::WINDOW_SIZE,
148 | W::NUM_WINDOWS,
149 | CHUNK_SIZE,
150 | );
151 | for generators in parameters.generators.iter() {
152 | assert_eq!(generators.len(), W::WINDOW_SIZE);
153 | }
154 | assert_eq!(CHUNK_SIZE, 3);
155 |
156 | // Compute sum of h_i^{sum of
157 | // (1-2*c_{i,j,2})*(1+c_{i,j,0}+2*c_{i,j,1})*2^{4*(j-1)} for all j in segment}
158 | // for all i. Described in section 5.4.1.7 in the Zcash protocol
159 | // specification.
160 |
161 | let result = cfg_chunks!(padded_input, W::WINDOW_SIZE * CHUNK_SIZE)
162 | .zip(¶meters.generators)
163 | .map(|(segment_bits, segment_generators)| {
164 | cfg_chunks!(segment_bits, CHUNK_SIZE)
165 | .zip(segment_generators)
166 | .map(|(chunk_bits, generator)| {
167 | let mut encoded = *generator;
168 | if chunk_bits[0] {
169 | encoded += generator;
170 | }
171 | if chunk_bits[1] {
172 | encoded += &generator.double();
173 | }
174 | if chunk_bits[2] {
175 | encoded = -encoded;
176 | }
177 | encoded
178 | })
179 | .sum::>()
180 | })
181 | .sum::>();
182 |
183 | end_timer!(eval_time);
184 |
185 | Ok(result.into_affine().x)
186 | }
187 | }
188 |
189 | impl TwoToOneCRHScheme for TwoToOneCRH {
190 | type Input = [u8];
191 |
192 | type Output = P::BaseField;
193 | type Parameters = Parameters
;
194 |
195 | fn setup(r: &mut R) -> Result {
196 | CRH::::setup(r)
197 | }
198 |
199 | /// A simple implementation method: just concat the left input and right input together
200 | ///
201 | /// `evaluate` requires that `left_input` and `right_input` are of equal length.
202 | fn evaluate>(
203 | parameters: &Self::Parameters,
204 | left_input: T,
205 | right_input: T,
206 | ) -> Result {
207 | let left_input = left_input.borrow();
208 | let right_input = right_input.borrow();
209 | assert_eq!(
210 | left_input.len(),
211 | right_input.len(),
212 | "left and right input should be of equal length"
213 | );
214 | // check overflow
215 |
216 | debug_assert!(left_input.len() * 8 <= Self::HALF_INPUT_SIZE_BITS);
217 | debug_assert!(right_input.len() * 8 <= Self::HALF_INPUT_SIZE_BITS);
218 |
219 | let mut buffer = vec![0u8; Self::INPUT_SIZE_BITS / 8];
220 |
221 | buffer
222 | .iter_mut()
223 | .zip(left_input.iter().chain(right_input.iter()))
224 | .for_each(|(b, l_b)| *b = *l_b);
225 |
226 | CRH::::evaluate(parameters, buffer)
227 | }
228 |
229 | fn compress>(
230 | parameters: &Self::Parameters,
231 | left_input: T,
232 | right_input: T,
233 | ) -> Result {
234 | Self::evaluate(
235 | parameters,
236 | crate::to_uncompressed_bytes!(left_input)?,
237 | crate::to_uncompressed_bytes!(right_input)?,
238 | )
239 | }
240 | }
241 |
242 | impl Debug for Parameters {
243 | fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
244 | writeln!(f, "Bowe-Hopwood-Pedersen Hash Parameters {{")?;
245 | for (i, g) in self.generators.iter().enumerate() {
246 | writeln!(f, "\t Generator {}: {:?}", i, g)?;
247 | }
248 | writeln!(f, "}}")
249 | }
250 | }
251 |
252 | #[cfg(test)]
253 | mod test {
254 | use crate::crh::{bowe_hopwood, pedersen::Window, CRHScheme};
255 | use ark_ed_on_bls12_381::EdwardsConfig;
256 | use ark_std::test_rng;
257 |
258 | #[test]
259 | fn test_simple_bh() {
260 | #[derive(Clone)]
261 | struct TestWindow {}
262 | impl Window for TestWindow {
263 | const WINDOW_SIZE: usize = 63;
264 | const NUM_WINDOWS: usize = 8;
265 | }
266 |
267 | let rng = &mut test_rng();
268 | let params = bowe_hopwood::CRH::::setup(rng).unwrap();
269 | let _ =
270 | bowe_hopwood::CRH::::evaluate(¶ms, [1, 2, 3]).unwrap();
271 | }
272 | }
273 |
--------------------------------------------------------------------------------
/crypto-primitives/src/crh/constraints.rs:
--------------------------------------------------------------------------------
1 | use crate::crh::{CRHScheme, TwoToOneCRHScheme};
2 | use ark_ff::Field;
3 | use ark_r1cs_std::prelude::*;
4 | use ark_relations::r1cs::SynthesisError;
5 | use ark_std::fmt::Debug;
6 |
7 | pub trait CRHSchemeGadget: Sized {
8 | type InputVar: ?Sized;
9 | type OutputVar: EqGadget
10 | + ToBytesGadget
11 | + CondSelectGadget
12 | + AllocVar
13 | + R1CSVar
14 | + Debug
15 | + Clone
16 | + Sized;
17 | type ParametersVar: AllocVar + Clone;
18 |
19 | fn evaluate(
20 | parameters: &Self::ParametersVar,
21 | input: &Self::InputVar,
22 | ) -> Result;
23 | }
24 |
25 | pub trait TwoToOneCRHSchemeGadget: Sized {
26 | type InputVar: ?Sized;
27 | type OutputVar: EqGadget
28 | + ToBytesGadget
29 | + CondSelectGadget
30 | + AllocVar
31 | + R1CSVar
32 | + Debug
33 | + Clone
34 | + Sized;
35 |
36 | type ParametersVar: AllocVar + Clone;
37 |
38 | fn evaluate(
39 | parameters: &Self::ParametersVar,
40 | left_input: &Self::InputVar,
41 | right_input: &Self::InputVar,
42 | ) -> Result;
43 |
44 | fn compress(
45 | parameters: &Self::ParametersVar,
46 | left_input: &Self::OutputVar,
47 | right_input: &Self::OutputVar,
48 | ) -> Result;
49 | }
50 |
--------------------------------------------------------------------------------
/crypto-primitives/src/crh/injective_map/constraints.rs:
--------------------------------------------------------------------------------
1 | use crate::crh::{
2 | constraints,
3 | injective_map::{
4 | InjectiveMap, PedersenCRHCompressor, PedersenTwoToOneCRHCompressor, TECompressor,
5 | },
6 | pedersen::{constraints as ped_constraints, Window},
7 | CRHSchemeGadget, TwoToOneCRHSchemeGadget,
8 | };
9 | use ark_ec::{
10 | twisted_edwards::{Projective as TEProjective, TECurveConfig},
11 | CurveConfig, CurveGroup,
12 | };
13 | use ark_ff::fields::{Field, PrimeField};
14 | use ark_r1cs_std::{
15 | fields::fp::FpVar, groups::curves::twisted_edwards::AffineVar as TEVar, prelude::*,
16 | };
17 | use ark_relations::r1cs::SynthesisError;
18 | use ark_std::{fmt::Debug, marker::PhantomData};
19 |
20 | type ConstraintF = <::BaseField as Field>::BasePrimeField;
21 |
22 | pub trait InjectiveMapGadget, GG: CurveVar>>
23 | where
24 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
25 | {
26 | type OutputVar: EqGadget>
27 | + ToBytesGadget>
28 | + CondSelectGadget>
29 | + AllocVar>
30 | + R1CSVar, Value = I::Output>
31 | + Debug
32 | + Clone
33 | + Sized;
34 |
35 | fn evaluate(ge: &GG) -> Result;
36 | }
37 |
38 | pub struct TECompressorGadget;
39 |
40 | impl InjectiveMapGadget, TECompressor, TEVar>>
41 | for TECompressorGadget
42 | where
43 | F: PrimeField,
44 | P: TECurveConfig + CurveConfig,
45 | {
46 | type OutputVar = FpVar;
47 |
48 | fn evaluate(ge: &TEVar>) -> Result {
49 | Ok(ge.x.clone())
50 | }
51 | }
52 |
53 | pub struct PedersenCRHCompressorGadget
54 | where
55 | C: CurveGroup,
56 | I: InjectiveMap,
57 | W: Window,
58 | GG: CurveVar>,
59 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
60 | IG: InjectiveMapGadget,
61 | {
62 | #[doc(hidden)]
63 | _compressor: PhantomData,
64 | #[doc(hidden)]
65 | _compressor_gadget: PhantomData,
66 | #[doc(hidden)]
67 | _crh: ped_constraints::CRHGadget,
68 | }
69 |
70 | impl constraints::CRHSchemeGadget, ConstraintF>
71 | for PedersenCRHCompressorGadget
72 | where
73 | C: CurveGroup,
74 | I: InjectiveMap,
75 | GG: CurveVar>,
76 | for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
77 | IG: InjectiveMapGadget,
78 | W: Window,
79 | {
80 | type InputVar = [UInt8