├── .github
└── workflows
│ └── dusk_ci.yml
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Cargo.toml
├── LICENSE
├── Makefile
├── README.md
├── assets
├── HOWTO.md
├── ark.bin
└── mds.bin
├── build.rs
├── codecov.yml
├── rust-toolchain.toml
└── src
├── lib.rs
├── mds_matrix.rs
├── round_constants.rs
├── strategies.rs
└── strategies
├── gadget.rs
└── scalar.rs
/.github/workflows/dusk_ci.yml:
--------------------------------------------------------------------------------
1 | on:
2 | pull_request:
3 | push:
4 | branches:
5 | - master
6 |
7 | name: Continuous integration
8 |
9 | jobs:
10 | analyze:
11 | name: Code Analysis
12 | uses: dusk-network/.github/.github/workflows/code-analysis.yml@main
13 |
14 | dusk_analyzer:
15 | name: Dusk Analyzer
16 | uses: dusk-network/.github/.github/workflows/dusk-analysis.yml@main
17 |
18 | test_nightly:
19 | name: Nightly test all features
20 | uses: dusk-network/.github/.github/workflows/run-tests.yml@main
21 | with:
22 | test_flags: --all-features
23 |
24 | test_nightly_no_std:
25 | name: Nightly tests no_std
26 | uses: dusk-network/.github/.github/workflows/run-tests.yml@main
27 | with:
28 | test_flags: --no-default-features
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | **/*.rs.bk
3 | Cargo.lock
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # CHANGELOG
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7 |
8 | ## [Unreleased]
9 |
10 | ## [0.24.1] - 2024-01-24
11 |
12 | ### Changed
13 |
14 | - Add deprecation notice [#120]
15 |
16 | ## [0.24.0] - 2024-01-03
17 |
18 | ### Changed
19 |
20 | - Update `dusk-plonk` to 0.19
21 |
22 | ## [0.23.0] - 2023-12-13
23 |
24 | ### Changed
25 |
26 | - Update `dusk-plonk` to 0.18
27 | - Update `dusk-bls12_381` to 0.13
28 |
29 | ## [0.22.1] - 2023-11-22
30 |
31 | ### Fixed
32 |
33 | - Clippy fixes
34 |
35 | ## [0.22.0] - 2023-10-11
36 |
37 | ## Changed
38 |
39 | - Update `dusk-plonk` to 0.16
40 | - Update `dusk-bls12_381` to 0.12
41 |
42 | ## [0.21.0] - 2023-06-28
43 |
44 | ### Changed
45 |
46 | - Update `dusk-plonk` from `0.13` to `0.14`
47 |
48 | ## [0.20.0] - 2022-10-26
49 |
50 | ### Changed
51 |
52 | - Update `dusk-plonk` from `0.12` to `0.13`
53 |
54 | ## [0.19.0] - 2022-08-17
55 |
56 | ### Changed
57 |
58 | - Update `dusk-bls12_381` from `0.8` to `0.11`
59 | - Update `dusk-plonk` from `0.9` to `0.12`
60 |
61 | ## [0.16.0] - 2021-07-02
62 |
63 | ### Added
64 |
65 | - Add toolchain file set to nightly-2021-06-06 [#99]
66 |
67 | ### Changed
68 |
69 | - Change CI toolchain to not override toolchain-file [#99]
70 | - Update `dusk-bls12_381` & `dusk-plonk` to latest versions. [#84]
71 | - Replace `rand` by `rand-core` [#86]
72 | - Change repo to `no_std` with `alloc` feature [#87]
73 | - Change `ROUND_CONSTANTS` and `MDS_MATRIX` to be generated at compile time [#96]
74 |
75 | ### Removed
76 |
77 | - Remove `anyhow` from dev-deps [#85]
78 | - Remove `lazy_static` as dependency
79 |
80 | ### Fixed
81 |
82 | - Fix `Readme.md` import into lib docs [#98]
83 |
84 | ## [0.15.0] - 2021-04-06
85 |
86 | ### Changed
87 |
88 | - Update `plonk` from `0.6` to `v0.7` #81
89 |
90 | ## [0.14.0] - 2021-03-11
91 |
92 | ### Changed
93 |
94 | - Update `plonk` from `0.5` to `v0.6` #79
95 |
96 | ## [0.13.0] - 2021-02-11
97 |
98 | ### Changed
99 |
100 | - Change crate's name from `Hades252` to `dusk-hades`
101 |
102 | ## [0.12.0] - 2021-01-27
103 |
104 | ### Changed
105 |
106 | - Bump `dusk-plonk` to `v0.5`
107 | - Bump `dusk-bls12_381` to `v0.6`
108 | - Remove `nightly_docs` feature
109 |
110 | ## [0.11.0] - 2021-01-26
111 |
112 | ### Changed
113 |
114 | - Bump `dusk-plonk` to `v0.4`
115 | - Bump `dusk-bls12_381` to `v0.5`
116 | - Update CHANGELOG to ISO 8601
117 |
118 | ## [0.10.1] - 2020-11-09
119 |
120 | ### Changed
121 |
122 | - Update to support full no-std.
123 |
124 | ## [0.10.0] - 2020-10-06
125 |
126 | ### Fixed
127 |
128 | - Fixes #69 - ARK on partial round must be applied to all elements.
129 |
130 | ## [0.9.0] - 2020-10-05
131 |
132 | ### Changed
133 |
134 | - Major optimization on `GadgetStrategy` with fan-in-3 feature of PLONK.
135 | Gates per permutation set to `973`
136 |
137 | ## [0.8.1] - 2020-10-04
138 |
139 | ### Changed
140 |
141 | - Optimize `GadgetStrategy` to consume less gates.
142 |
143 | ## [0.8.0] - 2020-09-29
144 |
145 | ### Changed
146 |
147 | - Bump `dusk-plonk` to `v0.2.11`.
148 |
149 | ## [0.7.0] - 2020-08-13
150 |
151 | ### Added
152 |
153 | - `anyhow` crate to support Error handling in the tests.
154 |
155 | ### Changed
156 |
157 | - Update the `dusk-plonk` versions to `v0.2.7`.
158 |
159 | ### Removed
160 |
161 | - Legacy methods to perform `poseidon-based ops` such as hashing
162 | which is not the purpose of this lib.
163 |
164 | ## [0.6.1] - 2020-07-24
165 |
166 | ### Changed
167 |
168 | - `dusk-plonk` crate version to `0.2.1`.
169 |
170 | ## [0.6.0] - 2020-07-21
171 |
172 | ### Changed
173 |
174 | - `dusk-plonk` crate version to `v0.2.0`
175 | - Tests for gadgets now use the Prover&Verifier abstraction.
176 |
177 | ### Removed
178 |
179 | - `dusk-bls12_381` deps which are now taken from plonk's re-exported ones.
180 |
181 | ## [0.5.0] - 2020-05-11
182 |
183 | ### Added
184 |
185 | - `dusk-plonk_v0.1.0` as proving system.
186 | - `dusk-bls12_381_v0.1.0` as curve-backend
187 |
188 | ### Changed
189 |
190 | - `GadgetStrategy` structure refactor & optimization.
191 | - tests updated & refactored with the new proving system.
192 |
193 | ### Removed
194 |
195 | - `Bulletproofs` is no longer the proving system used.
196 | - `Curve25519-dalek` is no longer used as curve-backend.
197 |
198 | ## [0.4.0] - 2020-04-12
199 |
200 | ### Added
201 |
202 | - Plonk/fast_prover_zexe backend for ZK-Gadget functions
203 | - Algebra, poly_commit & num_traits from Zexe as dependencies to work with PLONK.
204 |
205 | ### Changed
206 |
207 | - Refactor the tests to work with the new ZK-Proof algorithm Plonk.
208 |
209 | ### Fixed
210 |
211 | - Reduce the size of the circuit produced by reducing some gates that could be merged.
212 |
213 | ### Removed
214 |
215 | - Bulletproofs dependencies removal.
216 | - Curve25519 dependencies removal.
217 |
218 | ## [0.3.0] - 2020-03-21
219 |
220 | ### Changed
221 |
222 | - Bulletproofs dependencies change to use dusk-network/bulletproofs "branch=develop".
223 |
224 | ## [0.2.0] - 2020-03-15
225 |
226 | ### Changed
227 |
228 | - Bulletproofs dependencies change to use dusk-network/bulletproofs "branch=dalek_v2".
229 |
230 | ## [0.1.0] - 2020-02-27
231 |
232 | ### Added
233 |
234 | - Basic Hades252 implementation.
235 | - Strategy structure.
236 | - Use `curve25519-dalek` as curve-backend.
237 | - Use `bulletproofs` as proving system.
238 |
239 |
240 | [#120]: https://github.com/dusk-network/Hades252/issues/120
241 | [#99]: https://github.com/dusk-network/Hades252/issues/99
242 | [#98]: https://github.com/dusk-network/Hades252/issues/98
243 | [#96]: https://github.com/dusk-network/Hades252/issues/96
244 | [#87]: https://github.com/dusk-network/Hades252/issues/87
245 | [#86]: https://github.com/dusk-network/Hades252/issues/86
246 | [#85]: (https://github.com/dusk-network/Hades252/issues/85)
247 | [#84]: https://github.com/dusk-network/Hades252/issues/84
248 |
249 |
250 | [unreleased]: https://github.com/dusk-network/dusk-abi/compare/v0.24.1...HEAD
251 | [0.24.1]: https://github.com/dusk-network/dusk-abi/compare/v0.24.0...v0.24.1
252 | [0.24.0]: https://github.com/dusk-network/dusk-abi/compare/v0.23.0...v0.24.0
253 | [0.23.0]: https://github.com/dusk-network/dusk-abi/compare/v0.22.1...v0.23.0
254 | [0.22.1]: https://github.com/dusk-network/dusk-abi/compare/v0.22.0...v0.22.1
255 | [0.22.0]: https://github.com/dusk-network/dusk-abi/compare/v0.21.0...v0.22.0
256 | [0.21.0]: https://github.com/dusk-network/dusk-abi/compare/v0.20.0...v0.21.0
257 | [0.20.0]: https://github.com/dusk-network/dusk-abi/compare/v0.19.0...v0.20.0
258 | [0.19.0]: https://github.com/dusk-network/dusk-abi/compare/v0.16.0...v0.19.0
259 | [0.16.0]: https://github.com/dusk-network/dusk-abi/compare/v0.15.0...v0.16.0
260 | [0.15.0]: https://github.com/dusk-network/dusk-abi/compare/v0.14.0...v0.15.0
261 | [0.14.0]: https://github.com/dusk-network/dusk-abi/compare/v0.13.0...v0.14.0
262 | [0.13.0]: https://github.com/dusk-network/dusk-abi/compare/v0.12.0...v0.13.0
263 | [0.12.0]: https://github.com/dusk-network/dusk-abi/compare/v0.11.0...v0.12.0
264 | [0.11.0]: https://github.com/dusk-network/dusk-abi/compare/v0.10.1...v0.11.0
265 | [0.10.1]: https://github.com/dusk-network/dusk-abi/compare/v0.10.0...v0.10.1
266 | [0.10.0]: https://github.com/dusk-network/dusk-abi/compare/v0.9.0...v0.10.0
267 | [0.9.0]: https://github.com/dusk-network/dusk-abi/compare/v0.8.1...v0.9.0
268 | [0.8.1]: https://github.com/dusk-network/dusk-abi/compare/v0.8.0...v0.8.1
269 | [0.8.0]: https://github.com/dusk-network/dusk-abi/compare/v0.7.0...v0.8.0
270 | [0.7.0]: https://github.com/dusk-network/dusk-abi/compare/v0.6.1...v0.7.0
271 | [0.6.1]: https://github.com/dusk-network/dusk-abi/compare/v0.6.0...v0.6.1
272 | [0.6.0]: https://github.com/dusk-network/dusk-abi/compare/v0.5.0...v0.6.0
273 | [0.5.0]: https://github.com/dusk-network/dusk-abi/compare/v0.4.0...v0.5.0
274 | [0.4.0]: https://github.com/dusk-network/dusk-abi/compare/v0.3.0...v0.4.0
275 | [0.3.0]: https://github.com/dusk-network/dusk-abi/compare/v0.2.0...v0.3.0
276 | [0.2.0]: https://github.com/dusk-network/dusk-abi/compare/v0.1.0...v0.2.0
277 | [0.1.1]: https://github.com/dusk-network/dusk-abi/compare/v0.1.0...v0.1.1
278 | [0.1.0]: https://github.com/dusk-network/dusk-abi/releases/tag/v0.1.0
279 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Hades252
2 |
3 | All of the code under this repository is licensed under the
4 | Mozilla Public License Version 2.0.
5 |
6 | If you have questions or comments, please feel free to email the
7 | authors listed [here](https://github.com/dusk-network/Hades252/blob/master/Cargo.toml#L4).
8 |
9 | For feature requests, suggestions, and bug reports, please open an issue on
10 | [our Github](https://github.com/dusk-network/Hades252). (Or, send us
11 | an email if you're opposed to using Github for whatever reason.)
12 |
13 | Patches are welcomed as pull requests on
14 | [our Github](https://github.com/dusk-network/Hades252), as well as by
15 | email (preferably sent to all of the authors listed in `Cargo.toml`).
16 |
17 | If you want to work on an issue, please let us know in the comments of it and
18 | we will assign it to you.
19 |
20 | If you're new to this repository and you want to contribute, you can
21 | look for the issues tagged the with `good first issue` label. We try to add this tag
22 | to the issues we belive are easy for newcomers.
23 |
24 | If you need any help regarding an issue feel free to ask the authors in the `Draft pull request`
25 | or the issue (or by email if you prefer it by any reason.)
26 |
27 | # Pull Requests
28 |
29 | - Keep your pull requests as `Draft` until they are ready to be reviewed.
30 |
31 | - Be descriptive in the titles of your PRs and also provide good descriptions about
32 | which things are being added, changed, fixed or removed also addressing the corresponding
33 | issue that it is addressing to.
34 | See [How to Write a Git Commit Message]( https://chris.beams.io/posts/git-commit/) for more info.
35 |
36 | - Any pull request that it's not passing our CI tests & builds will not be merged.
37 | This implies incorrect formatting errors, compilation errors, clippy lints, or any
38 | other kind of inconsistency with your code.
39 |
40 | - Do not open PRs that are not linked or related to a previously opened issue.
41 |
42 | - Update the `Unreleased` section of the [CHANGELOG](https://github.com/dusk-network/Hades252/blob/master/CHANGELOG.md)
43 | if your PR includes anything that it's worth to be noticed in there. Avoid adding things
44 | like doc-nitpicks and similar changes which do not affect directly any added,
45 | fixed, removed or changed feature.
46 |
47 | # Code of Conduct
48 |
49 | We follow the [Rust Code of Conduct](http://www.rust-lang.org/conduct.html):
50 |
51 | * We are committed to providing a friendly, safe and welcoming environment for all, regardless
52 | of level of experience, gender identity and expression, sexual orientation, disability, personal
53 | appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic.
54 |
55 | * Please avoid using overtly sexual aliases or other nicknames that might detract from a friendly,
56 | safe and welcoming environment for all.
57 |
58 | * Please be kind and courteous. There’s no need to be mean or rude.
59 |
60 | * Respect that people have differences of opinion and that every design or implementation choice carries
61 | a trade-off and numerous costs. There is seldom a right answer.
62 |
63 | * Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works.
64 |
65 | * We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term “harassment” as including the definition in the Citizen Code of Conduct; if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don’t tolerate behavior that excludes people in socially marginalized groups.
66 |
67 | * Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the Rust moderation team immediately. Whether you’re a regular contributor or a newcomer, we care about making this community a safe place for you and we’ve got your back.
68 |
69 | * Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.
70 |
71 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "dusk-hades"
3 | version = "0.24.1"
4 | edition = "2021"
5 | description ="Implementation of Hades252 permutation algorithm over the Bls12-381 Scalar field."
6 | categories = ["algorithms", "cryptography", "no-std", "wasm"]
7 | keywords = ["cryptography", "zero-knowledge", "crypto"]
8 | license = "MPL-2.0"
9 | repository = "https://github.com/dusk-network/hades252"
10 |
11 | [dependencies]
12 | dusk-bls12_381 = { version = "0.13", default-features = false }
13 | dusk-plonk = { version = "0.19", default-features = false, features = [ "alloc" ], optional = true }
14 |
15 | [dev-dependencies]
16 | rand = "0.8"
17 | ff = {version = "0.13", default-features = false}
18 |
19 | [profile.release]
20 | panic = 'abort'
21 | lto = true
22 | incremental = false
23 | codegen-units = 1
24 |
25 | [features]
26 | plonk = ["dusk-plonk"]
27 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Mozilla Public License Version 2.0
2 | ==================================
3 |
4 | 1. Definitions
5 | --------------
6 |
7 | 1.1. "Contributor"
8 | means each individual or legal entity that creates, contributes to
9 | the creation of, or owns Covered Software.
10 |
11 | 1.2. "Contributor Version"
12 | means the combination of the Contributions of others (if any) used
13 | by a Contributor and that particular Contributor's Contribution.
14 |
15 | 1.3. "Contribution"
16 | means Covered Software of a particular Contributor.
17 |
18 | 1.4. "Covered Software"
19 | means Source Code Form to which the initial Contributor has attached
20 | the notice in Exhibit A, the Executable Form of such Source Code
21 | Form, and Modifications of such Source Code Form, in each case
22 | including portions thereof.
23 |
24 | 1.5. "Incompatible With Secondary Licenses"
25 | means
26 |
27 | (a) that the initial Contributor has attached the notice described
28 | in Exhibit B to the Covered Software; or
29 |
30 | (b) that the Covered Software was made available under the terms of
31 | version 1.1 or earlier of the License, but not also under the
32 | terms of a Secondary License.
33 |
34 | 1.6. "Executable Form"
35 | means any form of the work other than Source Code Form.
36 |
37 | 1.7. "Larger Work"
38 | means a work that combines Covered Software with other material, in
39 | a separate file or files, that is not Covered Software.
40 |
41 | 1.8. "License"
42 | means this document.
43 |
44 | 1.9. "Licensable"
45 | means having the right to grant, to the maximum extent possible,
46 | whether at the time of the initial grant or subsequently, any and
47 | all of the rights conveyed by this License.
48 |
49 | 1.10. "Modifications"
50 | means any of the following:
51 |
52 | (a) any file in Source Code Form that results from an addition to,
53 | deletion from, or modification of the contents of Covered
54 | Software; or
55 |
56 | (b) any new file in Source Code Form that contains any Covered
57 | Software.
58 |
59 | 1.11. "Patent Claims" of a Contributor
60 | means any patent claim(s), including without limitation, method,
61 | process, and apparatus claims, in any patent Licensable by such
62 | Contributor that would be infringed, but for the grant of the
63 | License, by the making, using, selling, offering for sale, having
64 | made, import, or transfer of either its Contributions or its
65 | Contributor Version.
66 |
67 | 1.12. "Secondary License"
68 | means either the GNU General Public License, Version 2.0, the GNU
69 | Lesser General Public License, Version 2.1, the GNU Affero General
70 | Public License, Version 3.0, or any later versions of those
71 | licenses.
72 |
73 | 1.13. "Source Code Form"
74 | means the form of the work preferred for making modifications.
75 |
76 | 1.14. "You" (or "Your")
77 | means an individual or a legal entity exercising rights under this
78 | License. For legal entities, "You" includes any entity that
79 | controls, is controlled by, or is under common control with You. For
80 | purposes of this definition, "control" means (a) the power, direct
81 | or indirect, to cause the direction or management of such entity,
82 | whether by contract or otherwise, or (b) ownership of more than
83 | fifty percent (50%) of the outstanding shares or beneficial
84 | ownership of such entity.
85 |
86 | 2. License Grants and Conditions
87 | --------------------------------
88 |
89 | 2.1. Grants
90 |
91 | Each Contributor hereby grants You a world-wide, royalty-free,
92 | non-exclusive license:
93 |
94 | (a) under intellectual property rights (other than patent or trademark)
95 | Licensable by such Contributor to use, reproduce, make available,
96 | modify, display, perform, distribute, and otherwise exploit its
97 | Contributions, either on an unmodified basis, with Modifications, or
98 | as part of a Larger Work; and
99 |
100 | (b) under Patent Claims of such Contributor to make, use, sell, offer
101 | for sale, have made, import, and otherwise transfer either its
102 | Contributions or its Contributor Version.
103 |
104 | 2.2. Effective Date
105 |
106 | The licenses granted in Section 2.1 with respect to any Contribution
107 | become effective for each Contribution on the date the Contributor first
108 | distributes such Contribution.
109 |
110 | 2.3. Limitations on Grant Scope
111 |
112 | The licenses granted in this Section 2 are the only rights granted under
113 | this License. No additional rights or licenses will be implied from the
114 | distribution or licensing of Covered Software under this License.
115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a
116 | Contributor:
117 |
118 | (a) for any code that a Contributor has removed from Covered Software;
119 | or
120 |
121 | (b) for infringements caused by: (i) Your and any other third party's
122 | modifications of Covered Software, or (ii) the combination of its
123 | Contributions with other software (except as part of its Contributor
124 | Version); or
125 |
126 | (c) under Patent Claims infringed by Covered Software in the absence of
127 | its Contributions.
128 |
129 | This License does not grant any rights in the trademarks, service marks,
130 | or logos of any Contributor (except as may be necessary to comply with
131 | the notice requirements in Section 3.4).
132 |
133 | 2.4. Subsequent Licenses
134 |
135 | No Contributor makes additional grants as a result of Your choice to
136 | distribute the Covered Software under a subsequent version of this
137 | License (see Section 10.2) or under the terms of a Secondary License (if
138 | permitted under the terms of Section 3.3).
139 |
140 | 2.5. Representation
141 |
142 | Each Contributor represents that the Contributor believes its
143 | Contributions are its original creation(s) or it has sufficient rights
144 | to grant the rights to its Contributions conveyed by this License.
145 |
146 | 2.6. Fair Use
147 |
148 | This License is not intended to limit any rights You have under
149 | applicable copyright doctrines of fair use, fair dealing, or other
150 | equivalents.
151 |
152 | 2.7. Conditions
153 |
154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155 | in Section 2.1.
156 |
157 | 3. Responsibilities
158 | -------------------
159 |
160 | 3.1. Distribution of Source Form
161 |
162 | All distribution of Covered Software in Source Code Form, including any
163 | Modifications that You create or to which You contribute, must be under
164 | the terms of this License. You must inform recipients that the Source
165 | Code Form of the Covered Software is governed by the terms of this
166 | License, and how they can obtain a copy of this License. You may not
167 | attempt to alter or restrict the recipients' rights in the Source Code
168 | Form.
169 |
170 | 3.2. Distribution of Executable Form
171 |
172 | If You distribute Covered Software in Executable Form then:
173 |
174 | (a) such Covered Software must also be made available in Source Code
175 | Form, as described in Section 3.1, and You must inform recipients of
176 | the Executable Form how they can obtain a copy of such Source Code
177 | Form by reasonable means in a timely manner, at a charge no more
178 | than the cost of distribution to the recipient; and
179 |
180 | (b) You may distribute such Executable Form under the terms of this
181 | License, or sublicense it under different terms, provided that the
182 | license for the Executable Form does not attempt to limit or alter
183 | the recipients' rights in the Source Code Form under this License.
184 |
185 | 3.3. Distribution of a Larger Work
186 |
187 | You may create and distribute a Larger Work under terms of Your choice,
188 | provided that You also comply with the requirements of this License for
189 | the Covered Software. If the Larger Work is a combination of Covered
190 | Software with a work governed by one or more Secondary Licenses, and the
191 | Covered Software is not Incompatible With Secondary Licenses, this
192 | License permits You to additionally distribute such Covered Software
193 | under the terms of such Secondary License(s), so that the recipient of
194 | the Larger Work may, at their option, further distribute the Covered
195 | Software under the terms of either this License or such Secondary
196 | License(s).
197 |
198 | 3.4. Notices
199 |
200 | You may not remove or alter the substance of any license notices
201 | (including copyright notices, patent notices, disclaimers of warranty,
202 | or limitations of liability) contained within the Source Code Form of
203 | the Covered Software, except that You may alter any license notices to
204 | the extent required to remedy known factual inaccuracies.
205 |
206 | 3.5. Application of Additional Terms
207 |
208 | You may choose to offer, and to charge a fee for, warranty, support,
209 | indemnity or liability obligations to one or more recipients of Covered
210 | Software. However, You may do so only on Your own behalf, and not on
211 | behalf of any Contributor. You must make it absolutely clear that any
212 | such warranty, support, indemnity, or liability obligation is offered by
213 | You alone, and You hereby agree to indemnify every Contributor for any
214 | liability incurred by such Contributor as a result of warranty, support,
215 | indemnity or liability terms You offer. You may include additional
216 | disclaimers of warranty and limitations of liability specific to any
217 | jurisdiction.
218 |
219 | 4. Inability to Comply Due to Statute or Regulation
220 | ---------------------------------------------------
221 |
222 | If it is impossible for You to comply with any of the terms of this
223 | License with respect to some or all of the Covered Software due to
224 | statute, judicial order, or regulation then You must: (a) comply with
225 | the terms of this License to the maximum extent possible; and (b)
226 | describe the limitations and the code they affect. Such description must
227 | be placed in a text file included with all distributions of the Covered
228 | Software under this License. Except to the extent prohibited by statute
229 | or regulation, such description must be sufficiently detailed for a
230 | recipient of ordinary skill to be able to understand it.
231 |
232 | 5. Termination
233 | --------------
234 |
235 | 5.1. The rights granted under this License will terminate automatically
236 | if You fail to comply with any of its terms. However, if You become
237 | compliant, then the rights granted under this License from a particular
238 | Contributor are reinstated (a) provisionally, unless and until such
239 | Contributor explicitly and finally terminates Your grants, and (b) on an
240 | ongoing basis, if such Contributor fails to notify You of the
241 | non-compliance by some reasonable means prior to 60 days after You have
242 | come back into compliance. Moreover, Your grants from a particular
243 | Contributor are reinstated on an ongoing basis if such Contributor
244 | notifies You of the non-compliance by some reasonable means, this is the
245 | first time You have received notice of non-compliance with this License
246 | from such Contributor, and You become compliant prior to 30 days after
247 | Your receipt of the notice.
248 |
249 | 5.2. If You initiate litigation against any entity by asserting a patent
250 | infringement claim (excluding declaratory judgment actions,
251 | counter-claims, and cross-claims) alleging that a Contributor Version
252 | directly or indirectly infringes any patent, then the rights granted to
253 | You by any and all Contributors for the Covered Software under Section
254 | 2.1 of this License shall terminate.
255 |
256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257 | end user license agreements (excluding distributors and resellers) which
258 | have been validly granted by You or Your distributors under this License
259 | prior to termination shall survive termination.
260 |
261 | ************************************************************************
262 | * *
263 | * 6. Disclaimer of Warranty *
264 | * ------------------------- *
265 | * *
266 | * Covered Software is provided under this License on an "as is" *
267 | * basis, without warranty of any kind, either expressed, implied, or *
268 | * statutory, including, without limitation, warranties that the *
269 | * Covered Software is free of defects, merchantable, fit for a *
270 | * particular purpose or non-infringing. The entire risk as to the *
271 | * quality and performance of the Covered Software is with You. *
272 | * Should any Covered Software prove defective in any respect, You *
273 | * (not any Contributor) assume the cost of any necessary servicing, *
274 | * repair, or correction. This disclaimer of warranty constitutes an *
275 | * essential part of this License. No use of any Covered Software is *
276 | * authorized under this License except under this disclaimer. *
277 | * *
278 | ************************************************************************
279 |
280 | ************************************************************************
281 | * *
282 | * 7. Limitation of Liability *
283 | * -------------------------- *
284 | * *
285 | * Under no circumstances and under no legal theory, whether tort *
286 | * (including negligence), contract, or otherwise, shall any *
287 | * Contributor, or anyone who distributes Covered Software as *
288 | * permitted above, be liable to You for any direct, indirect, *
289 | * special, incidental, or consequential damages of any character *
290 | * including, without limitation, damages for lost profits, loss of *
291 | * goodwill, work stoppage, computer failure or malfunction, or any *
292 | * and all other commercial damages or losses, even if such party *
293 | * shall have been informed of the possibility of such damages. This *
294 | * limitation of liability shall not apply to liability for death or *
295 | * personal injury resulting from such party's negligence to the *
296 | * extent applicable law prohibits such limitation. Some *
297 | * jurisdictions do not allow the exclusion or limitation of *
298 | * incidental or consequential damages, so this exclusion and *
299 | * limitation may not apply to You. *
300 | * *
301 | ************************************************************************
302 |
303 | 8. Litigation
304 | -------------
305 |
306 | Any litigation relating to this License may be brought only in the
307 | courts of a jurisdiction where the defendant maintains its principal
308 | place of business and such litigation shall be governed by laws of that
309 | jurisdiction, without reference to its conflict-of-law provisions.
310 | Nothing in this Section shall prevent a party's ability to bring
311 | cross-claims or counter-claims.
312 |
313 | 9. Miscellaneous
314 | ----------------
315 |
316 | This License represents the complete agreement concerning the subject
317 | matter hereof. If any provision of this License is held to be
318 | unenforceable, such provision shall be reformed only to the extent
319 | necessary to make it enforceable. Any law or regulation which provides
320 | that the language of a contract shall be construed against the drafter
321 | shall not be used to construe this License against a Contributor.
322 |
323 | 10. Versions of the License
324 | ---------------------------
325 |
326 | 10.1. New Versions
327 |
328 | Mozilla Foundation is the license steward. Except as provided in Section
329 | 10.3, no one other than the license steward has the right to modify or
330 | publish new versions of this License. Each version will be given a
331 | distinguishing version number.
332 |
333 | 10.2. Effect of New Versions
334 |
335 | You may distribute the Covered Software under the terms of the version
336 | of the License under which You originally received the Covered Software,
337 | or under the terms of any subsequent version published by the license
338 | steward.
339 |
340 | 10.3. Modified Versions
341 |
342 | If you create software not governed by this License, and you want to
343 | create a new license for such software, you may create and use a
344 | modified version of this License if you rename the license and remove
345 | any references to the name of the license steward (except to note that
346 | such modified license differs from this License).
347 |
348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary
349 | Licenses
350 |
351 | If You choose to distribute Source Code Form that is Incompatible With
352 | Secondary Licenses under the terms of this version of the License, the
353 | notice described in Exhibit B of this License must be attached.
354 |
355 | Exhibit A - Source Code Form License Notice
356 | -------------------------------------------
357 |
358 | This Source Code Form is subject to the terms of the Mozilla Public
359 | License, v. 2.0. If a copy of the MPL was not distributed with this
360 | file, You can obtain one at http://mozilla.org/MPL/2.0/.
361 |
362 | If it is not possible or desirable to put the notice in a particular
363 | file, then You may include the notice in a location (such as a LICENSE
364 | file in a relevant directory) where a recipient would be likely to look
365 | for such a notice.
366 |
367 | You may add additional accurate notices of copyright ownership.
368 |
369 | Exhibit B - "Incompatible With Secondary Licenses" Notice
370 | ---------------------------------------------------------
371 |
372 | This Source Code Form is "Incompatible With Secondary Licenses", as
373 | defined by the Mozilla Public License, v. 2.0.
374 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | REPO_NAME := $(shell git config --get-regexp remote.origin.url | sed "s/.*dusk-network\/\(.*\)\.git/\1/")
2 | PACKAGE_NAME := $(shell cargo metadata --no-deps --format-version=1 | python -c "import sys, json; print json.load(sys.stdin)['packages'][0]['name']")
3 | REPO_BADGE_URL := "https://img.shields.io/badge/github-$(shell echo $(REPO_NAME) | sed "s/-/--/g")-brightgreen?logo=github"
4 | META := ""
5 |
6 | define generate_docs
7 | @echo $(META) > target/doc/index.html && \
8 | curl -o 'target/doc/badge.svg' 'https://img.shields.io/badge/docs-latest-blue?logo=rust' && \
9 | curl -o 'target/doc/repo-badge.svg' $(REPO_BADGE_URL) && \
10 | curl -L https://github.com/davisp/ghp-import/archive/master.tar.gz | tar --strip-components 1 -C $1 -xz
11 | $1/ghp_import.py -n target/doc
12 | rm -rf $1
13 | endef
14 |
15 | help: ## Display this help screen
16 | @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'
17 |
18 | doc: ## Generate documentation
19 | @cargo +nightly rustdoc --lib --all-features
20 |
21 | doc-internal: ## Generate documentation with private items
22 | @cargo +nightly rustdoc --lib -- --document-private-items --all-features
23 |
24 | .PHONY: help doc doc-internal publish-doc
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | [](https://github.com/dusk-network/hades252)
3 | [](https://docs.rs/dusk-hades/)
4 |
5 | # Hades252 (deprecated)
6 |
7 | | :exclamation: This crate is deprecated. |
8 | |---------------------------------------------|
9 | The hades permutation moved into [`dusk-poseidon`](https://github.com/dusk-network/Poseidon252).
10 |
11 | Implementation of Hades252 permutation algorithm over the Bls12-381 Scalar field.
12 |
13 | ## Documentation
14 |
15 | To generate the `Hades252` documentation:
16 |
17 | ```sh
18 | make doc
19 | make doc-internal
20 | ```
21 |
22 | ## Use
23 |
24 | Run the following to add `Hades252` to the dependency section of your project's 'Cargo.toml':
25 |
26 | ```toml
27 | cargo add dusk-hades
28 | ```
29 |
30 | `Hades252` has a `width` equals to `5`; it's possible to use a different value,
31 | see [How to generate the assets](assets/HOWTO.md).
32 |
33 | ## Parameters
34 |
35 | - p = `0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`
36 |
37 | - Security level is 117 -120 bits of security [NCCG] bits.
38 |
39 | - width = 5
40 |
41 | - Number of full rounds = 8 . There are four full rounds at the beginning and four full rounds at the end,
42 | where each full round has `WIDTH` quintic S-Boxes.
43 |
44 | - Number of partial rounds = 59, where each partial round has one quintic S-Box and (width-1) identity functions.
45 |
46 | - Number of round constants = 960
47 |
48 | ## Example for `ScalarStrategy`
49 |
50 | ```rust
51 | use dusk_bls12_381::BlsScalar;
52 | use dusk_hades::{ScalarStrategy, Strategy, WIDTH};
53 |
54 | // Generate the inputs that will permute.
55 | // The number of values we can input is equivalent to `WIDTH`
56 |
57 | let input = vec![BlsScalar::from(1u64); dusk_hades::WIDTH];
58 | let mut output = input.clone();
59 |
60 | let mut strategy = ScalarStrategy::new();
61 | strategy.perm(output.as_mut_slice());
62 |
63 | assert_ne!(&input, &output);
64 | assert_eq!(input.len(), output.len());
65 | ```
66 |
67 | ## Deviations
68 |
69 | - Round constants for the full rounds are generated following: [https://extgit.iaik.tugraz.at/krypto/hadesmimc/blob/master/code/calc_round_numbers.py](https://extgit.iaik.tugraz.at/krypto/hadesmimc/blob/master/code/calc_round_numbers.py)
70 |
71 | - The MDS matrix is a cauchy matrix, the method used to generate it, is noted in section "Concrete Instantiations Poseidon and Starkad"
72 |
73 | ## Reference
74 |
75 | [https://eprint.iacr.org/2019/458.pdf](https://eprint.iacr.org/2019/458.pdf)
76 |
--------------------------------------------------------------------------------
/assets/HOWTO.md:
--------------------------------------------------------------------------------
1 | # How to generate the assets
2 |
3 | The `ark.bin` and `mds.bin` files in this folder are generated using the snippets below:
4 |
5 | ## Filename: ark.bin
6 |
7 | ```rust
8 | // This Source Code Form is subject to the terms of the Mozilla Public
9 | // License, v. 2.0. If a copy of the MPL was not distributed with this
10 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
11 | //
12 | // Copyright (c) DUSK NETWORK. All rights reserved.
13 |
14 | use dusk_bls12_381::BlsScalar;
15 | use sha2::{Digest, Sha512};
16 | use std::fs;
17 | use std::io::Write;
18 |
19 | const CONSTANTS: usize = 960;
20 |
21 | fn constants() -> [BlsScalar; CONSTANTS] {
22 | let mut cnst = [BlsScalar::zero(); CONSTANTS];
23 | let mut p = BlsScalar::one();
24 | let mut bytes = b"poseidon-for-plonk".to_vec();
25 |
26 | cnst.iter_mut().for_each(|c| {
27 | let mut hasher = Sha512::new();
28 | hasher.input(bytes.as_slice());
29 | bytes = hasher.result().to_vec();
30 |
31 | let mut v = [0x00u8; 64];
32 | v.copy_from_slice(&bytes[0..64]);
33 |
34 | *c = BlsScalar::from_bytes_wide(&v) + p;
35 | p = *c;
36 | });
37 |
38 | cnst
39 | }
40 |
41 | pub(crate) fn write_to(filename: &str) -> std::io::Result<()> {
42 | let mut buf: Vec = vec![];
43 |
44 | constants().iter().for_each(|c| {
45 | c.internal_repr()
46 | .iter()
47 | .for_each(|r| buf.extend_from_slice(&(*r).to_le_bytes()));
48 | });
49 |
50 | let mut file = fs::File::create(filename)?;
51 | file.write_all(&buf)?;
52 | Ok(())
53 | }
54 | ```
55 |
56 | ## Filename: mds.bin
57 |
58 | ```rust
59 | // This Source Code Form is subject to the terms of the Mozilla Public
60 | // License, v. 2.0. If a copy of the MPL was not distributed with this
61 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
62 | //
63 | // Copyright (c) DUSK NETWORK. All rights reserved.
64 |
65 | use dusk_bls12_381::BlsScalar;
66 | use std::fs;
67 | use std::io::Write;
68 |
69 | const WIDTH: usize = 5;
70 |
71 | fn mds() -> [[BlsScalar; WIDTH]; WIDTH] {
72 | let mut matrix = [[BlsScalar::zero(); WIDTH]; WIDTH];
73 | let mut xs = [BlsScalar::zero(); WIDTH];
74 | let mut ys = [BlsScalar::zero(); WIDTH];
75 |
76 | // Generate x and y values deterministically for the cauchy matrix
77 | // where x[i] != y[i] to allow the values to be inverted
78 | // and there are no duplicates in the x vector or y vector, so that the determinant is always non-zero
79 | // [a b]
80 | // [c d]
81 | // det(M) = (ad - bc) ; if a == b and c == d => det(M) =0
82 | // For an MDS matrix, every possible mxm submatrix, must have det(M) != 0
83 | (0..WIDTH).for_each(|i| {
84 | xs[i] = BlsScalar::from(i as u64);
85 | ys[i] = BlsScalar::from((i + WIDTH) as u64);
86 | });
87 |
88 | let mut m = 0;
89 | (0..WIDTH).for_each(|i| {
90 | (0..WIDTH).for_each(|j| {
91 | matrix[m][j] = (xs[i] + ys[j]).invert().unwrap();
92 | });
93 | m += 1;
94 | });
95 |
96 | matrix
97 | }
98 |
99 | pub(crate) fn write_to(filename: &str) -> std::io::Result<()> {
100 | let mut buf: Vec = vec![];
101 |
102 | mds().iter().for_each(|row| {
103 | row.iter().for_each(|c| {
104 | c.internal_repr()
105 | .iter()
106 | .for_each(|r| buf.extend_from_slice(&(*r).to_le_bytes()));
107 | });
108 | });
109 |
110 | let mut file = fs::File::create(filename)?;
111 | file.write_all(&buf)?;
112 | Ok(())
113 | }
114 | ```
115 |
--------------------------------------------------------------------------------
/assets/ark.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dusk-network/Hades252/0775be969c5f284ab256f04dfc151c60a3179f44/assets/ark.bin
--------------------------------------------------------------------------------
/assets/mds.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dusk-network/Hades252/0775be969c5f284ab256f04dfc151c60a3179f44/assets/mds.bin
--------------------------------------------------------------------------------
/build.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | /// Build file for the dusk-hades crate.
8 | ///
9 | /// The purpose of this file is to add a deprecation warning at compile time.
10 |
11 | #[deprecated(
12 | note = "This crate is not in active development anymore, use 'dusk-poseidon' instead."
13 | )]
14 | const DEPRECATED: bool = true;
15 |
16 | fn main() {
17 | // Ensure we run the build script again when only 'build.rs' has changed
18 | println!("cargo:rerun-if-changed=build.rs");
19 |
20 | #[allow(deprecated)]
21 | let _dusk_hades = DEPRECATED;
22 | }
23 |
--------------------------------------------------------------------------------
/codecov.yml:
--------------------------------------------------------------------------------
1 | codecov:
2 | require_ci_to_pass: yes # If travis does not pass, no reports will be publlished/updated
3 |
4 | coverage:
5 | range: 80..100
6 | round: down
7 | precision: 2
8 |
9 | status:
10 | project: # measuring the overall project coverage
11 | default: # context, you can create multiple ones with custom titles
12 | enabled: yes # must be yes|true to enable this status
13 | target: 90 # specify the target coverage for each commit status
14 | # option: "auto" (must increase from parent commit or pull request base)
15 | # option: "X%" a static target percentage to hit
16 | threshold: 5 # allowed to drop X% and still result in a "success" commit status
17 | if_not_found: success # if parent is not found report status as success, error, or failure
18 | if_ci_failed: error # if ci fails report status as success, error, or failure
19 | patch:
20 | default:
21 | enabled: no
--------------------------------------------------------------------------------
/rust-toolchain.toml:
--------------------------------------------------------------------------------
1 | [toolchain]
2 | channel = "nightly-2023-08-24"
3 | components = ["rustfmt", "clippy"]
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | #![deny(missing_docs)]
8 | #![no_std]
9 | #![doc = include_str!("../README.md")]
10 | #![deprecated = "This crate is deprecated. The code was moved to dusk-poseidon."]
11 |
12 | mod mds_matrix;
13 | mod round_constants;
14 |
15 | /// Strategies implemented for the Hades252 algorithm.
16 | mod strategies;
17 |
18 | /// Total ammount of full rounds that will be applied.
19 | /// This is expressed as `RF` in the paper.
20 | pub const TOTAL_FULL_ROUNDS: usize = 8;
21 |
22 | /// Total ammount of partial rounds that will be applied.
23 | /// This is expressed as `Rp` in the paper.
24 | pub const PARTIAL_ROUNDS: usize = 59;
25 |
26 | /// Maximum input width for the rounds
27 | pub const WIDTH: usize = 5;
28 |
29 | #[cfg(feature = "plonk")]
30 | pub use strategies::GadgetStrategy;
31 | pub use strategies::{ScalarStrategy, Strategy};
32 |
33 | pub(crate) const fn u64_from_buffer(buf: &[u8; N], i: usize) -> u64 {
34 | u64::from_le_bytes([
35 | buf[i],
36 | buf[i + 1],
37 | buf[i + 2],
38 | buf[i + 3],
39 | buf[i + 4],
40 | buf[i + 5],
41 | buf[i + 6],
42 | buf[i + 7],
43 | ])
44 | }
45 |
--------------------------------------------------------------------------------
/src/mds_matrix.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | #![allow(non_snake_case)]
8 | use crate::u64_from_buffer;
9 | use crate::WIDTH;
10 | use dusk_bls12_381::BlsScalar;
11 |
12 | /// Represents a `static reference` to the
13 | /// `Maximum Distance Separable Matrix -> MDS_MATRIX`
14 | /// of `(WIDTH x WIDTH)`.
15 | ///
16 | /// This matrix is loaded from the `mds.bin` file where
17 | /// is pre-computed and represented in bytes.
18 | pub const MDS_MATRIX: [[BlsScalar; WIDTH]; WIDTH] = {
19 | let bytes = include_bytes!("../assets/mds.bin");
20 | let mut mds = [[BlsScalar::zero(); WIDTH]; WIDTH];
21 | let mut k = 0;
22 | let mut i = 0;
23 |
24 | while i < WIDTH {
25 | let mut j = 0;
26 | while j < WIDTH {
27 | let a = u64_from_buffer(bytes, k);
28 | let b = u64_from_buffer(bytes, k + 8);
29 | let c = u64_from_buffer(bytes, k + 16);
30 | let d = u64_from_buffer(bytes, k + 24);
31 | k += 32;
32 |
33 | mds[i][j] = BlsScalar::from_raw([a, b, c, d]);
34 | j += 1;
35 | }
36 | i += 1;
37 | }
38 |
39 | mds
40 | };
41 |
--------------------------------------------------------------------------------
/src/round_constants.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | //! This module is designed to load from `ark.bin` the 960
8 | //! constants used as `round_constants`.
9 | //!
10 | //! The constants were originally computed using:
11 | //! https://extgit.iaik.tugraz.at/krypto/hadesmimc/blob/master/code/calc_round_numbers.py
12 | //! and then mapped onto `BlsScalar` in the Bls12_381 scalar field.
13 | #![allow(non_snake_case)]
14 |
15 | use crate::u64_from_buffer;
16 | use dusk_bls12_381::BlsScalar;
17 |
18 | const CONSTANTS: usize = 960;
19 |
20 | /// `ROUND_CONSTANTS` constists on a static reference
21 | /// that points to the pre-loaded 960 Fq constants.
22 | ///
23 | /// This 960 `BlsScalar` constants are loaded from `ark.bin`
24 | /// where all of the `BlsScalar`s are represented in buf.
25 | ///
26 | /// This round constants have been taken from:
27 | /// https://extgit.iaik.tugraz.at/krypto/hadesmimc/blob/master/code/calc_round_numbers.py
28 | /// and then mapped onto `Fq` in the Ristretto scalar field.
29 | pub const ROUND_CONSTANTS: [BlsScalar; CONSTANTS] = {
30 | let bytes = include_bytes!("../assets/ark.bin");
31 | let mut cnst = [BlsScalar::zero(); CONSTANTS];
32 |
33 | let mut i = 0;
34 | let mut j = 0;
35 | while i < bytes.len() {
36 | let a = u64_from_buffer(bytes, i);
37 | let b = u64_from_buffer(bytes, i + 8);
38 | let c = u64_from_buffer(bytes, i + 16);
39 | let d = u64_from_buffer(bytes, i + 24);
40 |
41 | cnst[j] = BlsScalar::from_raw([a, b, c, d]);
42 | j += 1;
43 |
44 | i += 32;
45 | }
46 |
47 | cnst
48 | };
49 |
50 | #[cfg(test)]
51 | mod test {
52 | use super::ROUND_CONSTANTS;
53 | use dusk_bls12_381::BlsScalar;
54 |
55 | #[test]
56 | fn test_round_constants() {
57 | // Check each element is non-zero
58 | let zero = BlsScalar::zero();
59 | let has_zero = ROUND_CONSTANTS.iter().any(|&x| x == zero);
60 | for ctant in ROUND_CONSTANTS.iter() {
61 | let bytes = ctant.to_bytes();
62 | assert!(&BlsScalar::from_bytes(&bytes).unwrap() == ctant);
63 | }
64 | assert!(!has_zero);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/strategies.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | //! This module contains an implementation of the `Hades252`
8 | //! strategy algorithm specifically designed to work outside of
9 | //! Rank 1 Constraint Systems (R1CS) or other custom Constraint
10 | //! Systems such as Add/Mul/Custom plonk gate-circuits.
11 | //!
12 | //! The inputs of the permutation function have to be explicitly
13 | //! over the BlsScalar Field of the bls12_381 curve so working over
14 | //! `Fq = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`.
15 |
16 | use crate::{round_constants::ROUND_CONSTANTS, PARTIAL_ROUNDS, TOTAL_FULL_ROUNDS};
17 | use dusk_bls12_381::BlsScalar;
18 |
19 | /// Strategy for zero-knowledge plonk circuits
20 | #[cfg(feature = "plonk")]
21 | mod gadget;
22 |
23 | /// Strategy for scalars
24 | mod scalar;
25 |
26 | #[cfg(feature = "plonk")]
27 | pub use gadget::GadgetStrategy;
28 | pub use scalar::ScalarStrategy;
29 |
30 | /// Defines the Hades252 strategy algorithm.
31 | pub trait Strategy {
32 | /// Fetch the next round constant from an iterator
33 | fn next_c<'b, I>(constants: &mut I) -> BlsScalar
34 | where
35 | I: Iterator- ,
36 | {
37 | constants
38 | .next()
39 | .copied()
40 | .expect("Hades252 out of ARK constants")
41 | }
42 |
43 | /// Add round keys to a set of `StrategyInput`.
44 | ///
45 | /// This round key addition also known as `ARK` is used to
46 | /// reach `Confusion and Diffusion` properties for the algorithm.
47 | ///
48 | /// Basically it allows to destroy any connection between the
49 | /// inputs and the outputs of the function.
50 | fn add_round_key<'b, I>(&mut self, constants: &mut I, words: &mut [T])
51 | where
52 | I: Iterator
- ;
53 |
54 | /// Computes `input ^ 5 (mod Fp)`
55 | ///
56 | /// The modulo depends on the input you use. In our case
57 | /// the modulo is done in respect of the `bls12_381 scalar field`
58 | /// == `0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001`.
59 | fn quintic_s_box(&mut self, value: &mut T);
60 |
61 | /// Multiply the values for MDS matrix during the
62 | /// full rounds application.
63 | fn mul_matrix<'b, I>(&mut self, constants: &mut I, values: &mut [T])
64 | where
65 | I: Iterator
- ;
66 |
67 | /// Applies a `Partial Round` also known as a
68 | /// `Partial S-Box layer` to a set of inputs.
69 | ///
70 | /// ### A partial round has 3 steps on every iteration:
71 | ///
72 | /// - Add round keys to each word. Also known as `ARK`.
73 | /// - Apply `quintic S-Box` **just to the last element of
74 | /// the words generated from the first step.** This is also known
75 | /// as a `Sub Words` operation.
76 | /// - Multiplies the output words from the second step by
77 | /// the `MDS_MATRIX`.
78 | /// This is known as the `Mix Layer`.
79 | fn apply_partial_round<'b, I>(&mut self, constants: &mut I, words: &mut [T])
80 | where
81 | I: Iterator
- ,
82 | {
83 | let last = words.len() - 1;
84 |
85 | // Add round keys to each word
86 | self.add_round_key(constants, words);
87 |
88 | // Then apply quintic s-box
89 | self.quintic_s_box(&mut words[last]);
90 |
91 | // Multiply this result by the MDS matrix
92 | self.mul_matrix(constants, words);
93 | }
94 |
95 | /// Applies a `Full Round` also known as a
96 | /// `Full S-Box layer` to a set of inputs.
97 | ///
98 | /// A full round has 3 steps on every iteration:
99 | ///
100 | /// - Add round keys to each word. Also known as `ARK`.
101 | /// - Apply `quintic S-Box` **to all of the words generated
102 | /// from the first step.**
103 | /// This is also known as a `Sub Words` operation.
104 | /// - Multiplies the output words from the second step by
105 | /// the `MDS_MATRIX`.
106 | /// This is known as the `Mix Layer`.
107 | fn apply_full_round<'a, I>(&mut self, constants: &mut I, words: &mut [T])
108 | where
109 | I: Iterator
- ,
110 | {
111 | // Add round keys to each word
112 | self.add_round_key(constants, words);
113 |
114 | // Then apply quintic s-box
115 | words.iter_mut().for_each(|w| self.quintic_s_box(w));
116 |
117 | // Multiply this result by the MDS matrix
118 | self.mul_matrix(constants, words);
119 | }
120 |
121 | /// Applies a `permutation-round` of the `Hades252` strategy.
122 | ///
123 | /// It returns a vec of `WIDTH` outputs as a result which should be
124 | /// a randomly permuted version of the input.
125 | ///
126 | /// In general, the same round function is iterated enough times
127 | /// to make sure that any symmetries and structural properties that
128 | /// might exist in the round function vanish.
129 | ///
130 | /// This `permutation` is a 3-step process that:
131 | ///
132 | /// - Applies twice the half of the `FULL_ROUNDS`
133 | /// (which can be understood as linear ops).
134 | ///
135 | /// - In the middle step it applies the `PARTIAL_ROUDS`
136 | /// (which can be understood as non-linear ops).
137 | ///
138 | /// This structure allows to minimize the number of non-linear
139 | /// ops while mantaining the security.
140 | fn perm(&mut self, data: &mut [T]) {
141 | let mut constants = ROUND_CONSTANTS.iter();
142 |
143 | // Apply R_f full rounds
144 | for _ in 0..TOTAL_FULL_ROUNDS / 2 {
145 | self.apply_full_round(&mut constants, data);
146 | }
147 |
148 | // Apply R_P partial rounds
149 | for _ in 0..PARTIAL_ROUNDS {
150 | self.apply_partial_round(&mut constants, data);
151 | }
152 |
153 | // Apply R_f full rounds
154 | for _ in 0..TOTAL_FULL_ROUNDS / 2 {
155 | self.apply_full_round(&mut constants, data);
156 | }
157 | }
158 |
159 | /// Return the total rounds count
160 | fn rounds() -> usize {
161 | TOTAL_FULL_ROUNDS + PARTIAL_ROUNDS
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/strategies/gadget.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | use super::Strategy;
8 | use crate::mds_matrix::MDS_MATRIX;
9 | use crate::WIDTH;
10 | use dusk_bls12_381::BlsScalar;
11 | use dusk_plonk::prelude::*;
12 |
13 | /// Implements a Hades252 strategy for `Witness` as input values.
14 | /// Requires a reference to a `ConstraintSystem`.
15 | pub struct GadgetStrategy<'a> {
16 | /// A reference to the constraint system used by the gadgets
17 | cs: &'a mut Composer,
18 | count: usize,
19 | }
20 |
21 | impl<'a> GadgetStrategy<'a> {
22 | /// Constructs a new `GadgetStrategy` with the constraint system.
23 | pub fn new(cs: &'a mut Composer) -> Self {
24 | GadgetStrategy { cs, count: 0 }
25 | }
26 |
27 | /// Perform the hades permutation on a plonk circuit
28 | pub fn gadget(composer: &'a mut Composer, x: &mut [Witness]) {
29 | let mut strategy = GadgetStrategy::new(composer);
30 |
31 | strategy.perm(x);
32 | }
33 | }
34 |
35 | impl AsMut for GadgetStrategy<'_> {
36 | fn as_mut(&mut self) -> &mut Composer {
37 | self.cs
38 | }
39 | }
40 |
41 | impl<'a> Strategy for GadgetStrategy<'a> {
42 | fn add_round_key<'b, I>(&mut self, constants: &mut I, words: &mut [Witness])
43 | where
44 | I: Iterator
- ,
45 | {
46 | // Add only for the first round.
47 | //
48 | // The remainder ARC are performed with the constant appended
49 | // to the linear layer
50 | if self.count == 0 {
51 | words.iter_mut().for_each(|w| {
52 | let constant = Self::next_c(constants);
53 | let constraint = Constraint::new().left(1).a(*w).constant(constant);
54 |
55 | *w = self.cs.gate_add(constraint);
56 | });
57 | }
58 | }
59 |
60 | fn quintic_s_box(&mut self, value: &mut Witness) {
61 | let constraint = Constraint::new().mult(1).a(*value).b(*value);
62 | let v2 = self.cs.gate_mul(constraint);
63 |
64 | let constraint = Constraint::new().mult(1).a(v2).b(v2);
65 | let v4 = self.cs.gate_mul(constraint);
66 |
67 | let constraint = Constraint::new().mult(1).a(v4).b(*value);
68 | *value = self.cs.gate_mul(constraint);
69 | }
70 |
71 | /// Adds a constraint for each matrix coefficient multiplication
72 | fn mul_matrix<'b, I>(&mut self, constants: &mut I, values: &mut [Witness])
73 | where
74 | I: Iterator
- ,
75 | {
76 | let mut result = [Composer::ZERO; WIDTH];
77 | self.count += 1;
78 |
79 | // Implementation optimized for WIDTH = 5
80 | //
81 | // c is the next round constant.
82 | // For the partial round, it is added only for the last element
83 | //
84 | // The resulting array `r` will be defined as
85 | // r[x] = sum j 0..WIDTH ( MDS[x][j] * values[j] ) + c
86 | //
87 | // q_l = MDS[x][0]
88 | // q_r = MDS[x][1]
89 | // q_4 = MDS[x][2]
90 | // w_l = values[0]
91 | // w_r = values[1]
92 | // w_4 = values[2]
93 | // r[x] = q_l · w_l + q_r · w_r + q_4 · w_4;
94 | //
95 | // q_l = MDS[x][3]
96 | // q_r = MDS[x][4]
97 | // q_4 = 1
98 | // w_l = values[3]
99 | // w_r = values[4]
100 | // w_4 = r[x]
101 | // r[x] = q_l · w_l + q_r · w_r + q_4 · w_4 + c;
102 | for j in 0..WIDTH {
103 | let c = if self.count < Self::rounds() {
104 | Self::next_c(constants)
105 | } else {
106 | BlsScalar::zero()
107 | };
108 |
109 | let constraint = Constraint::new()
110 | .left(MDS_MATRIX[j][0])
111 | .a(values[0])
112 | .right(MDS_MATRIX[j][1])
113 | .b(values[1])
114 | .fourth(MDS_MATRIX[j][2])
115 | .d(values[2]);
116 |
117 | result[j] = self.cs.gate_add(constraint);
118 |
119 | let constraint = Constraint::new()
120 | .left(MDS_MATRIX[j][3])
121 | .a(values[3])
122 | .right(MDS_MATRIX[j][4])
123 | .b(values[4])
124 | .fourth(1)
125 | .d(result[j])
126 | .constant(c);
127 |
128 | result[j] = self.cs.gate_add(constraint);
129 | }
130 |
131 | values.copy_from_slice(&result);
132 | }
133 | }
134 |
135 | #[cfg(test)]
136 | mod tests {
137 | use crate::{GadgetStrategy, ScalarStrategy, Strategy, WIDTH};
138 | use core::result::Result;
139 | use dusk_plonk::prelude::*;
140 | use ff::Field;
141 | use rand::rngs::StdRng;
142 | use rand::SeedableRng;
143 |
144 | #[derive(Default)]
145 | struct TestCircuit {
146 | i: [BlsScalar; WIDTH],
147 | o: [BlsScalar; WIDTH],
148 | }
149 |
150 | impl Circuit for TestCircuit {
151 | fn circuit(&self, composer: &mut Composer) -> Result<(), Error> {
152 | let zero = Composer::ZERO;
153 |
154 | let mut perm: [Witness; WIDTH] = [zero; WIDTH];
155 |
156 | let mut i_var: [Witness; WIDTH] = [zero; WIDTH];
157 | self.i.iter().zip(i_var.iter_mut()).for_each(|(i, v)| {
158 | *v = composer.append_witness(*i);
159 | });
160 |
161 | let mut o_var: [Witness; WIDTH] = [zero; WIDTH];
162 | self.o.iter().zip(o_var.iter_mut()).for_each(|(o, v)| {
163 | *v = composer.append_witness(*o);
164 | });
165 |
166 | // Apply Hades gadget strategy.
167 | GadgetStrategy::gadget(composer, &mut i_var);
168 |
169 | // Copy the result of the permutation into the perm.
170 | perm.copy_from_slice(&i_var);
171 |
172 | // Check that the Gadget perm results = BlsScalar perm results
173 | i_var.iter().zip(o_var.iter()).for_each(|(p, o)| {
174 | composer.assert_equal(*p, *o);
175 | });
176 |
177 | Ok(())
178 | }
179 | }
180 |
181 | /// Generate a random input and perform a permutation
182 | fn hades() -> ([BlsScalar; WIDTH], [BlsScalar; WIDTH]) {
183 | let mut input = [BlsScalar::zero(); WIDTH];
184 |
185 | input
186 | .iter_mut()
187 | .for_each(|s| *s = BlsScalar::random(&mut rand::thread_rng()));
188 |
189 | let mut output = [BlsScalar::zero(); WIDTH];
190 |
191 | output.copy_from_slice(&input);
192 | ScalarStrategy::new().perm(&mut output);
193 |
194 | (input, output)
195 | }
196 |
197 | /// Setup the test circuit prover and verifier
198 | fn setup() -> Result<(Prover, Verifier), Error> {
199 | const CAPACITY: usize = 1 << 10;
200 |
201 | let pp = PublicParameters::setup(CAPACITY, &mut rand::thread_rng())?;
202 | let label = b"hades_gadget_tester";
203 |
204 | Compiler::compile::(&pp, label)
205 | }
206 |
207 | #[test]
208 | fn preimage() -> Result<(), Error> {
209 | let (prover, verifier) = setup()?;
210 |
211 | let (i, o) = hades();
212 |
213 | let circuit = TestCircuit { i, o };
214 | let mut rng = StdRng::seed_from_u64(0xbeef);
215 |
216 | // Proving
217 | let (proof, public_inputs) = prover.prove(&mut rng, &circuit)?;
218 |
219 | // Verifying
220 | verifier.verify(&proof, &public_inputs)?;
221 |
222 | Ok(())
223 | }
224 |
225 | #[test]
226 | fn preimage_constant() -> Result<(), Error> {
227 | let (prover, verifier) = setup()?;
228 |
229 | // Prepare input & output
230 | let i = [BlsScalar::from(5000u64); WIDTH];
231 | let mut o = [BlsScalar::from(5000u64); WIDTH];
232 | ScalarStrategy::new().perm(&mut o);
233 |
234 | let circuit = TestCircuit { i, o };
235 | let mut rng = StdRng::seed_from_u64(0xbeef);
236 |
237 | // Proving
238 | let (proof, public_inputs) = prover.prove(&mut rng, &circuit)?;
239 |
240 | // Verifying
241 | verifier.verify(&proof, &public_inputs)?;
242 |
243 | Ok(())
244 | }
245 |
246 | #[test]
247 | fn preimage_fails() -> Result<(), Error> {
248 | let (prover, _) = setup()?;
249 |
250 | // Generate [31, 0, 0, 0, 0] as real input to the perm but build the
251 | // proof with [31, 31, 31, 31, 31]. This should fail on verification
252 | // since the Proof contains incorrect statements.
253 | let x_scalar = BlsScalar::from(31u64);
254 |
255 | let mut i = [BlsScalar::zero(); WIDTH];
256 | i[1] = x_scalar;
257 |
258 | let mut o = [BlsScalar::from(31u64); WIDTH];
259 | ScalarStrategy::new().perm(&mut o);
260 |
261 | let circuit = TestCircuit { i, o };
262 | let mut rng = StdRng::seed_from_u64(0xbeef);
263 |
264 | // Proving should fail
265 | assert!(
266 | prover.prove(&mut rng, &circuit).is_err(),
267 | "proving should fail since the circuit is invalid"
268 | );
269 |
270 | Ok(())
271 | }
272 | }
273 |
--------------------------------------------------------------------------------
/src/strategies/scalar.rs:
--------------------------------------------------------------------------------
1 | // This Source Code Form is subject to the terms of the Mozilla Public
2 | // License, v. 2.0. If a copy of the MPL was not distributed with this
3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 | //
5 | // Copyright (c) DUSK NETWORK. All rights reserved.
6 |
7 | use super::Strategy;
8 | use crate::{mds_matrix::MDS_MATRIX, WIDTH};
9 | use dusk_bls12_381::BlsScalar;
10 |
11 | /// Implements a Hades252 strategy for `BlsScalar` as input values.
12 | #[derive(Default)]
13 | pub struct ScalarStrategy {}
14 |
15 | impl ScalarStrategy {
16 | /// Constructs a new `ScalarStrategy`.
17 | pub fn new() -> Self {
18 | Default::default()
19 | }
20 | }
21 |
22 | impl Strategy for ScalarStrategy {
23 | fn add_round_key<'b, I>(&mut self, constants: &mut I, words: &mut [BlsScalar])
24 | where
25 | I: Iterator
- ,
26 | {
27 | words.iter_mut().for_each(|w| {
28 | *w += Self::next_c(constants);
29 | });
30 | }
31 |
32 | fn quintic_s_box(&mut self, value: &mut BlsScalar) {
33 | *value = value.square().square() * *value;
34 | }
35 |
36 | fn mul_matrix<'b, I>(&mut self, _constants: &mut I, values: &mut [BlsScalar])
37 | where
38 | I: Iterator
- ,
39 | {
40 | let mut result = [BlsScalar::zero(); WIDTH];
41 |
42 | for (j, value) in values.iter().enumerate().take(WIDTH) {
43 | for k in 0..WIDTH {
44 | result[k] += MDS_MATRIX[k][j] * value;
45 | }
46 | }
47 |
48 | values.copy_from_slice(&result);
49 | }
50 | }
51 |
52 | #[cfg(test)]
53 | mod tests {
54 | use super::*;
55 | use crate::{ScalarStrategy, Strategy, WIDTH};
56 |
57 | fn perm(values: &mut [BlsScalar]) {
58 | let mut strategy = ScalarStrategy::new();
59 | strategy.perm(values);
60 | }
61 |
62 | #[test]
63 | fn hades_det() {
64 | let mut x = [BlsScalar::from(17u64); WIDTH];
65 | let mut y = [BlsScalar::from(17u64); WIDTH];
66 | let mut z = [BlsScalar::from(19u64); WIDTH];
67 |
68 | perm(&mut x);
69 | perm(&mut y);
70 | perm(&mut z);
71 |
72 | assert_eq!(x, y);
73 | assert_ne!(x, z);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------