├── .github
└── workflows
│ └── general.yaml
├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
├── benches
├── Figures
│ ├── proofSizes.pdf
│ └── proverVerifierTimes.pdf
├── elgamal-plot.txt
├── elgamal.rs
├── kzg_elgamal.rs
├── kzg_paillier.rs
├── ourPlots.ipynb
├── paillier-plot.txt
├── plots.py
└── range_proof.rs
├── contracts
├── BN254.sol
├── Constants.sol
├── FDE.sol
├── FDEPaillier.sol
├── LibUint1024.sol
└── Types.sol
└── src
├── adaptor_sig.rs
├── commit
├── kzg.rs
└── mod.rs
├── dleq.rs
├── encrypt
├── elgamal
│ ├── mod.rs
│ ├── split_scalar.rs
│ └── utils.rs
└── mod.rs
├── hash.rs
├── lib.rs
├── range_proof
├── mod.rs
├── poly.rs
└── utils.rs
├── tests
└── mod.rs
└── veck
├── kzg
├── elgamal
│ ├── encryption.rs
│ └── mod.rs
├── mod.rs
└── paillier
│ ├── encrypt.rs
│ ├── mod.rs
│ ├── random.rs
│ ├── server.rs
│ └── utils.rs
└── mod.rs
/.github/workflows/general.yaml:
--------------------------------------------------------------------------------
1 | name: general code check
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 |
8 | jobs:
9 | test:
10 | name: test
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v4
14 | - uses: dtolnay/rust-toolchain@stable
15 | - name: Run tests
16 | run: cargo test --release --features parallel
17 | fmt:
18 | name: fmt
19 | runs-on: ubuntu-latest
20 | env:
21 | RUSTFLAGS: -Dwarnings # fails on warnings as well
22 | steps:
23 | - uses: actions/checkout@v4
24 | - uses: dtolnay/rust-toolchain@stable
25 | with:
26 | components: rustfmt
27 | - name: enforce formatting
28 | run: cargo fmt --check
29 |
30 | clippy:
31 | name: clippy
32 | runs-on: ubuntu-latest
33 | env:
34 | RUSTFLAGS: -Dwarnings # fails on warnings as well
35 | steps:
36 | - uses: actions/checkout@v4
37 | - uses: dtolnay/rust-toolchain@stable
38 | with:
39 | components: clippy
40 | - name: linting
41 | run: cargo clippy --tests --examples --all-features
42 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "fde"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | [profile.dev]
7 | opt-level = 3
8 |
9 | [features]
10 | default = ["std", "parallel"]
11 | std = [
12 | "ark-crypto-primitives/std",
13 | "ark-ec/std",
14 | "ark-ff/std",
15 | "ark-poly/std",
16 | "ark-poly-commit/std",
17 | "ark-serialize/std",
18 | "ark-std/std",
19 | ]
20 | parallel = [
21 | "ark-crypto-primitives/parallel",
22 | "ark-ec/parallel",
23 | "ark-ff/parallel",
24 | "ark-poly/parallel",
25 | "ark-poly-commit/parallel",
26 | "ark-std/parallel",
27 | "rayon"
28 | ]
29 |
30 | [dependencies]
31 | ark-crypto-primitives = { version = "0.4", default-features = false, features = ["signature"] }
32 | ark-ec = { version = "0.4", default-features = false }
33 | ark-ff = { version = "0.4", default-features = false }
34 | ark-poly = { version = "0.4", default-features = false }
35 | ark-poly-commit = { version = "0.4", default-features = false }
36 | ark-serialize = { version = "0.4", default-features = false }
37 | ark-std = { version = "0.4", default-features = false }
38 | num-bigint = { version = "0.4", features = ["rand"] }
39 | num-integer = "0.1"
40 | num-prime = "0.4"
41 | digest = { version = "0.10", default-features = false }
42 | rayon = { version = "1.8", optional = true }
43 | thiserror = "1"
44 |
45 | [dev-dependencies]
46 | ark-bls12-381 = "0.4"
47 | ark-secp256k1 = "0.4"
48 | criterion = "0.5"
49 | sha3 = "0.10"
50 |
51 | [[bench]]
52 | name = "kzg-paillier-veck"
53 | path = "benches/kzg_paillier.rs"
54 | harness = false
55 |
56 | [[bench]]
57 | name = "kzg-elgamal-veck"
58 | path = "benches/kzg_elgamal.rs"
59 | harness = false
60 |
61 | [[bench]]
62 | name = "split-elgamal-encryption"
63 | path = "benches/elgamal.rs"
64 | harness = false
65 |
66 | [[bench]]
67 | name = "range-proof"
68 | path = "benches/range_proof.rs"
69 | harness = false
70 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Atomic BlockChain Data Exchange with Fairness
2 |
3 | FDE protocols allow a server and a client to exchange KZG-committed data securely and fairly.
4 | The server holds all the data, while the client only knows a KZG (polynomial commitment) to the data. For more details on the protocol, refer to our research paper.
5 | This protocol is useful for Ethereum in a post [EIP-4844](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md) world. In particular, blocks will contain blob data (KZG commitments) that commit to rollup data. The block header only contains KZG commitments, while full nodes store the entire data. It is reasonable to assume that an efficient market will emerge for downloading rollup data from full nodes.
6 | This work creates protocols that allow full nodes to exchange the committed data for money in an atomic and fair manner.
7 |
8 | Title: Atomic BlockChain Data Exchange with Fairness
9 |
10 | Authors: Ertem Nusret Tas, Valeria Nikolaenko, István A. Seres, Márk Melczer, Yinuo Zhang, Mahimna Kelkar, Joseph Bonneau.
11 |
12 | Currently available at the following link:
13 | * IACR [eprint link](https://eprint.iacr.org/2024/418.pdf).
14 |
15 | ## Quickstart
16 |
17 | The protocols in the paper are implemented in the [Rust programming language](https://www.rust-lang.org/), relying heavily on cryptographic libraries from [arkworks](https://github.com/arkworks-rs). The source code is found in [src](https://github.com/PopcornPaws/fde/tree/main/src). Respective smart contracts were implemented in [Solidity](https://soliditylang.org/) and they are found in [contracts](https://github.com/PopcornPaws/fde/tree/main/contracts).
18 |
19 | ### Installing, building, and running tests
20 |
21 | First, you must install `rustup` by following the steps outlined [here](https://www.rust-lang.org/learn/get-started).
22 |
23 | ```sh
24 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
25 | ```
26 |
27 | Clone the repository and jump into the cloned directory
28 | ```sh
29 | git clone https://github.com/PopcornPaws/fde.git
30 | cd fde
31 | ```
32 | - build: `cargo build --release` (the `release` flag is optional)
33 | - test: `cargo test --release` (the `release` flag is optional)
34 | - benchmark: `cargo bench`
35 |
36 | ### Contracts
37 | Requires [Foundry](https://book.getfoundry.sh/getting-started/installation).
38 |
39 | Install: `forge install`
40 |
41 | Build: `forge build`
42 |
43 | Differential tests: `forge test --match-test testRef --ffi`
44 |
45 | Other tests: `forge test --no-match-test testRef`
46 |
47 |
48 | ## Implemented BDE protocols
49 |
50 | Below is a short introduction to the implementation of the protocols in the paper.
51 | **IMPORTANT** This is an unaudited, proof-of-concept implementation used mainly for benchmarking and exploring practical feasibility and limitations. Do not use this code in a production environment.
52 |
53 | ### ElGamal encryption-based
54 |
55 | This [version](https://github.com/PopcornPaws/fde/tree/main/src/veck/kzg/elgamal) of the protocol uses exponential ElGamal encryption for generating the ciphertexts. Plaintext data is represented by scalar field elements of the BLS12-381 curve. Since exponential ElGamal relies on a brute-force approach to decrypt the ciphertexts, we needed to ensure that the encrypted scalar field elements are split up into multiple `u32` shards that are easier to decrypt than a single 256-bit scalar. Thus we needed an additional [encryption proof](https://github.com/PopcornPaws/fde/blob/main/src/veck/kzg/elgamal/encryption.rs) whose goal is to prove that the plaintext shards are indeed in the range of `0..u32::MAX` and we also needed to ensure that the plaintext shards can be used to reconstruct the original 256 bit scalar. For this, we used simple [`DLEQ` proofs](https://github.com/PopcornPaws/fde/blob/main/src/dleq.rs). For the [range proofs](https://github.com/PopcornPaws/fde/tree/main/src/range_proof), we used a slightly modified version of [this](https://github.com/roynalnaruto/range_proof) implementation, that is based on the work of [Boneh-Fisch-Gabizon-Williamson](https://hackmd.io/@dabo/B1U4kx8XI) with further details discussed in [this blogpost](https://decentralizedthoughts.github.io/2020-03-03-range-proofs-from-polynomial-commitments-reexplained/).
56 |
57 | ### Paillier encryption-based
58 |
59 | This [version](https://github.com/PopcornPaws/fde/blob/main/src/veck/kzg/paillier/mod.rs) of the protocol uses the Paillier encryption scheme to encrypt the plaintext data. It utilizes the [num-bigint](https://crates.io/crates/num-bigint) crate for proof generation due to working in an RSA group instead of an elliptic curve. Computations are, therefore, slightly less performant than working with [arkworks](https://github.com/arkworks-rs) libraries, but we gain a lot in the decryption phase where there is no need to split up the original plaintext, generate range proofs, and use a brute-force approach for decryption.
60 |
61 | ## On-chain components of our protocols
62 | Our protocols apply smart contracts to achieve atomicity and fairness. Have a look at our [implemented FDE smart contracts](https://github.com/PopcornPaws/fde/blob/main/contracts/FDE.sol).
63 | ## Benchmarks
64 | We provide benchmarks in [this folder](https://github.com/PopcornPaws/fde/tree/main/benches).
65 | ## Contributing
66 | We welcome any contributions. Feel free to [open new issues](https://github.com/PopcornPaws/fde/issues/new) or [resolve existing ones](https://github.com/PopcornPaws/fde/issues).
67 |
68 | ## Disclaimer
69 | *The code is being provided as is. No guarantee, representation or warranty is being made, express or implied, as to the safety or correctness of the code. The code has not been audited and as such there can be no assurance it will work as intended, and users may experience delays, failures, errors, omissions or loss of transmitted information. THE CODE CONTAINED HEREIN IS FURNISHED AS IS, WHERE IS, WITH ALL FAULTS AND WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, NON- INFRINGEMENT OR FITNESS FOR ANY PARTICULAR PURPOSE. Further, use of any of the smart contracts may be restricted or prohibited under applicable law, including securities laws, and it is therefore strongly advised for you to contact a reputable attorney in any jurisdiction where these smart contracts may be accessible for any questions or concerns with respect thereto. Further, no information provided in this repo should be construed as investment advice or legal advice for any particular facts or circumstances, and is not meant to replace competent counsel. The authors are not liable for any use of the foregoing, and users should proceed with caution and use at their own risk.*
70 |
--------------------------------------------------------------------------------
/benches/Figures/proofSizes.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PopcornPaws/fde/0ae60c7ca544e78ba03ca7a5eccb55532dfb9674/benches/Figures/proofSizes.pdf
--------------------------------------------------------------------------------
/benches/Figures/proverVerifierTimes.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PopcornPaws/fde/0ae60c7ca544e78ba03ca7a5eccb55532dfb9674/benches/Figures/proverVerifierTimes.pdf
--------------------------------------------------------------------------------
/benches/elgamal-plot.txt:
--------------------------------------------------------------------------------
1 | KZG-ELGAMAL - all units are [ms]
2 | proof-gen 154.86,87.448,50.783,34.127,25.760,21.619,19.509,19.157,20.204,22.213,24.984,30.279,38.948
3 | proof-vfy 6.03,7.64,7.69,7.97,8.19,8.75,9.42,10.68,12.25,15.28,19.86,28.90,42.23
4 |
5 | range-proof-vfy 11.77,21.79,34.44,68.23,127.09,253.12,500.32,1004.9,1991.1,4020.1,8039.2,16084.0,32133.0
6 | split-scalar-encryption-vfy 1.92,3.64,5.66,10.92,40.83,80.35,160.01,319.60,639.45,1277.1,2550.7
7 |
8 | total-proof-vfy 27.796,31.336,43.210,77.583,136.80,264.56,511.48,1014.4,2119.5,4383.4,8630.0,17055.0,34149.0
9 |
10 | range proofs + encryptions are pre-computed in 89 seconds
11 |
--------------------------------------------------------------------------------
/benches/elgamal.rs:
--------------------------------------------------------------------------------
1 | use ark_bls12_381::{Bls12_381 as BlsCurve, G1Affine};
2 | use ark_ec::pairing::Pairing;
3 | use ark_ec::{AffineRepr, CurveGroup};
4 | use ark_ff::PrimeField;
5 | use ark_std::{test_rng, UniformRand};
6 | use criterion::{criterion_group, criterion_main, Criterion};
7 | use fde::encrypt::EncryptionEngine;
8 | #[cfg(feature = "parallel")]
9 | use rayon::prelude::*;
10 |
11 | const N: usize = Scalar::MODULUS_BIT_SIZE as usize / fde::encrypt::elgamal::MAX_BITS + 1;
12 |
13 | type Scalar = ::ScalarField;
14 | type SplitScalar = fde::encrypt::elgamal::SplitScalar<{ N }, Scalar>;
15 | type Elgamal = fde::encrypt::elgamal::ExponentialElgamal<::G1>;
16 |
17 | // NOTE in case of 4096 scalars, we have 4096 * N split scalars
18 | fn bench_elgamal(c: &mut Criterion) {
19 | let mut group = c.benchmark_group("split-elgamal");
20 | group.sample_size(10);
21 |
22 | let rng = &mut test_rng();
23 | let encryption_sk = Scalar::rand(rng);
24 | let encryption_pk = (G1Affine::generator() * encryption_sk).into_affine();
25 |
26 | let scalars: Vec = (0..4096 * N).map(|_| Scalar::rand(rng)).collect();
27 |
28 | let mut ciphers = Vec::with_capacity(scalars.len());
29 | let mut split_ciphers = Vec::with_capacity(scalars.len());
30 |
31 | println!("GENERATING ENCRYPTIONS...");
32 | let now = std::time::Instant::now();
33 | scalars.iter().enumerate().for_each(|(i, scalar)| {
34 | if i % 256 == 0 {
35 | println!("{}/{}", i, 4096 * N);
36 | }
37 | let split_scalar = SplitScalar::from(*scalar);
38 | let (split_cipher, randomness) = split_scalar.encrypt::(&encryption_pk, rng);
39 | let long_cipher = ::encrypt_with_randomness(
40 | &scalar,
41 | &encryption_pk,
42 | &randomness,
43 | );
44 |
45 | ciphers.push(long_cipher);
46 | split_ciphers.push(split_cipher);
47 | });
48 | let elapsed = std::time::Instant::now().duration_since(now).as_secs();
49 | println!("ELAPSED: {} [s]", elapsed);
50 |
51 | for i in 0..=12 {
52 | let subset_size = 1 << i;
53 | let verify_split_encryption_name = format!("verify-split-encryption-{}", subset_size);
54 | group.bench_function(verify_split_encryption_name, |b| {
55 | b.iter(|| {
56 | #[cfg(not(feature = "parallel"))]
57 | ciphers
58 | .iter()
59 | .take(subset_size * N)
60 | .zip(&split_ciphers)
61 | .for_each(|(cipher, split_cipher)| {
62 | assert!(cipher.check_encrypted_sum(split_cipher));
63 | });
64 | #[cfg(feature = "parallel")]
65 | ciphers
66 | .par_iter()
67 | .take(subset_size * N)
68 | .zip(&split_ciphers)
69 | .for_each(|(long_cipher, split_cipher)| {
70 | assert!(long_cipher.check_encrypted_sum(split_cipher));
71 | });
72 | })
73 | });
74 | }
75 |
76 | group.finish()
77 | }
78 |
79 | criterion_group!(benches, bench_elgamal);
80 | criterion_main!(benches);
81 |
--------------------------------------------------------------------------------
/benches/kzg_elgamal.rs:
--------------------------------------------------------------------------------
1 | use ark_ec::pairing::Pairing;
2 | use ark_ec::{CurveGroup, Group};
3 | use ark_ff::PrimeField;
4 | use ark_poly::univariate::DensePolynomial;
5 | use ark_poly::{EvaluationDomain, Evaluations, GeneralEvaluationDomain};
6 | use ark_std::{test_rng, UniformRand};
7 | use criterion::{criterion_group, criterion_main, Criterion};
8 | use fde::commit::kzg::Powers;
9 |
10 | const DATA_LOG_SIZE: usize = 12; // 4096 = 2^12
11 | const N: usize = Scalar::MODULUS_BIT_SIZE as usize / fde::encrypt::elgamal::MAX_BITS + 1;
12 |
13 | type TestCurve = ark_bls12_381::Bls12_381;
14 | type TestHash = sha3::Keccak256;
15 | type Scalar = ::ScalarField;
16 | type UniPoly = DensePolynomial;
17 | type Proof = fde::veck::kzg::elgamal::Proof<{ N }, TestCurve, TestHash>;
18 | type EncryptionProof = fde::veck::kzg::elgamal::EncryptionProof<{ N }, TestCurve, TestHash>;
19 |
20 | fn bench_proof(c: &mut Criterion) {
21 | let mut group = c.benchmark_group("kzg-elgamal");
22 | group.sample_size(10);
23 |
24 | let data_size = 1 << DATA_LOG_SIZE;
25 | assert_eq!(data_size, 4096);
26 |
27 | let rng = &mut test_rng();
28 | let tau = Scalar::rand(rng);
29 | let powers = Powers::::unsafe_setup(tau, data_size + 1);
30 |
31 | let encryption_sk = Scalar::rand(rng);
32 | let encryption_pk = (::G1::generator() * encryption_sk).into_affine();
33 |
34 | println!("Generating encryption proofs for 4096 * 8 split field elements...");
35 | println!("This might take a few minutes and it's not included in the actual benchmarks.");
36 | let t_start = std::time::Instant::now();
37 | let data: Vec = (0..data_size).map(|_| Scalar::rand(rng)).collect();
38 | let encryption_proof = EncryptionProof::new(&data, &encryption_pk, &powers, rng);
39 | let elapsed = std::time::Instant::now().duration_since(t_start).as_secs();
40 | println!("Generated encryption proofs, elapsed time: {} [s]", elapsed);
41 |
42 | let domain = GeneralEvaluationDomain::new(data.len()).expect("valid domain");
43 | let index_map = fde::veck::index_map(domain);
44 |
45 | let evaluations = Evaluations::from_vec_and_domain(data, domain);
46 | let f_poly: UniPoly = evaluations.interpolate_by_ref();
47 | let com_f_poly = powers.commit_g1(&f_poly);
48 |
49 | for i in 0..=12 {
50 | let subset_size = 1 << i;
51 | let proof_gen_name = format!("proof-gen-{}", subset_size);
52 | let proof_vfy_name = format!("proof-vfy-{}", subset_size);
53 |
54 | let subdomain = GeneralEvaluationDomain::new(subset_size).unwrap();
55 | let subset_indices = fde::veck::subset_indices(&index_map, &subdomain);
56 | let subset_evaluations = fde::veck::subset_evals(&evaluations, &subset_indices, subdomain);
57 |
58 | let f_s_poly: UniPoly = subset_evaluations.interpolate_by_ref();
59 | let com_f_s_poly = powers.commit_g1(&f_s_poly);
60 |
61 | let sub_encryption_proof = encryption_proof.subset(&subset_indices);
62 |
63 | group.bench_function(&proof_gen_name, |b| {
64 | b.iter(|| {
65 | Proof::new(
66 | &f_poly,
67 | &f_s_poly,
68 | &encryption_sk,
69 | sub_encryption_proof.clone(),
70 | &powers,
71 | rng,
72 | )
73 | .unwrap();
74 | })
75 | });
76 |
77 | group.bench_function(&proof_vfy_name, |b| {
78 | let proof = Proof::new(
79 | &f_poly,
80 | &f_s_poly,
81 | &encryption_sk,
82 | sub_encryption_proof.clone(),
83 | &powers,
84 | rng,
85 | )
86 | .unwrap();
87 | b.iter(|| {
88 | assert!(proof
89 | .verify(com_f_poly, com_f_s_poly, encryption_pk, &powers)
90 | .is_ok())
91 | })
92 | });
93 | }
94 |
95 | group.finish();
96 | }
97 |
98 | criterion_group!(benches, bench_proof);
99 | criterion_main!(benches);
100 |
--------------------------------------------------------------------------------
/benches/kzg_paillier.rs:
--------------------------------------------------------------------------------
1 | use ark_bls12_381::Bls12_381 as BlsCurve;
2 | use ark_ec::pairing::Pairing;
3 | use ark_ff::{BigInteger, PrimeField};
4 | use ark_poly::univariate::DensePolynomial;
5 | use ark_poly::{EvaluationDomain, Evaluations, GeneralEvaluationDomain};
6 | use ark_std::{test_rng, UniformRand};
7 | use criterion::{criterion_group, criterion_main, Criterion};
8 | use fde::commit::kzg::Powers;
9 | use fde::veck::kzg::paillier::Server;
10 | use num_bigint::BigUint;
11 |
12 | type TestCurve = ark_bls12_381::Bls12_381;
13 | type TestHash = sha3::Keccak256;
14 | type Scalar = ::ScalarField;
15 | type UniPoly = DensePolynomial;
16 | type PaillierEncryptionProof = fde::veck::kzg::paillier::Proof;
17 |
18 | fn bench_proof(c: &mut Criterion) {
19 | let mut group = c.benchmark_group("kzg-paillier");
20 | group.sample_size(10);
21 |
22 | // TODO until subset openings don't work, use full open
23 | // https://github.com/PopcornPaws/fde/issues/9
24 | //let data_size = 1 << 12;
25 | //let data: Vec = (0..data_size).map(|_| Scalar::rand(rng)).collect();
26 | //let domain = GeneralEvaluationDomain::new(DATA_SIZE).unwrap();
27 | let rng = &mut test_rng();
28 | let tau = Scalar::rand(rng);
29 | let powers = Powers::::unsafe_setup_eip_4844(tau, 1 << 12); // TODO data_size
30 | let server = Server::new(rng);
31 |
32 | for i in 0..=12 {
33 | // TODO remove this once subset proofs work https://github.com/PopcornPaws/fde/issues/9
34 | let data_size = 1 << i;
35 | let subset_size = 1 << i;
36 | let proof_gen_name = format!("proof-gen-{}", subset_size);
37 | let proof_vfy_name = format!("proof-vfy-{}", subset_size);
38 | let decryption_name = format!("decryption-{}", subset_size);
39 | // random data to encrypt
40 | let data: Vec = (0..data_size).map(|_| Scalar::rand(rng)).collect();
41 | let domain = GeneralEvaluationDomain::new(data_size).unwrap();
42 | let domain_s = GeneralEvaluationDomain::new(subset_size).unwrap();
43 | let evaluations = Evaluations::from_vec_and_domain(data, domain);
44 | let index_map = fde::veck::index_map(domain);
45 | let subset_indices = fde::veck::subset_indices(&index_map, &domain_s);
46 | let evaluations_s = fde::veck::subset_evals(&evaluations, &subset_indices, domain_s);
47 |
48 | let f_poly: UniPoly = evaluations.interpolate_by_ref();
49 | let f_s_poly: UniPoly = evaluations_s.interpolate_by_ref();
50 |
51 | let evaluations_s_d = f_s_poly.evaluate_over_domain_by_ref(domain);
52 |
53 | let com_f_poly = powers.commit_scalars_g1(&evaluations.evals);
54 | let com_f_s_poly = powers.commit_scalars_g1(&evaluations_s_d.evals);
55 |
56 | let data_biguint: Vec = evaluations_s
57 | .evals
58 | .iter()
59 | .map(|d| BigUint::from_bytes_le(&d.into_bigint().to_bytes_le()))
60 | .collect();
61 |
62 | group.bench_function(&proof_gen_name, |b| {
63 | b.iter(|| {
64 | PaillierEncryptionProof::new(
65 | &data_biguint,
66 | &f_poly,
67 | &f_s_poly,
68 | &com_f_poly,
69 | &com_f_s_poly,
70 | &domain,
71 | &domain_s,
72 | &server.pubkey,
73 | &powers,
74 | rng,
75 | );
76 | })
77 | });
78 |
79 | group.bench_function(&proof_vfy_name, |b| {
80 | let proof = PaillierEncryptionProof::new(
81 | &data_biguint,
82 | &f_poly,
83 | &f_s_poly,
84 | &com_f_poly,
85 | &com_f_s_poly,
86 | &domain,
87 | &domain_s,
88 | &server.pubkey,
89 | &powers,
90 | rng,
91 | );
92 | b.iter(|| {
93 | assert!(proof
94 | .verify(
95 | &com_f_poly,
96 | &com_f_s_poly,
97 | &domain,
98 | &domain_s,
99 | &server.pubkey,
100 | &powers
101 | )
102 | .is_ok());
103 | })
104 | });
105 |
106 | group.bench_function(&decryption_name, |b| {
107 | let proof = PaillierEncryptionProof::new(
108 | &data_biguint,
109 | &f_poly,
110 | &f_s_poly,
111 | &com_f_poly,
112 | &com_f_s_poly,
113 | &domain,
114 | &domain_s,
115 | &server.pubkey,
116 | &powers,
117 | rng,
118 | );
119 | b.iter(|| {
120 | proof.decrypt(&server);
121 | })
122 | });
123 | }
124 |
125 | group.finish();
126 | }
127 |
128 | criterion_group!(benches, bench_proof);
129 | criterion_main!(benches);
130 |
--------------------------------------------------------------------------------
/benches/paillier-plot.txt:
--------------------------------------------------------------------------------
1 | KZG-PAILLIER - all units are [ms]
2 | gen 7.0327,11.586,14.667,14.188,23.555,43.434,83.285,163.02,321.44,641.81,1281.0,2549.2,5098.9
3 | vfy 6.6277,11.374,20.728,39.452,76.829,151.92,303.81,597.88,1203.2,2411.3,4861.1,9780.2,19455.0
4 | dec 4.7182,7.0237,11.507,20.714,38.926,75.921,148.84,296.96,598.35,1181.0,2373.0,4756.1,9541.7
5 |
--------------------------------------------------------------------------------
/benches/plots.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import numpy as np
3 |
4 | x_axis = [1<::ScalarField;
15 | type RangeProof = fde::range_proof::RangeProof;
16 |
17 | fn bench_proof(c: &mut Criterion) {
18 | let mut group = c.benchmark_group("range-proof");
19 |
20 | let rng = &mut test_rng();
21 | let tau = Scalar::rand(rng);
22 | let powers = Powers::::unsafe_setup(tau, 4 * LOG_2_UPPER_BOUND);
23 |
24 | let z = Scalar::from(100u32);
25 |
26 | group.bench_function("proof-gen", |b| {
27 | b.iter(|| {
28 | let _proof = RangeProof::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap();
29 | })
30 | });
31 |
32 | group.bench_function("proof-vfy", |b| {
33 | let proof = RangeProof::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap();
34 | b.iter(|| assert!(proof.verify(LOG_2_UPPER_BOUND, &powers).is_ok()))
35 | });
36 |
37 | group.finish();
38 | }
39 |
40 | // NOTE in case of 4096 scalars, we need 4096 * N range proofs for each smaller split scalar
41 | fn bench_multiple_proofs(c: &mut Criterion) {
42 | let mut group = c.benchmark_group("range-proof");
43 | group.sample_size(10);
44 |
45 | let rng = &mut test_rng();
46 | let tau = Scalar::rand(rng);
47 | let powers = Powers::::unsafe_setup(tau, 4 * LOG_2_UPPER_BOUND);
48 |
49 | let scalars: Vec = (0..4096 * N)
50 | .map(|_| Scalar::from(rng.next_u32()))
51 | .collect();
52 | println!("GENERATING RANGE PROOFS...");
53 | let now = std::time::Instant::now();
54 | let proofs = scalars
55 | .into_iter()
56 | .enumerate()
57 | .inspect(|(i, _)| {
58 | if i % 256 == 0 {
59 | println!("{}/{}", i, 4096 * N);
60 | }
61 | })
62 | .map(|(_, z)| RangeProof::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap())
63 | .collect::>();
64 |
65 | let elapsed = std::time::Instant::now().duration_since(now).as_secs();
66 | println!("ELAPSED: {} [s]", elapsed);
67 |
68 | for i in 0..=12 {
69 | let subset_size = 1 << i;
70 | let range_proof_vfy_name = format!("range-proof-vfy-{}", subset_size);
71 | group.bench_function(range_proof_vfy_name, |b| {
72 | b.iter(|| {
73 | #[cfg(not(feature = "parallel"))]
74 | unimplemented!();
75 | #[cfg(feature = "parallel")]
76 | proofs.par_iter().take(subset_size * N).for_each(|proof| {
77 | assert!(proof.verify(LOG_2_UPPER_BOUND, &powers).is_ok());
78 | });
79 | })
80 | });
81 | }
82 | }
83 |
84 | criterion_group!(benches, bench_multiple_proofs, bench_proof);
85 | criterion_main!(benches);
86 |
--------------------------------------------------------------------------------
/contracts/BN254.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import { Types } from "./Types.sol";
5 | import { Constants } from "./Constants.sol";
6 |
7 | contract BN254 {
8 | /// @return the generator of G1
9 | // solhint-disable-next-line func-name-mixedcase
10 | function P1() internal pure returns (Types.G1Point memory) {
11 | return Types.G1Point(1, 2);
12 | }
13 |
14 | function P1Neg() internal pure returns (Types.G1Point memory) {
15 | return Types.G1Point(1, 0x30644E72E131A029B85045B68181585D97816A916871CA8D3C208C16D87CFD45);
16 | }
17 |
18 | /// @return the generator of G2
19 | // solhint-disable-next-line func-name-mixedcase
20 | function P2() internal pure returns (Types.G2Point memory) {
21 | return Types.G2Point({
22 | x0: 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
23 | x1: 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed,
24 | y0: 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
25 | y1: 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
26 | });
27 | }
28 |
29 | /*
30 | * @return The negation of p, i.e. p.plus(p.negate()) should be zero.
31 | */
32 | function negate(
33 | Types.G1Point memory _p
34 | ) internal pure returns (Types.G1Point memory) {
35 | // The prime q in the base field F_q for G1
36 | if (_p.x == 0 && _p.y == 0) {
37 | return Types.G1Point(0, 0);
38 | } else {
39 | uint256 q = Constants.PRIME_Q;
40 | return Types.G1Point(_p.x, q - (_p.y % q));
41 | }
42 | }
43 |
44 | /*
45 | * @return The multiplication of a G1 point with a scalar value.
46 | */
47 | function mul(
48 | Types.G1Point memory _p,
49 | uint256 v
50 | ) internal view returns (Types.G1Point memory) {
51 | uint256[3] memory input;
52 | input[0] = _p.x;
53 | input[1] = _p.y;
54 | input[2] = v;
55 |
56 | Types.G1Point memory result;
57 | bool success;
58 |
59 | // solium-disable-next-line security/no-inline-assembly
60 | assembly {
61 | success := staticcall(sub(gas(), 2000), 7, input, 0x60, result, 0x40)
62 | switch success case 0 { revert(0, 0) }
63 | }
64 | require (success, "BN254: mul failed");
65 |
66 | return result;
67 | }
68 |
69 | /*
70 | * @return Returns the sum of two G1 points.
71 | */
72 | function plus(
73 | Types.G1Point memory p1,
74 | Types.G1Point memory p2
75 | ) internal view returns (Types.G1Point memory) {
76 |
77 | Types.G1Point memory result;
78 | bool success;
79 |
80 | uint256[4] memory input;
81 | input[0] = p1.x;
82 | input[1] = p1.y;
83 | input[2] = p2.x;
84 | input[3] = p2.y;
85 |
86 | // solium-disable-next-line security/no-inline-assembly
87 | assembly {
88 | success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40)
89 | switch success case 0 { revert(0, 0) }
90 | }
91 |
92 | require(success, "BN254: plus failed");
93 |
94 | return result;
95 | }
96 |
97 | // Return true if the following pairing product equals 1:
98 | // e(-a1, a2) * e(b1, b2) * e(c1, c2)
99 | // It is the caller's responsibility to ensure that the points are valid.
100 | function pairingCheck(
101 | Types.G1Point memory a1,
102 | Types.G2Point memory a2,
103 | Types.G1Point memory b1,
104 | Types.G2Point memory b2,
105 | Types.G1Point memory c1,
106 | Types.G2Point memory c2
107 | ) internal view returns (bool) {
108 | uint256 out;
109 | bool success;
110 | assembly {
111 | let mPtr := mload(0x40)
112 | // a1
113 | mstore(mPtr, mload(a1))
114 | mstore(add(mPtr, 0x20), mload(add(a1, 0x20)))
115 | // a2
116 | mstore(add(mPtr, 0x40), mload(a2))
117 | mstore(add(mPtr, 0x60), mload(add(a2, 0x20)))
118 | mstore(add(mPtr, 0x80), mload(add(a2, 0x40)))
119 | mstore(add(mPtr, 0xa0), mload(add(a2, 0x60)))
120 | // b1
121 | mstore(add(mPtr, 0xc0), mload(b1))
122 | mstore(add(mPtr, 0xe0), mload(add(b1, 0x20)))
123 | // b2
124 | mstore(add(mPtr, 0x100), mload(b2))
125 | mstore(add(mPtr, 0x120), mload(add(b2, 0x20)))
126 | mstore(add(mPtr, 0x140), mload(add(b2, 0x40)))
127 | mstore(add(mPtr, 0x160), mload(add(b2, 0x60)))
128 | // c1
129 | mstore(add(mPtr, 0x180), mload(c1))
130 | mstore(add(mPtr, 0x1a0), mload(add(c1, 0x20)))
131 | // c2
132 | mstore(add(mPtr, 0x1c0), mload(c2))
133 | mstore(add(mPtr, 0x1e0), mload(add(c2, 0x20)))
134 | mstore(add(mPtr, 0x200), mload(add(c2, 0x40)))
135 | mstore(add(mPtr, 0x220), mload(add(c2, 0x60)))
136 |
137 | success := staticcall(gas(), 8, mPtr, 0x240, 0x00, 0x20)
138 | out := mload(0x00)
139 | }
140 | require(success, "BN254: pairing check failed!");
141 | return out == 1;
142 | }
143 | }
--------------------------------------------------------------------------------
/contracts/Constants.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | library Constants {
5 | // The base field
6 | uint256 constant PRIME_Q =
7 | 21888242871839275222246405745257275088696311157297823662689037894645226208583;
8 |
9 | // The scalar field
10 | uint256 constant PRIME_R =
11 | 21888242871839275222246405745257275088548364400416034343698204186575808495617;
12 |
13 | // Compute this value with Fr::from(128).inverse().unwrap()
14 | uint256 constant DOMAIN_SIZE_INV = 0x300385D5FB6F3CE964DFA52B147E55AC6DE38077E8C5FDB0215A31A8C8200001;
15 | uint256 constant LOG2_DOMAIN_SIZE = 7;
16 |
17 | // The 1st root of unity (counting from 0) of the subgroup domain.
18 | uint256 constant OMEGA = 0x16E73DFDAD310991DF5CE19CE85943E01DCB5564B6F24C799D0E470CBA9D1811;
19 |
20 | // The nth root of unity (counting from 0) of the subgroup domain.
21 | uint256 constant OMEGA_N = 0x1332CB377D53B9C681AFA4DC09F66BC37E3F2F33DEB33D9B40BD245C971B2447;
22 |
23 | // These values should be replaced with new ones from a trusted setup.
24 | // During development, remember to update these values if you use
25 | // unsafe_setup() or change the table size!
26 |
27 | // srs_g1[table_size] x and y and srs_g2[1] x0, x1, y0, and y1
28 | // from the output of https://github.com/geometryresearch/export-ptau-points
29 | // Using the Hermez Network phase 1 SRS (the 54th contribution of Perpetual
30 | // Powers of Tau plus a random beacon)
31 |
32 | // For a table size of 2 ^ 10:
33 | uint256 constant SRS_G1_T_X = 0x17A40BF6B2A82570FED3BEDB71E3DDF36680B431FFB3641FEC94F5478D34DCCC;
34 | uint256 constant SRS_G1_T_Y = 0x050852202323C504AAB1AE596553781B3DC87CC6793D731D054C7D751E82AF0A;
35 |
36 | // For a table size of 2 ^ 11:
37 | //uint256 constant SRS_G1_T_X = 0x195B22E5A84C5D5A70E8FAEA64DB9BFE8EB57577CFEB3A7798F5470C60B99BED;
38 | //uint256 constant SRS_G1_T_Y = 0x15D250AF555DC3DBF386C1BBDD00D9AB2B6908120041BC75F496A6FBE051A494;
39 |
40 | // For a table size of 2 ** 12:
41 | //uint256 constant SRS_G1_T_X = 0x160220880FDFD72FA9C1D4B6477B5AC9BF0310BE9C5C491F3F52EFD8573A2A14;
42 | //uint256 constant SRS_G1_T_Y = 0x094E210CAF49A96E4433927B1D17309B7724958FACADE891C041CDC196E4BCB8;
43 |
44 | // For a table size of 2 ** 14:
45 | //uint256 constant SRS_G1_T_X = 0x1820CAC999202BEBA571F32647CA77E38AA8AA2C6286857D68CAAA0C8F6EA688;
46 | //uint256 constant SRS_G1_T_Y = 0x1F93BBD6833793937E7971F0D99FDC98521C1869870763F17F0730850C476F69;
47 |
48 | // For a table size of 2 ** 16:
49 | //uint256 constant SRS_G1_T_X = 0x0E4753DD9EC507F7B9A3DB6069A6686872963B01D260378F4619E3166CA1481A;
50 | //uint256 constant SRS_G1_T_Y = 0x08DEAB995B28148852575D6BDB33AE1B5719861E09EC2FA4B6D295A74110BFCF;
51 |
52 | // For a table size of 2 ^ 20:
53 | //uint256 constant SRS_G1_T_X = 0x28ECE6AC832172CE0174B269049E9BF74F739090D042E277AFADB9B047937885;
54 | //uint256 constant SRS_G1_T_Y = 0x2C408B09EA45E3DC700AD3830D57080CA519AF5EDCABFCEB47EB64E08BB75D79;
55 |
56 | uint256 constant SRS_G2_1_X_0 = 0x26186A2D65EE4D2F9C9A5B91F86597D35F192CD120CAF7E935D8443D1938E23D;
57 | uint256 constant SRS_G2_1_X_1 = 0x30441FD1B5D3370482C42152A8899027716989A6996C2535BC9F7FEE8AAEF79E;
58 | uint256 constant SRS_G2_1_Y_0 = 0x1970EA81DD6992ADFBC571EFFB03503ADBBB6A857F578403C6C40E22D65B3C02;
59 | uint256 constant SRS_G2_1_Y_1 = 0x054793348F12C0CF5622C340573CB277586319DE359AB9389778F689786B1E48;
60 | }
--------------------------------------------------------------------------------
/contracts/FDE.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import { BN254 } from "./BN254.sol";
5 | import { Types } from "./Types.sol";
6 | import { Constants } from "./Constants.sol";
7 |
8 |
9 | // We could also have an almost identical contract that supports the Paillier-encryption scheme
10 | contract FDE is BN254 {
11 |
12 | struct agreedPurchase {
13 | uint256 timeOut; // The protocol after this timestamp, simply aborts and returns funds.
14 | uint256 agreedPrice;
15 | Types.G1Point sellerPubKey;
16 | bool ongoingPurchase;
17 | bool fundsLocked;
18 | }
19 |
20 | // We assume that for a given seller-buyer pair, there is only a single purchase at any given time
21 | // Maps seller (server addresses) to buyer (client addresses) which in turn are mapped to tx details
22 | mapping(address => mapping(address => agreedPurchase)) public orderBook; // Privacy is out of scope for now
23 | mapping(address => uint256) balances; //stores the Eth balances of sellers
24 |
25 | // Events
26 | event BroadcastPubKey(address indexed _seller, address indexed _buyer, uint256 _pubKeyX, uint256 _timeOut, uint256 _agreedPrice);
27 | event BroadcastSecKey(address indexed _seller, address indexed _buyer, uint256 _secKey);
28 |
29 | constructor (
30 | ) {
31 | }
32 |
33 | // Agreed price could be set by the contract akin to Uniswap whereby price would be dynamically changing
34 | // according to a constant product formula given the current number of sellers and buyers (assuming
35 | // that each tx in the orderBook has the same volume)
36 | function sellerSendsPubKey(
37 | uint256 _timeOut,
38 | uint256 _agreedPrice,
39 | uint256 _pubKeyX,
40 | uint256 _pubKeyY,
41 | address _buyer
42 | ) public {
43 | require(!orderBook[msg.sender][_buyer].ongoingPurchase, "There can only be one purchase per buyer-seller pair!");
44 |
45 | orderBook[msg.sender][_buyer] = agreedPurchase({
46 | timeOut: _timeOut,
47 | agreedPrice: _agreedPrice,
48 | sellerPubKey: Types.G1Point(_pubKeyX, _pubKeyY),
49 | ongoingPurchase: true,
50 | fundsLocked: false
51 | });
52 |
53 | emit BroadcastPubKey(msg.sender, _buyer, _pubKeyX, _timeOut, _agreedPrice);
54 | }
55 |
56 | // If buyer agrees to the details of the purchase, then it locks the corresponding amount of money.
57 | function buyerLockPayment(
58 | address _seller
59 | ) public payable {
60 | agreedPurchase memory order = orderBook[_seller][msg.sender];
61 |
62 | requireOngoingPurchase(order);
63 |
64 | require(!order.fundsLocked, "Funds have been already locked!");
65 | require(msg.value == order.agreedPrice, "The transferred money does not match the agreed price!");
66 |
67 | orderBook[_seller][msg.sender].fundsLocked = true;
68 | }
69 |
70 | function sellerSendsSecKey(
71 | uint256 _secKey,
72 | address _buyer
73 | ) public {
74 | agreedPurchase memory order = orderBook[msg.sender][_buyer];
75 |
76 | requireOngoingPurchase(order);
77 |
78 | require(mul(P1(),_secKey).x == order.sellerPubKey.x, "Invalid secret key has been provided by the seller!");
79 |
80 | // this case is problematic for the seller, because they already revealed the secret key
81 | // but it is important for the health of the protocol that we don't increase their balance
82 | // if the funds have not been locked
83 | require(order.fundsLocked, "Funds have not been locked yet!");
84 |
85 | _terminateOrder(msg.sender, _buyer);
86 |
87 | balances[msg.sender] += order.agreedPrice;
88 |
89 | // There is no need to store the secret key in storage
90 | emit BroadcastSecKey(msg.sender, _buyer, _secKey);
91 | }
92 |
93 | // This function allocates funds to the server from previous accrued purchase incomes
94 | function withdrawPayment(
95 |
96 | ) public {
97 | uint256 balance = balances[msg.sender];
98 | if (balance != 0) {
99 | // We reset the balance to zero before the transfer to prevent reentrancy attacks
100 | balances[msg.sender] = 0;
101 |
102 | // forward all gas to the recipient
103 | (bool success, ) = payable(msg.sender).call{value: balance}("");
104 |
105 | // revert on error
106 | require(success, "Transfer failed.");
107 | }
108 | }
109 |
110 | // Buyer can withdraw its money if seller does not reveal the correct secret key.
111 | function withdrawPaymentAfterTimeout(
112 | address _seller
113 | ) public {
114 | agreedPurchase memory order = orderBook[_seller][msg.sender];
115 |
116 | requireOngoingPurchase(order);
117 | require(block.timestamp >= order.timeOut, "The seller has still time to provide the encryption secret key!");
118 | require(order.fundsLocked, "Funds have not been locked yet!");
119 |
120 | _terminateOrder(_seller, msg.sender);
121 |
122 | // forward all gas to the recipient
123 | (bool success, ) = payable(msg.sender).call{value: order.agreedPrice}("");
124 |
125 | // revert on error
126 | require(success, "Transfer failed.");
127 | }
128 |
129 | /// Key function for state management:
130 | /// - can only have a single ongoing purchase per buyer-seller pair
131 | /// - order must be ongoing for valid state transition (locking funds, revealing key, triggering refund)
132 | ///
133 | /// reverts if:
134 | /// - the order never existed
135 | /// - it has completed successfully
136 | /// - it has expired
137 | function requireOngoingPurchase(
138 | agreedPurchase memory _order
139 | ) internal pure {
140 | require(_order.ongoingPurchase, "No such order");
141 | }
142 |
143 | /// completely resets the state of an order (after expiration or completion)
144 | function _terminateOrder(
145 | address _seller,
146 | address _buyer
147 | ) internal {
148 | orderBook[_seller][_buyer] = agreedPurchase({
149 | timeOut: 0,
150 | agreedPrice: 0,
151 | sellerPubKey: Types.G1Point(0, 0),
152 | ongoingPurchase: false,
153 | fundsLocked: false
154 | });
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/contracts/FDEPaillier.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "./LibUint1024.sol";
5 |
6 |
7 | // We could also have an almost identical contract that supports the Paillier-encryption scheme
8 | contract FDEPaillier {
9 | using LibUint1024 for *;
10 |
11 | uint256 public agreedPrice;
12 | uint256 public timeOut; // The protocol after this timestamp, sipmly aborts and returns funds.
13 | address public buyer;
14 | address public seller;
15 | uint256[4] public sellerPubKey;
16 | bool public secretKeySent;
17 |
18 |
19 | // Events
20 | event BroadcastPubKey(address indexed _seller, address indexed _buyer, uint256[4] _pubKey);
21 | event BroadcastSecKey(address indexed _seller, address indexed _buyer, uint256[4] _secKey);
22 |
23 |
24 | constructor (
25 | uint256 _agreedPrice,
26 | uint256 _timeOut,
27 | address _buyer,
28 | address _seller
29 | ) {
30 | agreedPrice = _agreedPrice;
31 | timeOut = _timeOut;
32 | buyer = _buyer;
33 | seller = _seller;
34 | }
35 |
36 | // This function could be incorporated into the constructor?
37 | function sellerSendsPubKey(
38 | uint256[4] memory _pubKey
39 | ) public {
40 | require(msg.sender == seller, "Only the seller can provide the encryption public key!");
41 |
42 | sellerPubKey = _pubKey;
43 |
44 | emit BroadcastPubKey(seller, buyer, _pubKey);
45 | }
46 |
47 | function buyerLockPayment(
48 |
49 | ) public payable {
50 | require(!secretKeySent, "Secret keys have been already revealed!");
51 | require(msg.sender == buyer, "Only the buyer can lock the payment for the data!");
52 | require(msg.value == agreedPrice, "The transferred money does not match the agreed price!");
53 | }
54 |
55 | function sellerSendsSecKey(
56 | uint256[4] memory p,
57 | uint256[4] memory q
58 | ) public {
59 | require(msg.sender == seller);
60 | require(p.mulMod(q,[~uint256(0),~uint256(0),~uint256(0),~uint256(0)]).eq(sellerPubKey), "Invalid secret key has been provided by the seller!");
61 | secretKeySent = true;
62 | // There is no need to store the secret key in storage
63 | emit BroadcastSecKey(seller, buyer, p);
64 | }
65 |
66 | // This function allocates funds to the server if it already sent the encryption secret keys
67 | function withdrawPayment(
68 |
69 | ) public {
70 | require(secretKeySent, "The encryption secret key has not been provided by the seller!");
71 | payable(seller).transfer(address(this).balance);
72 | // selfdestruct(buyer); maybe we should clean up the storage?
73 |
74 | }
75 |
76 | function withdrawPaymentAfterTimout(
77 |
78 | ) public {
79 | require(!secretKeySent, "The encryption secret key has already been sent by the seller!");
80 | require(block.timestamp >= timeOut, "The seller has still time to provide the encryption secret key!");
81 | payable(buyer).transfer(address(this).balance);
82 | // selfdestruct(buyer); maybe we should clean up the storage?
83 | }
84 | }
--------------------------------------------------------------------------------
/contracts/LibUint1024.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0
2 | pragma solidity ^0.8;
3 |
4 |
5 | /// @dev A library for big (1024-bit) number arithmetic, including modular arithmetic
6 | /// operations.
7 | library LibUint1024 {
8 | using LibUint1024 for *;
9 |
10 | uint256 private constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
11 |
12 | error Overflow(uint256[4] a, uint256[4] b);
13 | error Underflow(uint256[4] a, uint256[4] b);
14 |
15 | /// @dev Converts a uint256 to its 1024-bit representation.
16 | function toUint1024(uint256 x)
17 | internal
18 | pure
19 | returns (uint256[4] memory bn)
20 | {
21 | bn[3] = x;
22 | }
23 |
24 | /// @dev Computes a + b, reverting on overflow.
25 | function add(uint256[4] memory a, uint256[4] memory b)
26 | internal
27 | pure
28 | returns (uint256[4] memory c)
29 | {
30 | uint256 carry;
31 | (c, carry) = _add(a, b);
32 | if (carry != 0) {
33 | revert Overflow(a, b);
34 | }
35 | }
36 |
37 | /// @dev Computes a - b, reverting on underflow.
38 | function sub(uint256[4] memory a, uint256[4] memory b)
39 | internal
40 | pure
41 | returns (uint256[4] memory c)
42 | {
43 | uint256 carry;
44 | (c, carry) = _sub(a, b);
45 | if (carry != 0) {
46 | revert Underflow(a, b);
47 | }
48 | }
49 |
50 | /// @dev Computes a + b, returning the 1024-bit result and the carry bit.
51 | function _add(uint256[4] memory a, uint256[4] memory b)
52 | internal
53 | pure
54 | returns (uint256[4] memory c, uint256 carry)
55 | {
56 | assembly {
57 | // c[3] = a[3] + b[3]
58 | let aWord := mload(add(a, 0x60))
59 | let bWord := mload(add(b, 0x60))
60 | let sum := add(aWord, bWord)
61 | mstore(add(c, 0x60), sum)
62 | // carry = c[3] < a[3]
63 | carry := lt(sum, aWord)
64 |
65 | // c[2] = a[2] + b[2] + carry
66 | aWord := mload(add(a, 0x40))
67 | bWord := mload(add(b, 0x40))
68 | sum := add(aWord, bWord)
69 | let cWord := add(sum, carry)
70 | mstore(add(c, 0x40), cWord)
71 | // carry = (a[2] + b[2] < a[2]) || (c[2] < a[2] + b[2])
72 | carry := or(lt(sum, aWord), lt(cWord, sum))
73 |
74 | // c[1] = a[1] + b[1] + carry
75 | aWord := mload(add(a, 0x20))
76 | bWord := mload(add(b, 0x20))
77 | sum := add(aWord, bWord)
78 | cWord := add(sum, carry)
79 | mstore(add(c, 0x20), cWord)
80 | // carry = (a[1] + b[1] < a[1]) || (c[1] < a[1] + b[1])
81 | carry := or(lt(sum, aWord), lt(cWord, sum))
82 |
83 | // c[0] = a[0] + b[0] + carry
84 | aWord := mload(a)
85 | bWord := mload(b)
86 | sum := add(aWord, bWord)
87 | cWord := add(sum, carry)
88 | mstore(c, cWord)
89 | // carry = (a[0] + b[0] < a[0]) || (c[0] < a[0] + b[0])
90 | carry := or(lt(sum, aWord), lt(cWord, sum))
91 | }
92 | }
93 |
94 | /// @dev Computes a - b, returning the 1024-bit result and the carry bit.
95 | function _sub(uint256[4] memory a, uint256[4] memory b)
96 | internal
97 | pure
98 | returns (uint256[4] memory c, uint256 carry)
99 | {
100 | assembly {
101 | // c[3] = a[3] - b[3]
102 | let aWord := mload(add(a, 0x60))
103 | let bWord := mload(add(b, 0x60))
104 | let diff := sub(aWord, bWord)
105 | mstore(add(c, 0x60), diff)
106 | // carry = a[3] < b[3]
107 | carry := lt(aWord, bWord)
108 |
109 | // c[2] = a[2] - b[2]
110 | aWord := mload(add(a, 0x40))
111 | bWord := mload(add(b, 0x40))
112 | diff := sub(aWord, bWord)
113 | mstore(add(c, 0x40), sub(diff, carry))
114 | // carry = (a[2] < b[2]) || (c[2] < carry)
115 | carry := or(lt(aWord, bWord), lt(diff, carry))
116 |
117 | // c[1] = a[1] - b[1]
118 | aWord := mload(add(a, 0x20))
119 | bWord := mload(add(b, 0x20))
120 | diff := sub(aWord, bWord)
121 | mstore(add(c, 0x20), sub(diff, carry))
122 | // carry = (a[1] < b[1]) || (c[1] < carry)
123 | carry := or(lt(aWord, bWord), lt(diff, carry))
124 |
125 | // c[0] = a[0] - b[0]
126 | aWord := mload(a)
127 | bWord := mload(b)
128 | diff := sub(aWord, bWord)
129 | mstore(c, sub(diff, carry))
130 | // carry = (a[0] < b[0]) || (c[0] < carry)
131 | carry := or(lt(aWord, bWord), lt(diff, carry))
132 | }
133 | }
134 |
135 | /// @dev a == b
136 | function eq(uint256[4] memory a, uint256[4] memory b)
137 | internal
138 | pure
139 | returns (bool)
140 | {
141 | return
142 | a[0] == b[0] &&
143 | a[1] == b[1] &&
144 | a[2] == b[2] &&
145 | a[3] == b[3];
146 | }
147 |
148 | /// @dev a > b
149 | function gt(uint256[4] memory a, uint256[4] memory b)
150 | internal
151 | pure
152 | returns (bool)
153 | {
154 | return _gt(a, b, false);
155 | }
156 |
157 | /// @dev a ≥ b
158 | function gte(uint256[4] memory a, uint256[4] memory b)
159 | internal
160 | pure
161 | returns (bool)
162 | {
163 | return _gt(a, b, true);
164 | }
165 |
166 | function _gt(
167 | uint256[4] memory a,
168 | uint256[4] memory b,
169 | bool trueIfEqual
170 | )
171 | private
172 | pure
173 | returns (bool)
174 | {
175 | if (a[0] < b[0]) {
176 | return false;
177 | } else if (a[0] > b[0]) {
178 | return true;
179 | }
180 | if (a[1] < b[1]) {
181 | return false;
182 | } else if (a[1] > b[1]) {
183 | return true;
184 | }
185 | if (a[2] < b[2]) {
186 | return false;
187 | } else if (a[2] > b[2]) {
188 | return true;
189 | }
190 | if (a[3] < b[3]) {
191 | return false;
192 | }
193 | return trueIfEqual || a[3] > b[3];
194 | }
195 |
196 | /// @dev a < b
197 | function lt(uint256[4] memory a, uint256[4] memory b)
198 | internal
199 | pure
200 | returns (bool)
201 | {
202 | return _lt(a, b, false);
203 | }
204 |
205 | /// a ≤ b
206 | function lte(uint256[4] memory a, uint256[4] memory b)
207 | internal
208 | pure
209 | returns (bool)
210 | {
211 | return _lt(a, b, true);
212 | }
213 |
214 | function _lt(
215 | uint256[4] memory a,
216 | uint256[4] memory b,
217 | bool trueIfEqual
218 | )
219 | private
220 | pure
221 | returns (bool)
222 | {
223 | if (a[0] > b[0]) {
224 | return false;
225 | } else if (a[0] < b[0]) {
226 | return true;
227 | }
228 | if (a[1] > b[1]) {
229 | return false;
230 | } else if (a[1] < b[1]) {
231 | return true;
232 | }
233 | if (a[2] > b[2]) {
234 | return false;
235 | } else if (a[2] < b[2]) {
236 | return true;
237 | }
238 | if (a[3] > b[3]) {
239 | return false;
240 | }
241 | return trueIfEqual || a[3] < b[3];
242 | }
243 |
244 | /// @dev Computes (a * b) % modulus. Assumes a < modulus and b < modulus.
245 | /// Based on the "schoolbook" multiplication algorithm, using the EXPMOD
246 | /// precompile to reduce by the modulus.
247 | function mulMod(uint256[4] memory a, uint256[4] memory b, uint256[4] memory modulus)
248 | internal
249 | view
250 | returns (uint256[4] memory result)
251 | {
252 | assembly {
253 | // Computes x + y and increments the carry value if
254 | // x + y overflows.
255 | function addWithCarry(x, y, carry) -> z, updatedCarry {
256 | z := add(x, y)
257 | updatedCarry := add(carry, lt(z, x))
258 | }
259 |
260 | // Multiplies two 256-bit mumbers to obtain the full 512-bit
261 | // result. h/t Remco Bloemen for this implementation:
262 | // https://medium.com/wicketh/mathemagic-full-multiply-27650fec525d
263 | function mul512(x, y) -> r1, r0 {
264 | let mm := mulmod(x, y, MAX_UINT)
265 | r0 := mul(x, y)
266 | r1 := sub(sub(mm, r0), lt(mm, r0))
267 | }
268 |
269 | // The implementation roughly follows the schoolbook method:
270 |
271 | // ===a[0]== ===a[1]== ===a[2]== ===a[3]==
272 | // x ===b[0]== ===b[1]== ===b[2]== ===b[3]==
273 | // –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
274 | // ======a[3]b[3]======
275 | // ======a[2]b[3]======
276 | // ======a[1]b[3]======
277 | // ======a[0]b[3]======
278 | // ======a[3]b[2]======
279 | // ======a[2]b[2]======
280 | // ======a[1]b[2]======
281 | // ======a[0]b[2]======
282 | // ======a[3]b[1]======
283 | // ======a[2]b[1]======
284 | // ======a[1]b[1]======
285 | // ======a[0]b[1]======
286 | // ======a[3]b[0]======
287 | // ======a[2]b[0]======
288 | // ======a[1]b[0]======
289 | // ======a[0]b[0]======
290 | // –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
291 | // | | | | | | | |
292 | // | | | | | | | |
293 | // r0 | r1 | r2 | r3 | r4 | r5 | r6 | r7 |
294 |
295 | // Each a[j]b[k] is computed using mul512, so the result occupies two words.
296 | // Let a[j]b[k].h and a[j]b[k].l denote the high and low words, respectively.
297 |
298 | // Each ri will be computed as the sum of all the words in its column, plus the
299 | // carry ci from r{i+1}.
300 |
301 | // For example:
302 | // r7 := a[3]b[3].l
303 | // r6 := a[3]b[3].h + a[2]b[3].l + a[3]b[2].l
304 | // c5 := the carry value from the above sum
305 | // r5 := a[2]b[3].h + a[3]b[2].h + a[1]b[3].l + a[2]b[2].l + a[3]b[1].l + c5
306 | // c4 :+ the carry value from the above sum
307 | // ...and so on
308 |
309 | let p := mload(0x40)
310 |
311 | // Load all four words of a
312 | let a0 := mload(a)
313 | let a1 := mload(add(a, 0x20))
314 | let a2 := mload(add(a, 0x40))
315 | let a3 := mload(add(a, 0x60))
316 |
317 | // This is where the words of the multiplication result (before reduction) will go.
318 | let r0 := 0
319 | let r1 := 0
320 | let r2 := 0
321 | let r3 := 0
322 | let r4 := 0
323 | let r5 := 0
324 | let r6 := 0
325 |
326 | // These will keep track of the carry values for each column.
327 | let c0 := 0
328 | let c1 := 0
329 | let c2 := 0
330 | let c3 := 0
331 | let c4 := 0
332 | let c5 := 0
333 |
334 | let h := 0
335 | let l := 0
336 |
337 | // b[3]
338 | let bi := mload(add(b, 0x60))
339 |
340 | // r6 = a[3]b[3].h
341 | // r7 = a[3]b[3].l
342 | r6, l := mul512(a3, bi)
343 | // r7 doesn't get an explicit stack variable, we just mstore it immediately.
344 | mstore(add(p, 0x140), l)
345 |
346 | // r5 = a[2]b[3].h
347 | // r6 += a[2]b[3].l
348 | // c5 = carry from above addition
349 | r5, l := mul512(a2, bi)
350 | r6, c5 := addWithCarry(r6, l, 0)
351 |
352 | // r4 = a[1]b[3].h
353 | // r5 += a[1]b[3].l
354 | // c4 = carry from above addition
355 | r4, l := mul512(a1, bi)
356 | r5, c4 := addWithCarry(r5, l, 0)
357 |
358 | // r3 = a[0]b[3].h
359 | // r4 += a[0]b[3].l
360 | // c3 = carry from above addition
361 | r3, l := mul512(a0, bi)
362 | r4, c3 := addWithCarry(r4, l, 0)
363 |
364 | // b[2]
365 | bi := mload(add(b, 0x40))
366 |
367 | // r6 += a[3]b[2].l
368 | // c5 += carry from above addition
369 | // r5 += a[3]b[2].h
370 | // c4 += carry from above addition
371 | h, l := mul512(a3, bi)
372 | r6, c5 := addWithCarry(r6, l, c5)
373 | r5, c4 := addWithCarry(r5, h, c4)
374 |
375 | // r5 += a[2]b[2].l
376 | // c4 += carry from above addition
377 | // r4 += a[2]b[2].h
378 | // c3 += carry from above addition
379 | h, l := mul512(a2, bi)
380 | r5, c4 := addWithCarry(r5, l, c4)
381 | r4, c3 := addWithCarry(r4, h, c3)
382 |
383 | // r4 += a[1]b[2].l
384 | // c3 += carry from above addition
385 | // r3 += a[1]b[2].h
386 | // c2 += carry from above addition
387 | h, l := mul512(a1, bi)
388 | r4, c3 := addWithCarry(r4, l, c3)
389 | r3, c2 := addWithCarry(r3, h, c2)
390 |
391 | // r3 += a[0]b[2].l
392 | // c2 += carry from above addition
393 | // r2 += a[0]b[2].h
394 | // c1 += carry from above addition
395 | h, l := mul512(a0, bi)
396 | r3, c2 := addWithCarry(r3, l, c2)
397 | r2, c1 := addWithCarry(r2, h, c1)
398 |
399 | // b[1]
400 | bi := mload(add(b, 0x20))
401 |
402 | // r5 += a[3]b[1].l
403 | // c4 += carry from above addition
404 | // r4 += a[3]b[1].h
405 | // c3 += carry from above addition
406 | h, l := mul512(a3, bi)
407 | r5, c4 := addWithCarry(r5, l, c4)
408 | r4, c3 := addWithCarry(r4, h, c3)
409 |
410 | // r4 += a[2]b[1].l
411 | // c3 += carry from above addition
412 | // r3 += a[2]b[1].h
413 | // c2 += carry from above addition
414 | h, l := mul512(a2, bi)
415 | r4, c3 := addWithCarry(r4, l, c3)
416 | r3, c2 := addWithCarry(r3, h, c2)
417 |
418 | // r3 += a[1]b[1].l
419 | // c2 += carry from above addition
420 | // r2 += a[1]b[1].h
421 | // c1 += carry from above addition
422 | h, l := mul512(a1, bi)
423 | r3, c2 := addWithCarry(r3, l, c2)
424 | r2, c1 := addWithCarry(r2, h, c1)
425 |
426 | // r2 += a[0]b[1].l
427 | // c1 += carry from above addition
428 | // r1 += a[0]b[1].h
429 | // c0 += carry from above addition
430 | h, l := mul512(a0, bi)
431 | r2, c1 := addWithCarry(r2, l, c1)
432 | r1, c0 := addWithCarry(r1, h, c0)
433 |
434 | // b[0]
435 | bi := mload(b)
436 |
437 | // r4 += a[3]b[0].l
438 | // c3 += carry from above addition
439 | // r3 += a[3]b[0].h
440 | // c2 += carry from above addition
441 | h, l := mul512(a3, bi)
442 | r4, c3 := addWithCarry(r4, l, c3)
443 | r3, c2 := addWithCarry(r3, h, c2)
444 |
445 | // r3 += a[2]b[0].l
446 | // c2 += carry from above addition
447 | // r2 += a[2]b[0].h
448 | // c1 += carry from above addition
449 | h, l := mul512(a2, bi)
450 | r3, c2 := addWithCarry(r3, l, c2)
451 | r2, c1 := addWithCarry(r2, h, c1)
452 |
453 | // r2 += a[1]b[0].l
454 | // c1 += carry from above addition
455 | // r1 += a[1]b[0].h
456 | // c0 += carry from above addition
457 | h, l := mul512(a1, bi)
458 | r2, c1 := addWithCarry(r2, l, c1)
459 | r1, c0 := addWithCarry(r1, h, c0)
460 |
461 | // r1 += a[0]b[0].l
462 | // c0 += carry from above addition
463 | // r0 = a[0]b[0].h
464 | r0, l := mul512(a0, bi)
465 | r1, c0 := addWithCarry(r1, l, c0)
466 |
467 | // r5 += c5
468 | // c4 += carry from above addition
469 | r5 := add(r5, c5)
470 | c4 := add(c4, lt(r5, c5))
471 |
472 | // r4 += c4
473 | // c3 += carry from above addition
474 | r4 := add(r4, c4)
475 | c3 := add(c3, lt(r4, c4))
476 |
477 | // r3 += c3
478 | // c2 += carry from above addition
479 | r3 := add(r3, c3)
480 | c2 := add(c2, lt(r3, c3))
481 |
482 | // r2 += c2
483 | // c1 += carry from above addition
484 | r2 := add(r2, c2)
485 | c1 := add(c1, lt(r2, c2))
486 |
487 | // r1 += c1
488 | // c0 += carry from above addition
489 | r1 := add(r1, c1)
490 | c0 := add(c0, lt(r1, c1))
491 |
492 | // r0 += c0 (cannot overflow)
493 | mstore(add(p, 0x60), add(r0, c0))
494 |
495 | // Use EXPMOD precompile to compute
496 | // (r ** 1) % modulus = r % modulus
497 |
498 | // Store parameters for the EXPMOD precompile
499 | mstore(p, 0x100) // Length of base (8 * 32 = 256 bytes)
500 | mstore(add(p, 0x20), 0x20) // Length of exponent
501 | mstore(add(p, 0x40), 0x80) // Length of modulus (4 * 32 = 128 bytes)
502 |
503 | // Store the base
504 | mstore(add(p, 0x80), r1)
505 | mstore(add(p, 0xa0), r2)
506 | mstore(add(p, 0xc0), r3)
507 | mstore(add(p, 0xe0), r4)
508 | mstore(add(p, 0x100), r5)
509 | mstore(add(p, 0x120), r6)
510 |
511 | // Store the exponent
512 | mstore(add(p, 0x160), 1)
513 |
514 | // Use Identity (0x04) precompile to memcpy the modulus
515 | if iszero(staticcall(gas(), 0x04, modulus, 0x80, add(p, 0x180), 0x80)) {
516 | revert(0, 0)
517 | }
518 | // Call 0x05 (EXPMOD) precompile
519 | if iszero(staticcall(gas(), 0x05, p, 0x200, result, 0x80)) {
520 | revert(0, 0)
521 | }
522 |
523 | // Update free memory pointer
524 | mstore(0x40, add(p, 0x200))
525 | }
526 | }
527 |
528 | /// @dev Computes (a + b) % modulus. Assumes a < modulus and b < modulus.
529 | function addMod(uint256[4] memory a, uint256[4] memory b, uint256[4] memory modulus)
530 | internal
531 | pure
532 | returns (uint256[4] memory result)
533 | {
534 | uint256 carry;
535 | (result, carry) = _add(a, b);
536 | if (carry == 1 || result.gte(modulus)) {
537 | (result, ) = _sub(result, modulus);
538 | }
539 | }
540 |
541 | /// @dev Computes (a - b) % modulus. Assumes a < modulus and b < modulus.
542 | function subMod(uint256[4] memory a, uint256[4] memory b, uint256[4] memory modulus)
543 | internal
544 | pure
545 | returns (uint256[4] memory result)
546 | {
547 | if (a.gte(b)) {
548 | return a.sub(b);
549 | } else {
550 | return modulus.sub(b.sub(a));
551 | }
552 | }
553 |
554 | /// @dev Computes (base ** exponent) % modulus
555 | function expMod(uint256[4] memory base, uint256 exponent, uint256[4] memory modulus)
556 | internal
557 | view
558 | returns (uint256[4] memory result)
559 | {
560 | assembly {
561 | // Get free memory pointer
562 | let p := mload(0x40)
563 |
564 | // Store parameters for the EXPMOD precompile
565 | mstore(p, 0x80) // Length of base (4 * 32 = 128 bytes)
566 | mstore(add(p, 0x20), 0x20) // Length of exponent (32 bytes)
567 | mstore(add(p, 0x40), 0x80) // Length of modulus (4 * 32 = 128 bytes)
568 |
569 | // Use Identity (0x04) precompile to memcpy the base
570 | if iszero(staticcall(gas(), 0x04, base, 0x80, add(p, 0x60), 0x80)) {
571 | revert(0, 0)
572 | }
573 | // Store the exponent
574 | mstore(add(p, 0xe0), exponent)
575 | // Use Identity (0x04) precompile to memcpy the modulus
576 | if iszero(staticcall(gas(), 0x04, modulus, 0x80, add(p, 0x100), 0x80)) {
577 | revert(0, 0)
578 | }
579 | // Call 0x05 (EXPMOD) precompile
580 | if iszero(staticcall(gas(), 0x05, p, 0x180, result, 0x80)) {
581 | revert(0, 0)
582 | }
583 |
584 | // Update free memory pointer
585 | mstore(0x40, add(p, 0x180))
586 | }
587 | }
588 |
589 | /// @dev Computes (base ** exponent) % modulus
590 | function expMod(
591 | uint256[4] memory base,
592 | uint256[4] memory exponent,
593 | uint256[4] memory modulus
594 | )
595 | internal
596 | view
597 | returns (uint256[4] memory result)
598 | {
599 | assembly {
600 | // Get free memory pointer
601 | let p := mload(0x40)
602 |
603 | // Store parameters for the EXPMOD precompile
604 | mstore(p, 0x80) // Length of base (4 * 32 = 128 bytes)
605 | mstore(add(p, 0x20), 0x80) // Length of exponent (4 * 32 = 128 bytes)
606 | mstore(add(p, 0x40), 0x80) // Length of modulus (4 * 32 = 128 bytes)
607 |
608 | // Use Identity (0x04) precompile to memcpy the base
609 | if iszero(staticcall(gas(), 0x04, base, 0x80, add(p, 0x60), 0x80)) {
610 | revert(0, 0)
611 | }
612 | // Use Identity (0x04) precompile to memcpy the exponent
613 | if iszero(staticcall(gas(), 0x04, exponent, 0x80, add(p, 0xe0), 0x80)) {
614 | revert(0, 0)
615 | }
616 | // Use Identity (0x04) precompile to memcpy the modulus
617 | if iszero(staticcall(gas(), 0x04, modulus, 0x80, add(p, 0x160), 0x80)) {
618 | revert(0, 0)
619 | }
620 | // Call 0x05 (EXPMOD) precompile
621 | if iszero(staticcall(gas(), 0x05, p, 0x1e0, result, 0x80)) {
622 | revert(0, 0)
623 | }
624 |
625 | // Update free memory pointer
626 | mstore(0x40, add(p, 0x1e0))
627 | }
628 | }
629 |
630 | /// @dev Converts an element `x` of the RSA group Z_N to its "coset
631 | /// representative", defined to be min(x mod N, -x mod N). This ensures
632 | /// that the low-order assumption is not trivially false, see Section 6:
633 | /// http://crypto.stanford.edu/~dabo/papers/VDFsurvey.pdf
634 | function normalize(
635 | uint256[4] memory x,
636 | uint256[4] memory modulus
637 | )
638 | internal
639 | pure
640 | returns (uint256[4] memory normalized)
641 | {
642 | uint256[4] memory negX = modulus.sub(x);
643 | if (negX.lt(x)) {
644 | return negX;
645 | }
646 | return x;
647 | }
648 | }
--------------------------------------------------------------------------------
/contracts/Types.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | library Types {
5 | struct G1Point {
6 | uint256 x;
7 | uint256 y;
8 | }
9 | // G2 group element where x \in Fq2 = x0 * z + x1
10 | struct G2Point {
11 | uint256 x0;
12 | uint256 x1;
13 | uint256 y0;
14 | uint256 y1;
15 | }
16 |
17 | struct ChallengeTranscript {
18 | /* 0x00 */ uint256 v;
19 | /* 0x20 */ uint256 hi_2;
20 | /* 0x40 */ uint256 alpha;
21 | /* 0x60 */ uint256 x1;
22 | /* 0x80 */ uint256 x2;
23 | /* 0xa0 */ uint256 x3;
24 | /* 0xc0 */ uint256 x4;
25 | /* 0xe0 */ uint256 s;
26 | }
27 |
28 | struct VerifierTranscript {
29 | /* 0x00 */ uint256 d;
30 | /* 0x20 */ uint256 omega_alpha;
31 | /* 0x40 */ uint256 omega_n_alpha;
32 | /* 0x60 */ uint256 dMinusOneInv;
33 | /* 0x80 */ uint256 xi_minus_v_inv;
34 | /* 0xa0 */ uint256 xi_minus_alpha_inv;
35 | /* 0xc0 */ uint256 xi_minus_omega_alpha_inv;
36 | /* 0xe0 */ uint256 xi_minus_omega_n_alpha_inv;
37 | /* 0x100 */ uint256 alpha_minus_omega_alpha_inv;
38 | /* 0x120 */ uint256 alpha_minus_omega_n_alpha_inv;
39 | /* 0x140 */ uint256 omega_alpha_minus_omega_n_alpha_inv;
40 | /* 0x160 */ uint256 l0Eval;
41 | /* 0x180 */ uint256 zhEval;
42 | /* 0x1a0 */ uint256 x1_pow_2;
43 | /* 0x1c0 */ uint256 x1_pow_3;
44 | /* 0x1e0 */ uint256 x1_pow_4;
45 | /* 0x200 */ uint256 x2_pow_2;
46 | /* 0x220 */ uint256 x2_pow_3;
47 | /* 0x240 */ uint256 x4_pow_2;
48 | /* 0x260 */ uint256 x4_pow_3;
49 | /* 0x280 */ uint256 x4_pow_4;
50 | /* 0x2a0 */ Types.G1Point q2;
51 | /* 0x2c0 */ Types.G1Point q4;
52 | /* 0x2e0 */ uint256 q4_at_alpha;
53 | /* 0x300 */ uint256 q4_at_omega_alpha;
54 | /* 0x320 */ uint256 q4_at_omega_n_alpha;
55 | /* 0x340 */ uint256 q2_eval;
56 | /* 0x360 */ uint256 f1;
57 | /* 0x380 */ uint256 f2;
58 | /* 0x3a0 */ uint256 f3;
59 | /* 0x3c0 */ uint256 f4;
60 | /* 0x3e0 */ uint256 xi_minus_omega_alpha;
61 | /* 0x400 */ uint256 xi_minus_alpha;
62 | /* 0x420 */ uint256 xi_minus_omega_n_alpha;
63 | /* 0x440 */ uint256 omega_alpha_minus_alpha_inv;
64 | /* 0x460 */ uint256 z3_xi;
65 | /* 0x480 */ uint256 f_eval;
66 | /* 0x4a0 */ Types.G1Point final_poly;
67 | /* 0x4c0 */ uint256 final_poly_eval;
68 | }
69 |
70 | struct Commitments {
71 | /* 0x00 */ Types.G1Point w0;
72 | /* 0x40 */ Types.G1Point w1;
73 | /* 0x80 */ Types.G1Point w2;
74 | /* 0xc0 */ Types.G1Point key;
75 | /* 0x100 */ Types.G1Point mimc_cts;
76 | /* 0x140 */ Types.G1Point quotient;
77 | /* 0x180 */ Types.G1Point u_prime;
78 | /* 0x1c0 */ Types.G1Point zi;
79 | /* 0x200 */ Types.G1Point ci;
80 | /* 0x240 */ Types.G1Point p1;
81 | /* 0x280 */ Types.G1Point p2;
82 | /* 0x2c0 */ Types.G1Point q_mimc;
83 | /* 0x300 */ Types.G1Point h;
84 | /* 0x340 */ Types.G2Point w;
85 | }
86 |
87 | struct Openings {
88 | /* 0x00 */ uint256 q_mimc;
89 | /* 0x20 */ uint256 mimc_cts;
90 | /* 0x40 */ uint256 quotient;
91 | /* 0x60 */ uint256 u_prime;
92 | /* 0x80 */ uint256 p1;
93 | /* 0xa0 */ uint256 p2;
94 | /* 0xc0 */ uint256 w0_0;
95 | /* 0xe0 */ uint256 w0_1;
96 | /* 0x100 */ uint256 w0_2;
97 | /* 0x120 */ uint256 w1_0;
98 | /* 0x140 */ uint256 w1_1;
99 | /* 0x160 */ uint256 w1_2;
100 | /* 0x180 */ uint256 w2_0;
101 | /* 0x1a0 */ uint256 w2_1;
102 | /* 0x1c0 */ uint256 w2_2;
103 | /* 0x1e0 */ uint256 key_0;
104 | /* 0x200 */ uint256 key_1;
105 | }
106 |
107 | struct MultiopenProof {
108 | /* 0x00 */ uint256 q1_opening;
109 | /* 0x20 */ uint256 q2_opening;
110 | /* 0x40 */ uint256 q3_opening;
111 | /* 0x60 */ uint256 q4_opening;
112 | /* 0x80 */ Types.G1Point f_cm;
113 | /* 0xa0 */ Types.G1Point final_poly_proof;
114 | }
115 |
116 | struct Proof {
117 | /* 0x00 */ MultiopenProof multiopenProof;
118 | /* 0x20 */ Openings openings;
119 | /* 0x40 */ Commitments commitments;
120 | }
121 | }
--------------------------------------------------------------------------------
/src/adaptor_sig.rs:
--------------------------------------------------------------------------------
1 | use ark_crypto_primitives::signature::schnorr::{Schnorr, SecretKey, Signature};
2 | use ark_crypto_primitives::signature::SignatureScheme;
3 | use ark_crypto_primitives::Error;
4 | use ark_ec::{AffineRepr, CurveGroup};
5 | use ark_ff::Field;
6 | use ark_serialize::CanonicalSerialize;
7 | use ark_std::rand::Rng;
8 | use ark_std::UniformRand;
9 | use digest::Digest;
10 |
11 | pub trait AdaptorSignatureScheme: SignatureScheme {
12 | type PreSignature;
13 |
14 | fn pre_sign(
15 | adaptor_pk: &Self::PublicKey,
16 | signer_sk: &Self::SecretKey,
17 | message: &[u8],
18 | rng: &mut R,
19 | ) -> Result;
20 |
21 | fn verify(
22 | signature: &Self::PreSignature,
23 | adaptor_pk: &Self::PublicKey,
24 | signer_pk: &Self::PublicKey,
25 | message: &[u8],
26 | ) -> Result<(), Error>;
27 |
28 | fn adapt(
29 | signature: &Self::PreSignature,
30 | adaptor_sk: &Self::SecretKey,
31 | ) -> Result;
32 |
33 | fn extract(
34 | pre_signature: &Self::PreSignature,
35 | signature: &Self::Signature,
36 | adaptor_pk: &Self::PublicKey,
37 | ) -> Result;
38 | }
39 |
40 | impl AdaptorSignatureScheme for Schnorr {
41 | type PreSignature = Signature;
42 | fn pre_sign(
43 | adaptor_pk: &Self::PublicKey,
44 | signer_sk: &Self::SecretKey,
45 | message: &[u8],
46 | rng: &mut R,
47 | ) -> Result {
48 | let signer_pk = (::generator() * signer_sk.0).into_affine();
49 | // random nonce (r) sampled uniformly
50 | let random_nonce = C::ScalarField::rand(rng);
51 | // commitment is shifted by the adaptor's pubkey
52 | // R_hat = r * G + Y
53 | let commitment =
54 | (::generator() * random_nonce + adaptor_pk).into_affine();
55 | // compute challenge from public values (R_hat, X, m)
56 | let verifier_challenge = hash_challenge::(&commitment, &signer_pk, message)?;
57 | // s_hat = r - cx
58 | let prover_response = random_nonce - verifier_challenge * signer_sk.0;
59 |
60 | Ok(Signature {
61 | prover_response,
62 | verifier_challenge,
63 | })
64 | }
65 |
66 | fn verify(
67 | signature: &Self::PreSignature,
68 | adaptor_pk: &Self::PublicKey,
69 | signer_pk: &Self::PublicKey,
70 | message: &[u8],
71 | ) -> Result<(), Error> {
72 | let &Signature {
73 | prover_response,
74 | verifier_challenge,
75 | } = signature;
76 | // s_hat * G + c * X + Y
77 | let commitment = ::generator() * prover_response
78 | + *signer_pk * verifier_challenge
79 | + adaptor_pk;
80 | // compute challenge
81 | let challenge = hash_challenge::(&commitment.into_affine(), signer_pk, message)?;
82 | if challenge != verifier_challenge {
83 | Err("verification failure".into())
84 | } else {
85 | Ok(())
86 | }
87 | }
88 |
89 | fn adapt(
90 | signature: &Self::PreSignature,
91 | adaptor_sk: &Self::SecretKey,
92 | ) -> Result {
93 | let &Signature {
94 | prover_response,
95 | verifier_challenge,
96 | } = signature;
97 | Ok(Signature {
98 | prover_response: prover_response + adaptor_sk.0,
99 | verifier_challenge,
100 | })
101 | }
102 |
103 | fn extract(
104 | pre_signature: &Self::PreSignature,
105 | signature: &Self::Signature,
106 | adaptor_pk: &Self::PublicKey,
107 | ) -> Result {
108 | let &Signature {
109 | prover_response: pre_prover_response,
110 | ..
111 | } = pre_signature;
112 | let &Signature {
113 | prover_response, ..
114 | } = signature;
115 | let sk = prover_response - pre_prover_response;
116 | let pk = (::generator() * sk).into_affine();
117 | if pk != *adaptor_pk {
118 | Err("invalid signatures".into())
119 | } else {
120 | Ok(SecretKey(sk))
121 | }
122 | }
123 | }
124 |
125 | fn hash_challenge(
126 | commitment: &C::Affine,
127 | signer_pk: &C::Affine,
128 | message: &[u8],
129 | ) -> Result {
130 | let mut hash_input = Vec::new();
131 | commitment.serialize_compressed(&mut hash_input)?;
132 | signer_pk.serialize_compressed(&mut hash_input)?;
133 | message.serialize_compressed(&mut hash_input)?;
134 |
135 | C::ScalarField::from_random_bytes(&D::digest(&hash_input))
136 | .ok_or::("invalid challenge".into())
137 | }
138 |
139 | #[cfg(test)]
140 | mod test {
141 | use super::*;
142 | use ark_ec::Group;
143 | use ark_secp256k1::Projective as Secp256k1;
144 | use ark_std::test_rng;
145 | use sha3::Keccak256;
146 |
147 | type Scheme = Schnorr;
148 |
149 | fn keygen(
150 | rng: &mut R,
151 | ) -> (
152 | ::PublicKey,
153 | ::SecretKey,
154 | ) {
155 | let mut parameters = Scheme::setup(rng).unwrap();
156 | parameters.generator = Secp256k1::generator().into_affine();
157 | Scheme::keygen(¶meters, rng).unwrap()
158 | }
159 |
160 | #[test]
161 | fn completeness() {
162 | // setup and keygen
163 | let rng = &mut test_rng();
164 | let (signer_pk, signer_sk) = keygen(rng);
165 | let (adaptor_pk, adaptor_sk) = keygen(rng);
166 |
167 | // pre-signature generation
168 | let message = b"hello adaptor signature";
169 | let pre_sig = Scheme::pre_sign(&adaptor_pk, &signer_sk, message, rng).unwrap();
170 | // verify pre-signature
171 | assert!(::verify(
172 | &pre_sig,
173 | &adaptor_pk,
174 | &signer_pk,
175 | message
176 | )
177 | .is_ok());
178 |
179 | // adapt and verify signature
180 | let adapted_sig = Scheme::adapt(&pre_sig, &adaptor_sk).unwrap();
181 |
182 | // s + y
183 | let commitment = Secp256k1::generator() * adapted_sig.prover_response
184 | + signer_pk * adapted_sig.verifier_challenge;
185 |
186 | let challenge =
187 | hash_challenge::(&commitment.into_affine(), &signer_pk, message)
188 | .unwrap();
189 |
190 | assert_eq!(challenge, adapted_sig.verifier_challenge);
191 |
192 | // extract adaptor secret key
193 | let extracted_sk = Scheme::extract(&pre_sig, &adapted_sig, &adaptor_pk).unwrap();
194 | assert_eq!(extracted_sk.0, adaptor_sk.0);
195 | }
196 |
197 | #[test]
198 | fn soundness() {
199 | // setup and keygen
200 | let rng = &mut test_rng();
201 | let (signer_pk, signer_sk) = keygen(rng);
202 | let (adaptor_pk, _adaptor_sk) = keygen(rng);
203 |
204 | let message = b"hello adaptor signature";
205 |
206 | // pre-signature generation (with invalid adaptor pubkey)
207 | let pre_sig = Scheme::pre_sign(&signer_pk, &signer_sk, message, rng).unwrap();
208 | assert!(::verify(
209 | &pre_sig,
210 | &adaptor_pk,
211 | &signer_pk,
212 | message
213 | )
214 | .is_err());
215 |
216 | // pre-signature generation (with invalid message pubkey)
217 | let pre_sig = Scheme::pre_sign(&adaptor_pk, &signer_sk, b"invalid", rng).unwrap();
218 | assert!(::verify(
219 | &pre_sig,
220 | &adaptor_pk,
221 | &signer_pk,
222 | message
223 | )
224 | .is_err());
225 |
226 | // valid pre-signature
227 | let pre_sig = Scheme::pre_sign(&adaptor_pk, &signer_sk, message, rng).unwrap();
228 | assert!(::verify(
229 | &pre_sig,
230 | &adaptor_pk,
231 | &signer_pk,
232 | message
233 | )
234 | .is_ok());
235 |
236 | // adapt with invalid secret key
237 | let adapted_sig = Scheme::adapt(&pre_sig, &signer_sk).unwrap();
238 | // signature will be invalid, thus it will be rejected when checked by a 3rd party
239 | // s + y
240 | let commitment = Secp256k1::generator() * adapted_sig.prover_response
241 | + signer_pk * adapted_sig.verifier_challenge;
242 |
243 | let challenge =
244 | hash_challenge::(&commitment.into_affine(), &signer_pk, message)
245 | .unwrap();
246 |
247 | assert_ne!(challenge, adapted_sig.verifier_challenge);
248 |
249 | // extract invalid adaptor secret key
250 | assert!(Scheme::extract(&pre_sig, &adapted_sig, &adaptor_pk).is_err());
251 | }
252 | }
253 |
--------------------------------------------------------------------------------
/src/commit/kzg.rs:
--------------------------------------------------------------------------------
1 | // We need to commit to G2 as well, which arkworks' kzg10 implementation doesn't allow
2 | use ark_ec::pairing::Pairing;
3 | use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM as Msm};
4 | use ark_ff::PrimeField;
5 | use ark_poly::univariate::DensePolynomial;
6 | use ark_poly::{EvaluationDomain, GeneralEvaluationDomain};
7 | use ark_poly_commit::DenseUVPolynomial;
8 | use ark_std::marker::PhantomData;
9 | use ark_std::rand::Rng;
10 | use ark_std::{One, UniformRand, Zero};
11 |
12 | pub struct Powers {
13 | pub g1: Vec,
14 | pub g2: Vec,
15 | }
16 |
17 | impl Powers {
18 | pub fn unsafe_setup(tau: C::ScalarField, range: usize) -> Self {
19 | let mut g1 = Vec::new();
20 | let mut g2 = Vec::new();
21 | let mut exponent = C::ScalarField::one();
22 | for _ in 1..=range {
23 | g1.push((::generator() * exponent).into_affine());
24 | g2.push((::generator() * exponent).into_affine());
25 | exponent *= tau;
26 | }
27 | Self { g1, g2 }
28 | }
29 |
30 | pub fn unsafe_setup_eip_4844(tau: C::ScalarField, range: usize) -> Self {
31 | let mut g1 = Vec::new();
32 | let mut g2 = Vec::new();
33 | let domain = GeneralEvaluationDomain::new(range).unwrap();
34 | let lagrange_evaluations = domain.evaluate_all_lagrange_coefficients(tau);
35 | lagrange_evaluations.into_iter().for_each(|exponent| {
36 | g1.push((::generator() * exponent).into_affine());
37 | g2.push((::generator() * exponent).into_affine());
38 | });
39 |
40 | Self { g1, g2 }
41 | }
42 |
43 | pub fn commit_scalars_g1(&self, scalars: &[C::ScalarField]) -> C::G1 {
44 | Msm::msm_unchecked(&self.g1[0..scalars.len()], scalars)
45 | }
46 |
47 | pub fn commit_scalars_g2(&self, scalars: &[C::ScalarField]) -> C::G2 {
48 | Msm::msm_unchecked(&self.g2[0..scalars.len()], scalars)
49 | }
50 |
51 | pub fn commit_g1>(
52 | &self,
53 | poly: &P,
54 | ) -> C::G1 {
55 | self.commit_scalars_g1(poly.coeffs())
56 | }
57 |
58 | pub fn commit_g2>(
59 | &self,
60 | poly: &P,
61 | ) -> C::G2 {
62 | self.commit_scalars_g2(poly.coeffs())
63 | }
64 |
65 | pub fn g1_tau(&self) -> C::G1Affine {
66 | self.g1[1]
67 | }
68 |
69 | pub fn g2_tau(&self) -> C::G2Affine {
70 | self.g2[1]
71 | }
72 |
73 | pub fn g2_tau_squared(&self) -> C::G2Affine {
74 | self.g2[2]
75 | }
76 | }
77 |
78 | pub struct Kzg(PhantomData);
79 |
80 | impl Kzg {
81 | pub fn witness(
82 | poly: &DensePolynomial,
83 | point: C::ScalarField,
84 | ) -> DensePolynomial {
85 | let divisor = DensePolynomial::from_coefficients_slice(&[-point, C::ScalarField::one()]);
86 | poly / &divisor
87 | }
88 |
89 | pub fn aggregate_witness(
90 | polys: &[DensePolynomial],
91 | point: C::ScalarField,
92 | challenge: C::ScalarField,
93 | ) -> DensePolynomial {
94 | let aggregated = aggregate_polys(polys, challenge);
95 | Self::witness(&aggregated, point)
96 | }
97 |
98 | pub fn proof(
99 | poly: &DensePolynomial,
100 | point: C::ScalarField,
101 | value: C::ScalarField,
102 | powers: &Powers,
103 | ) -> C::G1Affine {
104 | let numerator = poly + &DensePolynomial::from_coefficients_slice(&[-value]);
105 | let quotient = Self::witness(&numerator, point);
106 | powers.commit_g1("ient).into()
107 | }
108 |
109 | pub fn verify_scalar(
110 | proof: C::G1Affine,
111 | commitment: C::G1Affine,
112 | point: C::ScalarField,
113 | value: C::ScalarField,
114 | powers: &Powers,
115 | ) -> bool {
116 | let point_g2 = C::G2Affine::generator() * point;
117 | let value_g1 = C::G1Affine::generator() * value;
118 | Self::verify(proof, commitment, point_g2, value_g1, powers)
119 | }
120 |
121 | pub fn verify(
122 | proof: C::G1Affine,
123 | commitment: C::G1Affine,
124 | point: C::G2,
125 | value: C::G1,
126 | powers: &Powers,
127 | ) -> bool {
128 | // com / g^y
129 | let com_over_g_value = commitment.into_group() - value;
130 | // g^{tau} / g^x
131 | let g_tau_over_g_point = powers.g2_tau().into_group() - point;
132 |
133 | Self::pairing_check(com_over_g_value, proof.into_group(), g_tau_over_g_point)
134 | }
135 |
136 | pub fn pairing_check(lhs_g1: C::G1, rhs_g1: C::G1, rhs_g2: C::G2) -> bool {
137 | let lhs = C::pairing(lhs_g1, C::G2Affine::generator());
138 | let rhs = C::pairing(rhs_g1, rhs_g2);
139 | lhs == rhs
140 | }
141 |
142 | pub fn batch_verify(
143 | proofs: &[C::G1Affine],
144 | commitments: &[C::G1Affine],
145 | points: &[C::ScalarField],
146 | values: &[C::ScalarField],
147 | powers: &Powers,
148 | rng: &mut R,
149 | ) -> bool {
150 | // NOTE copied (and slightly modified) from
151 | // https://docs.rs/ark-poly-commit/latest/src/ark_poly_commit/kzg10/mod.rs.html#334-353
152 | // because we need a more flexible KZG implementation
153 | let mut total_c = ::zero();
154 | let mut total_w = ::zero();
155 |
156 | let mut randomizer = C::ScalarField::one();
157 | // Instead of multiplying g and gamma_g in each turn, we simply accumulate
158 | // their coefficients and perform a final multiplication at the end.
159 | let mut g_multiplier = C::ScalarField::zero();
160 | let gamma_g_multiplier = C::ScalarField::zero();
161 | for (((c, &z), v), &w) in commitments.iter().zip(points).zip(values).zip(proofs) {
162 | let mut temp = w * z;
163 | temp += c;
164 | let c = temp;
165 | g_multiplier += &(randomizer * v);
166 | total_c += c * randomizer;
167 | total_w += w * randomizer;
168 | // We don't need to sample randomizers from the full field,
169 | // only from 128-bit strings.
170 | randomizer = u128::rand(rng).into();
171 | }
172 | total_c -= C::G1Affine::generator() * g_multiplier;
173 | total_c -= powers.g1_tau() * gamma_g_multiplier;
174 |
175 | let affine_points = C::G1::normalize_batch(&[-total_w, total_c]);
176 | let (total_w, total_c) = (affine_points[0], affine_points[1]);
177 |
178 | C::multi_pairing(
179 | [total_w, total_c],
180 | [powers.g2_tau(), C::G2Affine::generator()],
181 | )
182 | .0
183 | .is_one()
184 | }
185 | }
186 |
187 | pub fn aggregate_polys(values: &[DensePolynomial], by: S) -> DensePolynomial {
188 | let mut acc = S::one();
189 | let mut result = DensePolynomial::zero();
190 |
191 | for value in values {
192 | let tmp = value * &DensePolynomial { coeffs: vec![acc] };
193 | result += &tmp;
194 | acc *= by;
195 | }
196 |
197 | result
198 | }
199 |
200 | #[cfg(test)]
201 | mod test {
202 | use super::*;
203 | use ark_bls12_381::Bls12_381 as BlsCurve;
204 | use ark_ec::CurveGroup;
205 | use ark_poly::univariate::DensePolynomial;
206 | use ark_poly::Polynomial;
207 | use ark_std::{test_rng, One};
208 |
209 | type Scalar = ::ScalarField;
210 | type UniPoly = DensePolynomial;
211 |
212 | #[test]
213 | fn commitment() {
214 | let tau = Scalar::from(2);
215 | // 3 - 2x + x^2
216 | let poly =
217 | UniPoly::from_coefficients_slice(&[Scalar::from(3), -Scalar::from(2), Scalar::one()]);
218 | let poly_tau = poly.evaluate(&tau);
219 | assert_eq!(poly_tau, Scalar::from(3));
220 | // kzg
221 | let powers = Powers::::unsafe_setup(tau, 10);
222 | let com_g1 = powers.commit_g1(&poly);
223 | let com_g2 = powers.commit_g2(&poly);
224 |
225 | assert_eq!(com_g1, (powers.g1[0] * poly_tau).into_affine());
226 | assert_eq!(com_g2, (powers.g2[0] * poly_tau).into_affine());
227 | }
228 |
229 | #[test]
230 | fn batch_verification() {
231 | let rng = &mut test_rng();
232 | for _ in 0..10 {
233 | let mut degree = 0;
234 | while degree <= 1 {
235 | degree = usize::rand(rng) % 20;
236 | }
237 |
238 | let tau = Scalar::rand(rng);
239 | let powers = Powers::::unsafe_setup(tau, degree + 1);
240 |
241 | let mut comms = Vec::new();
242 | let mut values = Vec::new();
243 | let mut points = Vec::new();
244 | let mut proofs = Vec::new();
245 | for _ in 0..10 {
246 | let poly = UniPoly::rand(degree, rng);
247 | let comm = powers.commit_g1(&poly).into_affine();
248 | let point = Scalar::rand(rng);
249 | let value = poly.evaluate(&point);
250 | let proof = Kzg::proof(&poly, point, value, &powers);
251 | assert!(Kzg::verify_scalar(proof, comm, point, value, &powers));
252 |
253 | comms.push(comm);
254 | values.push(value);
255 | points.push(point);
256 | proofs.push(proof);
257 | }
258 | assert!(Kzg::batch_verify(
259 | &proofs, &comms, &points, &values, &powers, rng
260 | ));
261 | }
262 | }
263 |
264 | #[test]
265 | fn commitment_equality() {
266 | let rng = &mut test_rng();
267 | let degree: usize = 16;
268 | let domain = GeneralEvaluationDomain::new(degree).unwrap();
269 | let tau = Scalar::rand(rng);
270 | let powers = Powers::::unsafe_setup(tau, degree);
271 | let powers_eip = Powers::::unsafe_setup_eip_4844(tau, degree);
272 |
273 | let coeffs = (0..degree).map(|_| Scalar::rand(rng)).collect();
274 | let poly = UniPoly { coeffs };
275 |
276 | let evals = poly.evaluate_over_domain_by_ref(domain);
277 | let com_p = powers.commit_g1(&poly);
278 | let com_p_eip = powers_eip.commit_scalars_g1(&evals.evals);
279 |
280 | assert_eq!(com_p, com_p_eip);
281 | }
282 | }
283 |
--------------------------------------------------------------------------------
/src/commit/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod kzg;
2 |
--------------------------------------------------------------------------------
/src/dleq.rs:
--------------------------------------------------------------------------------
1 | use crate::hash::Hasher;
2 | use ark_ec::CurveGroup;
3 | use ark_ff::PrimeField;
4 | use ark_std::marker::PhantomData;
5 | use ark_std::rand::Rng;
6 | use ark_std::UniformRand;
7 | use digest::Digest;
8 |
9 | pub struct Proof {
10 | pub challenge: C::ScalarField,
11 | pub claim: C::ScalarField,
12 | _digest: PhantomData,
13 | }
14 |
15 | impl Proof
16 | where
17 | C: CurveGroup,
18 | D: Digest,
19 | {
20 | pub fn new(secret: &C::ScalarField, g1: C::Affine, g2: C::Affine, rng: &mut R) -> Self {
21 | let rand = C::ScalarField::rand(rng);
22 | let k1 = g1 * rand;
23 | let k2 = g2 * rand;
24 | let h1 = g1 * secret;
25 | let h2 = g2 * secret;
26 |
27 | let mut hasher = Hasher::::new();
28 | hasher.update(&k1);
29 | hasher.update(&k2);
30 | hasher.update(&h1);
31 | hasher.update(&h2);
32 | let hash_output = hasher.finalize();
33 |
34 | let challenge = C::ScalarField::from_le_bytes_mod_order(&hash_output);
35 | let claim = rand - challenge * secret;
36 |
37 | Self {
38 | challenge,
39 | claim,
40 | _digest: PhantomData,
41 | }
42 | }
43 |
44 | pub fn verify(&self, g1: C::Affine, h1: C, g2: C::Affine, h2: C) -> bool {
45 | let k1 = g1 * self.claim + h1 * self.challenge;
46 | let k2 = g2 * self.claim + h2 * self.challenge;
47 |
48 | let mut hasher = Hasher::::new();
49 | hasher.update(&k1);
50 | hasher.update(&k2);
51 | hasher.update(&h1);
52 | hasher.update(&h2);
53 | let hash_output = hasher.finalize();
54 |
55 | let challenge = C::ScalarField::from_le_bytes_mod_order(&hash_output);
56 |
57 | challenge == self.challenge
58 | }
59 | }
60 |
61 | #[cfg(test)]
62 | mod test {
63 | use super::*;
64 | use crate::tests::{G1Affine, Scalar, TestCurve, TestHash};
65 | use ark_ec::pairing::Pairing;
66 | use ark_ec::{AffineRepr, CurveGroup};
67 | use ark_std::{test_rng, UniformRand};
68 |
69 | type DleqProof = Proof<::G1, TestHash>;
70 |
71 | #[test]
72 | fn completeness() {
73 | let rng = &mut test_rng();
74 |
75 | let g1 = G1Affine::generator();
76 | let g2 = (G1Affine::generator() * Scalar::rand(rng)).into_affine();
77 |
78 | let secret = Scalar::rand(rng);
79 |
80 | let h1 = g1 * secret;
81 | let h2 = g2 * secret;
82 |
83 | let proof = DleqProof::new(&secret, g1, g2, rng);
84 |
85 | assert!(proof.verify(g1, h1, g2, h2));
86 | }
87 |
88 | #[test]
89 | fn soundness() {
90 | let rng = &mut test_rng();
91 |
92 | let g1 = G1Affine::generator();
93 | let g2 = (G1Affine::generator() * Scalar::rand(rng)).into_affine();
94 |
95 | let secret = Scalar::rand(rng);
96 |
97 | let h1 = g1 * secret;
98 | let h2 = g2 * secret;
99 |
100 | // invalid secret
101 | let proof = DleqProof::new(&(secret * Scalar::from(2)), g1, g2, rng);
102 | assert!(!proof.verify(g1, h1, g2, h2));
103 |
104 | // invalid point
105 | let proof = DleqProof::new(&secret, g1, g2, rng);
106 | assert!(!proof.verify(g1, h1, g1, h1));
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/encrypt/elgamal/mod.rs:
--------------------------------------------------------------------------------
1 | mod split_scalar;
2 | mod utils;
3 |
4 | pub use split_scalar::SplitScalar;
5 | use utils::shift_scalar;
6 |
7 | use super::EncryptionEngine;
8 | use ark_ec::{AffineRepr, CurveGroup};
9 | use ark_std::marker::PhantomData;
10 | use ark_std::ops::{Add, Mul};
11 | use ark_std::rand::Rng;
12 | use ark_std::{One, UniformRand, Zero};
13 |
14 | pub const MAX_BITS: usize = 32;
15 |
16 | pub struct ExponentialElgamal(pub PhantomData);
17 |
18 | /// Exponential Elgamal encryption scheme ciphertext.
19 | ///
20 | /// It contains `c1 = g^y` and `c2 = g^m * h^y` where `g` is a group generator, `h = g^x` is the
21 | /// public encryption key computed from the secret `x` key, `y` is some random scalar and `m` is
22 | /// the message to be encrypted.
23 | #[derive(Clone, Copy, Debug, Eq, PartialEq)]
24 | pub struct Cipher([C::Affine; 2]);
25 |
26 | impl Default for Cipher {
27 | fn default() -> Self {
28 | Self::zero()
29 | }
30 | }
31 |
32 | impl Zero for Cipher {
33 | fn zero() -> Self {
34 | Self([C::Affine::zero(); 2])
35 | }
36 |
37 | fn is_zero(&self) -> bool {
38 | self.c0().is_zero() && self.c1().is_zero()
39 | }
40 | }
41 |
42 | impl Cipher {
43 | pub fn c0(&self) -> C::Affine {
44 | self.0[0]
45 | }
46 |
47 | pub fn c1(&self) -> C::Affine {
48 | self.0[1]
49 | }
50 |
51 | pub fn check_encrypted_sum(&self, ciphers: &[Self]) -> bool {
52 | let ciphers_sum = ciphers
53 | .iter()
54 | .enumerate()
55 | .fold(Self::zero(), |acc, (i, c)| {
56 | acc + *c * shift_scalar(&C::ScalarField::one(), MAX_BITS * i)
57 | });
58 | ciphers_sum == *self
59 | }
60 | }
61 |
62 | impl Add for Cipher {
63 | type Output = Self;
64 | fn add(self, rhs: Self) -> Self::Output {
65 | Self([
66 | (self.c0() + rhs.c0()).into_affine(),
67 | (self.c1() + rhs.c1()).into_affine(),
68 | ])
69 | }
70 | }
71 |
72 | impl Mul for Cipher {
73 | type Output = Self;
74 | fn mul(self, rhs: C::ScalarField) -> Self::Output {
75 | Self([
76 | (self.c0() * rhs).into_affine(),
77 | (self.c1() * rhs).into_affine(),
78 | ])
79 | }
80 | }
81 |
82 | impl EncryptionEngine for ExponentialElgamal {
83 | type EncryptionKey = C::Affine;
84 | type DecryptionKey = C::ScalarField;
85 | type Cipher = Cipher;
86 | type PlainText = C::ScalarField;
87 |
88 | fn encrypt(
89 | data: &Self::PlainText,
90 | key: &Self::EncryptionKey,
91 | rng: &mut R,
92 | ) -> Self::Cipher {
93 | let random_nonce = C::ScalarField::rand(rng);
94 | Self::encrypt_with_randomness(data, key, &random_nonce)
95 | }
96 |
97 | fn encrypt_with_randomness(
98 | data: &Self::PlainText,
99 | key: &Self::EncryptionKey,
100 | randomness: &Self::PlainText,
101 | ) -> Self::Cipher {
102 | // h^y
103 | let shared_secret = *key * randomness;
104 | // g^y
105 | let c1 = ::generator() * randomness;
106 | // g^m * h^y
107 | let c2 = ::generator() * data + shared_secret;
108 | Cipher([c1.into_affine(), c2.into_affine()])
109 | }
110 |
111 | fn decrypt(cipher: Self::Cipher, key: &Self::DecryptionKey) -> Self::PlainText {
112 | let decrypted_exp = Self::decrypt_exp(cipher, key);
113 | Self::brute_force(decrypted_exp)
114 | }
115 | }
116 |
117 | impl ExponentialElgamal {
118 | pub fn decrypt_exp(cipher: Cipher, key: &C::ScalarField) -> C::Affine {
119 | let shared_secret = (cipher.c0() * key).into_affine();
120 | // AffineRepr has to be converted into a Group element in order to perform subtraction but
121 | // I believe this is optimized away in release mode
122 | (cipher.c1().into() - shared_secret.into()).into_affine()
123 | }
124 |
125 | pub fn brute_force(decrypted: C::Affine) -> C::ScalarField {
126 | let max = C::ScalarField::from(u32::MAX);
127 | let mut exponent = C::ScalarField::zero();
128 |
129 | while (::generator() * exponent).into_affine() != decrypted
130 | && exponent < max
131 | {
132 | exponent += C::ScalarField::one();
133 | }
134 | exponent
135 | }
136 | }
137 |
138 | #[cfg(test)]
139 | mod test {
140 | use super::*;
141 | use crate::tests::{G1Affine, Scalar, TestCurve, N};
142 | use ark_ec::pairing::Pairing;
143 | use ark_ec::{AffineRepr, CurveGroup};
144 | use ark_std::{test_rng, UniformRand};
145 |
146 | type Elgamal = ExponentialElgamal<::G1>;
147 |
148 | #[test]
149 | fn exponential_elgamal() {
150 | let rng = &mut test_rng();
151 | let decryption_key = Scalar::rand(rng);
152 | let encryption_key = (G1Affine::generator() * decryption_key).into_affine();
153 |
154 | // completeness
155 | let data = Scalar::from(12342526u32);
156 | let encrypted = Elgamal::encrypt(&data, &encryption_key, rng);
157 | let decrypted = Elgamal::decrypt_exp(encrypted, &decryption_key);
158 | assert_eq!(decrypted, (G1Affine::generator() * data).into_affine());
159 | // soundness
160 | let data = Scalar::from(12342526u32);
161 | let invalid_decryption_key = decryption_key + Scalar::from(123u32);
162 | let encrypted = Elgamal::encrypt(&data, &encryption_key, rng);
163 | let decrypted = Elgamal::decrypt_exp(encrypted, &invalid_decryption_key);
164 | assert_ne!(decrypted, (G1Affine::generator() * data).into_affine());
165 |
166 | // with brute force check
167 | let data = Scalar::from(12u32);
168 | let encrypted = Elgamal::encrypt(&data, &encryption_key, rng);
169 | let decrypted = Elgamal::decrypt(encrypted, &decryption_key);
170 | assert_eq!(decrypted, data);
171 | }
172 |
173 | #[test]
174 | fn elgamal_homomorphism() {
175 | let a = Scalar::from(16u8);
176 | let b = Scalar::from(10u8);
177 | let c = Scalar::from(100u8);
178 | let ra = Scalar::from(2u8);
179 | let rb = Scalar::from(20u8);
180 | let rc = Scalar::from(200u8);
181 |
182 | let decryption_key = Scalar::from(1234567);
183 | let encryption_key = (G1Affine::generator() * decryption_key).into_affine();
184 |
185 | let ea = Elgamal::encrypt_with_randomness(&a, &encryption_key, &ra);
186 | let eb = Elgamal::encrypt_with_randomness(&b, &encryption_key, &rb);
187 | let ec = Elgamal::encrypt_with_randomness(&c, &encryption_key, &rc);
188 |
189 | let sum = a + b + c;
190 | let rsum = ra + rb + rc;
191 | let esum = ea + eb + ec;
192 |
193 | assert_eq!(esum.c0(), G1Affine::generator() * rsum);
194 | assert_eq!(
195 | esum.c1(),
196 | G1Affine::generator() * sum + encryption_key * rsum
197 | );
198 |
199 | let ma = Scalar::from(3u8);
200 | let mb = Scalar::from(4u8);
201 | let mc = Scalar::from(5u8);
202 |
203 | let sum = ma * a + mb * b + mc * c;
204 | let rsum = ma * ra + mb * rb + mc * rc;
205 | let esum = ea * ma + eb * mb + ec * mc;
206 |
207 | assert_eq!(esum.c0(), G1Affine::generator() * rsum);
208 | assert_eq!(
209 | esum.c1(),
210 | G1Affine::generator() * sum + encryption_key * rsum
211 | );
212 | }
213 |
214 | #[test]
215 | fn split_encryption() {
216 | let rng = &mut test_rng();
217 | let scalar = Scalar::rand(rng);
218 | let split_scalar = SplitScalar::<{ N }, Scalar>::from(scalar);
219 | let secret = Scalar::rand(rng);
220 | let encryption_key = (G1Affine::generator() * secret).into_affine();
221 |
222 | let (ciphers, randomness) = split_scalar.encrypt::(&encryption_key, rng);
223 |
224 | let cipher = Elgamal::encrypt_with_randomness(&scalar, &encryption_key, &randomness);
225 |
226 | assert!(cipher.check_encrypted_sum(&ciphers));
227 | }
228 | }
229 |
--------------------------------------------------------------------------------
/src/encrypt/elgamal/split_scalar.rs:
--------------------------------------------------------------------------------
1 | use super::utils::shift_scalar;
2 | use super::MAX_BITS;
3 | use crate::encrypt::EncryptionEngine;
4 | use ark_ff::fields::PrimeField;
5 | use ark_ff::BigInteger;
6 | use ark_std::rand::Rng;
7 | #[cfg(feature = "parallel")]
8 | use rayon::prelude::*;
9 |
10 | #[derive(Clone, Copy, Debug)]
11 | pub struct SplitScalar([S; N]);
12 |
13 | impl SplitScalar {
14 | pub fn new(inner: [S; N]) -> Self {
15 | Self(inner)
16 | }
17 |
18 | pub fn reconstruct(&self) -> S {
19 | sum_shifted(self.splits())
20 | }
21 |
22 | pub fn encrypt(
23 | self,
24 | encryption_key: &E::EncryptionKey,
25 | rng: &mut R,
26 | ) -> ([E::Cipher; N], S)
27 | where
28 | E: EncryptionEngine,
29 | E::Cipher: ark_std::fmt::Debug,
30 | R: Rng,
31 | {
32 | let rands: Vec = (0..N).map(|_| S::rand(rng)).collect();
33 | let ciphers: Vec = self
34 | .0
35 | .iter()
36 | .zip(&rands)
37 | .map(|(s, r)| E::encrypt_with_randomness(s, encryption_key, r))
38 | .collect();
39 |
40 | let shifted_rand_sum = sum_shifted(&rands);
41 |
42 | // NOTE unwrap is fine because ciphers.len() is always N
43 | (ciphers.try_into().unwrap(), shifted_rand_sum)
44 | }
45 |
46 | pub fn splits(&self) -> &[S; N] {
47 | &self.0
48 | }
49 | }
50 |
51 | #[cfg(not(feature = "parallel"))]
52 | fn sum_shifted(splits: &[S]) -> S {
53 | splits
54 | .iter()
55 | .enumerate()
56 | .fold(S::zero(), |acc, (i, s)| acc + shift_scalar(s, MAX_BITS * i))
57 | }
58 |
59 | #[cfg(feature = "parallel")]
60 | fn sum_shifted(splits: &[S]) -> S {
61 | splits
62 | .par_iter()
63 | .enumerate()
64 | .fold(
65 | || S::zero(),
66 | |acc, (i, s)| acc + shift_scalar(s, MAX_BITS * i),
67 | )
68 | .sum()
69 | }
70 |
71 | impl From for SplitScalar {
72 | fn from(scalar: S) -> Self {
73 | let scalar_le_bytes = scalar.into_bigint().to_bits_le();
74 | let mut output = [S::zero(); N];
75 |
76 | for (i, chunk) in scalar_le_bytes.chunks(MAX_BITS).enumerate() {
77 | let split = S::from_bigint(::from_bits_le(chunk))
78 | .expect("should not fail");
79 | output[i] = split;
80 | }
81 | Self::new(output)
82 | }
83 | }
84 |
85 | #[cfg(test)]
86 | mod test {
87 | use super::*;
88 | use crate::tests::{G1Affine, Scalar, TestCurve, N};
89 | use ark_ec::pairing::Pairing;
90 | use ark_ec::{AffineRepr, CurveGroup};
91 | use ark_std::{test_rng, UniformRand, Zero};
92 |
93 | type Elgamal = super::super::ExponentialElgamal<::G1>;
94 |
95 | #[test]
96 | fn scalar_splitting() {
97 | let scalar = Scalar::zero();
98 | let split_scalar = SplitScalar::<{ N }, Scalar>::from(scalar);
99 | let reconstructed_scalar = split_scalar.reconstruct();
100 | assert_eq!(scalar, reconstructed_scalar);
101 |
102 | let rng = &mut test_rng();
103 | let max_scalar = Scalar::from(u32::MAX);
104 | for _ in 0..10 {
105 | let scalar = Scalar::rand(rng);
106 | let split_scalar = SplitScalar::<{ N }, Scalar>::from(scalar);
107 | for split in split_scalar.splits() {
108 | assert!(split <= &max_scalar);
109 | }
110 | let reconstructed_scalar = split_scalar.reconstruct();
111 | assert_eq!(scalar, reconstructed_scalar);
112 | }
113 | }
114 |
115 | #[test]
116 | fn encryption() {
117 | let rng = &mut test_rng();
118 | let encryption_pk = (G1Affine::generator() * Scalar::rand(rng)).into_affine();
119 | let scalar = Scalar::rand(rng);
120 | let split_scalar = SplitScalar::<{ N }, Scalar>::from(scalar);
121 |
122 | let (short_ciphers, elgamal_r) = split_scalar.encrypt::(&encryption_pk, rng);
123 | let long_cipher = ::encrypt_with_randomness(
124 | &scalar,
125 | &encryption_pk,
126 | &elgamal_r,
127 | );
128 |
129 | assert!(long_cipher.check_encrypted_sum(&short_ciphers));
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/src/encrypt/elgamal/utils.rs:
--------------------------------------------------------------------------------
1 | use ark_ff::fields::PrimeField;
2 | use ark_ff::BigInteger;
3 |
4 | pub fn shift_scalar(scalar: &S, by: usize) -> S {
5 | let mut bigint = S::one().into_bigint();
6 | bigint.muln(by as u32);
7 | *scalar * S::from_bigint(bigint).unwrap()
8 | }
9 |
10 | #[cfg(test)]
11 | mod test {
12 | use super::*;
13 | use ark_bls12_381::Fr;
14 | use ark_std::{One, Zero};
15 |
16 | #[test]
17 | fn scalar_shifting() {
18 | let scalar = Fr::zero();
19 | assert_eq!(shift_scalar(&scalar, 32), Fr::zero());
20 |
21 | let scalar = Fr::one();
22 | assert_eq!(
23 | shift_scalar(&scalar, 32),
24 | Fr::from(u64::from(u32::MAX) + 1u64)
25 | );
26 |
27 | // shifting with overflow
28 | // according to the docs, overflow is
29 | // ignored
30 | let scalar = Fr::one();
31 | assert_eq!(shift_scalar(&scalar, u32::MAX as usize), Fr::zero());
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/encrypt/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod elgamal;
2 |
3 | use ark_std::rand::Rng;
4 |
5 | pub trait EncryptionEngine {
6 | type EncryptionKey;
7 | type DecryptionKey;
8 | type Cipher;
9 | type PlainText;
10 | fn encrypt(
11 | data: &Self::PlainText,
12 | key: &Self::EncryptionKey,
13 | rng: &mut R,
14 | ) -> Self::Cipher;
15 | fn encrypt_with_randomness(
16 | data: &Self::PlainText,
17 | key: &Self::EncryptionKey,
18 | randomness: &Self::PlainText,
19 | ) -> Self::Cipher;
20 | fn decrypt(cipher: Self::Cipher, key: &Self::DecryptionKey) -> Self::PlainText;
21 | }
22 |
--------------------------------------------------------------------------------
/src/hash.rs:
--------------------------------------------------------------------------------
1 | use ark_ff::PrimeField;
2 | use ark_serialize::CanonicalSerialize;
3 | use ark_std::marker::PhantomData;
4 | use digest::{Digest, Output};
5 |
6 | #[derive(Clone, Debug)]
7 | pub struct Hasher {
8 | data: Vec,
9 | _digest: PhantomData,
10 | }
11 |
12 | impl Default for Hasher {
13 | fn default() -> Self {
14 | Self {
15 | data: Vec::new(),
16 | _digest: PhantomData,
17 | }
18 | }
19 | }
20 |
21 | impl Hasher {
22 | pub fn new() -> Self {
23 | Self::default()
24 | }
25 |
26 | pub fn update(&mut self, input: &T) {
27 | input
28 | .serialize_compressed(&mut self.data)
29 | .expect("should not fail");
30 | }
31 |
32 | pub fn finalize(self) -> Output {
33 | D::digest(self.data)
34 | }
35 |
36 | pub fn next_scalar(&mut self, label: &[u8]) -> S {
37 | self.data.extend_from_slice(label);
38 | let output = D::digest(&self.data);
39 | S::from_le_bytes_mod_order(&output)
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | #![deny(clippy::all)]
2 | #![deny(clippy::dbg_macro)]
3 | #![deny(unused_crate_dependencies)]
4 |
5 | pub mod adaptor_sig;
6 | pub mod commit;
7 | pub mod dleq;
8 | pub mod encrypt;
9 | pub mod hash;
10 | pub mod range_proof;
11 | #[cfg(test)]
12 | mod tests;
13 | pub mod veck;
14 |
15 | use thiserror::Error;
16 |
17 | #[derive(Error, Debug, PartialEq)]
18 | pub enum Error {
19 | #[error("couldn't generate valid FFT domain of size {0}")]
20 | InvalidFftDomain(usize),
21 | #[error(transparent)]
22 | RangeProof(#[from] range_proof::Error),
23 | #[error(transparent)]
24 | KzgElgamalProofError(#[from] veck::kzg::elgamal::Error),
25 | #[error(transparent)]
26 | KzgPaillierProofError(#[from] veck::kzg::paillier::Error),
27 | }
28 |
--------------------------------------------------------------------------------
/src/range_proof/mod.rs:
--------------------------------------------------------------------------------
1 | //! This crate contains a proof-of-concept implementation of the
2 | //! [Boneh-Fisch-Gabizon-Williamson](https://hackmd.io/@dabo/B1U4kx8XI) range proof.
3 | //!
4 | //! The protocol relies on KZG commitments, thus it fits our KZG-based protocols perfectly. Further
5 | //! discussion of the proof can be found
6 | //! [here](https://decentralizedthoughts.github.io/2020-03-03-range-proofs-from-polynomial-commitments-reexplained/).
7 | //!
8 | //! This implementation is a modernized/updated version of the code found
9 | //! [here](https://github.com/roynalnaruto/range_proof).
10 | mod poly;
11 | mod utils;
12 |
13 | use crate::commit::kzg::{Kzg, Powers};
14 | use crate::hash::Hasher;
15 | use crate::Error as CrateError;
16 | use ark_ec::pairing::Pairing;
17 | use ark_ec::{AffineRepr, CurveGroup};
18 | use ark_poly::{EvaluationDomain, GeneralEvaluationDomain, Polynomial};
19 | use ark_std::marker::PhantomData;
20 | use ark_std::rand::Rng;
21 | use ark_std::UniformRand;
22 | use digest::Digest;
23 | use thiserror::Error as ErrorT;
24 |
25 | #[derive(ErrorT, Debug, PartialEq)]
26 | pub enum Error {
27 | #[error("aggregated witness pairings are not equal")]
28 | AggregateWitnessCheckFailed,
29 | #[error("shifted witness pairings are not equal")]
30 | ShiftedWitnessCheckFailed,
31 | #[error("input value is greater than the upper range bound")]
32 | InputOutOfBounds,
33 | #[error("polynomial is nonzero")]
34 | ExpectedZeroPolynomial,
35 | }
36 |
37 | const PROOF_DOMAIN_SEP: &[u8] = b"fde range proof";
38 |
39 | #[derive(Clone, Copy, Debug)]
40 | pub struct Evaluations {
41 | pub g: S,
42 | pub g_omega: S,
43 | pub w_cap: S,
44 | }
45 |
46 | #[derive(Clone, Copy, Debug)]
47 | pub struct Commitments {
48 | pub f: C::G1Affine,
49 | pub g: C::G1Affine,
50 | pub q: C::G1Affine,
51 | }
52 |
53 | #[derive(Clone, Copy, Debug)]
54 | pub struct Proofs {
55 | pub aggregate: C::G1Affine,
56 | pub shifted: C::G1Affine,
57 | }
58 |
59 | #[derive(Clone, Copy, Debug)]
60 | pub struct RangeProof {
61 | pub evaluations: Evaluations,
62 | pub commitments: Commitments,
63 | pub proofs: Proofs,
64 | _digest: PhantomData,
65 | }
66 |
67 | impl RangeProof {
68 | // prove 0 <= z < 2^n
69 | pub fn new(
70 | z: C::ScalarField,
71 | n: usize,
72 | powers: &Powers,
73 | rng: &mut R,
74 | ) -> Result {
75 | let domain = GeneralEvaluationDomain::::new(n)
76 | .ok_or(CrateError::InvalidFftDomain(n))?;
77 | let domain_2n = GeneralEvaluationDomain::::new(2 * n)
78 | .ok_or(CrateError::InvalidFftDomain(2 * n))?;
79 |
80 | // random scalars
81 | let r = C::ScalarField::rand(rng);
82 | let alpha = C::ScalarField::rand(rng);
83 | let beta = C::ScalarField::rand(rng);
84 |
85 | // compute f and g polynomials and their commitments
86 | let f_poly = poly::f(&domain, z, r);
87 | let g_poly = poly::g(&domain, z, alpha, beta);
88 | let f_commitment = powers.commit_g1(&f_poly);
89 | let g_commitment = powers.commit_g1(&g_poly);
90 |
91 | // compute challenges
92 | let mut hasher = Hasher::::new();
93 | hasher.update(&PROOF_DOMAIN_SEP);
94 | hasher.update(&n.to_le_bytes());
95 | hasher.update(&domain.group_gen());
96 | hasher.update(&f_commitment);
97 | hasher.update(&g_commitment);
98 |
99 | let tau = hasher.next_scalar(b"tau");
100 | let rho = hasher.next_scalar(b"rho");
101 | let aggregation_challenge = hasher.next_scalar(b"aggregation_challenge");
102 |
103 | // aggregate w1, w2 and w3 to compute quotient polynomial
104 | let (w1_poly, w2_poly) = poly::w1_w2(&domain, &f_poly, &g_poly)?;
105 | let w3_poly = poly::w3(&domain, &domain_2n, &g_poly)?;
106 | let q_poly = poly::quotient(&domain, &w1_poly, &w2_poly, &w3_poly, tau)?;
107 | let q_commitment = powers.commit_g1(&q_poly);
108 |
109 | let rho_omega = rho * domain.group_gen();
110 | // evaluate g at rho
111 | let g_eval = g_poly.evaluate(&rho);
112 | // evaluate g at `rho * omega`
113 | let g_omega_eval = g_poly.evaluate(&rho_omega);
114 |
115 | // compute evaluation of w_cap at ρ
116 | let w_cap_poly = poly::w_cap(&domain, &f_poly, &q_poly, rho);
117 | let w_cap_eval = w_cap_poly.evaluate(&rho);
118 |
119 | // compute witness for g(X) at ρw
120 | let shifted_witness_poly = Kzg::::witness(&g_poly, rho_omega);
121 | let shifted_proof = powers.commit_g1(&shifted_witness_poly);
122 |
123 | // compute aggregate witness for
124 | // g(X) at ρ, f(X) at ρ, w_cap(X) at ρ
125 | let aggregate_witness_poly =
126 | Kzg::::aggregate_witness(&[g_poly, w_cap_poly], rho, aggregation_challenge);
127 | let aggregate_proof = powers.commit_g1(&aggregate_witness_poly);
128 |
129 | let evaluations = Evaluations {
130 | g: g_eval,
131 | g_omega: g_omega_eval,
132 | w_cap: w_cap_eval,
133 | };
134 |
135 | let commitments = Commitments {
136 | f: f_commitment.into_affine(),
137 | g: g_commitment.into_affine(),
138 | q: q_commitment.into_affine(),
139 | };
140 |
141 | let proofs = Proofs {
142 | aggregate: aggregate_proof.into_affine(),
143 | shifted: shifted_proof.into_affine(),
144 | };
145 |
146 | Ok(Self {
147 | evaluations,
148 | commitments,
149 | proofs,
150 | _digest: PhantomData,
151 | })
152 | }
153 |
154 | pub fn verify(&self, n: usize, powers: &Powers) -> Result<(), CrateError> {
155 | let domain = GeneralEvaluationDomain::::new(n)
156 | .ok_or(CrateError::InvalidFftDomain(n))?;
157 |
158 | let mut hasher = Hasher::::new();
159 | hasher.update(&PROOF_DOMAIN_SEP);
160 | hasher.update(&n.to_le_bytes());
161 | hasher.update(&domain.group_gen());
162 | hasher.update(&self.commitments.f);
163 | hasher.update(&self.commitments.g);
164 |
165 | let tau = hasher.next_scalar(b"tau");
166 | let rho = hasher.next_scalar(b"rho");
167 | let aggregation_challenge: C::ScalarField = hasher.next_scalar(b"aggregation_challenge");
168 |
169 | // calculate w_cap_commitment
170 | let w_cap_commitment =
171 | utils::w_cap::(domain.size(), self.commitments.f, self.commitments.q, rho);
172 |
173 | // calculate w2(ρ) and w3(ρ)
174 | let sum = utils::w1_w2_w3_evals_sum(
175 | &domain,
176 | self.evaluations.g,
177 | self.evaluations.g_omega,
178 | rho,
179 | tau,
180 | );
181 | // calculate w(ρ) that should zero since w(X) is after all a zero polynomial
182 | if sum != self.evaluations.w_cap {
183 | return Err(Error::ExpectedZeroPolynomial.into());
184 | }
185 |
186 | // check aggregate witness commitment
187 | let aggregate_poly_commitment = utils::aggregate(
188 | &[
189 | self.commitments.g.into_group(),
190 | w_cap_commitment.into_group(),
191 | ],
192 | aggregation_challenge,
193 | );
194 | let aggregate_value = utils::aggregate(
195 | &[self.evaluations.g, self.evaluations.w_cap],
196 | aggregation_challenge,
197 | );
198 | let aggregation_kzg_check = Kzg::verify_scalar(
199 | self.proofs.aggregate,
200 | aggregate_poly_commitment.into_affine(),
201 | rho,
202 | aggregate_value,
203 | powers,
204 | );
205 |
206 | // check shifted witness commitment
207 | let rho_omega = rho * domain.group_gen();
208 | let shifted_kzg_check = Kzg::verify_scalar(
209 | self.proofs.shifted,
210 | self.commitments.g,
211 | rho_omega,
212 | self.evaluations.g_omega,
213 | powers,
214 | );
215 |
216 | if !aggregation_kzg_check {
217 | Err(Error::AggregateWitnessCheckFailed.into())
218 | } else if !shifted_kzg_check {
219 | Err(Error::ShiftedWitnessCheckFailed.into())
220 | } else {
221 | Ok(())
222 | }
223 | }
224 | }
225 |
226 | #[cfg(test)]
227 | mod test {
228 | use super::*;
229 | use crate::commit::kzg::Powers;
230 | use crate::tests::{Scalar, TestCurve, TestHash};
231 | use crate::Error as CrateError;
232 | use ark_std::{test_rng, UniformRand};
233 |
234 | const LOG_2_UPPER_BOUND: usize = 8; // 2^8
235 |
236 | #[test]
237 | fn range_proof_success() {
238 | // KZG setup simulation
239 | let rng = &mut test_rng();
240 | let tau = Scalar::rand(rng); // "secret" tau
241 | let powers = Powers::::unsafe_setup(tau, 4 * LOG_2_UPPER_BOUND);
242 |
243 | let z = Scalar::from(100u32);
244 | let proof =
245 | RangeProof::::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap();
246 | assert!(proof.verify(LOG_2_UPPER_BOUND, &powers).is_ok());
247 |
248 | let z = Scalar::from(255u32);
249 | let proof =
250 | RangeProof::::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap();
251 | assert!(proof.verify(LOG_2_UPPER_BOUND, &powers).is_ok());
252 | }
253 |
254 | #[test]
255 | fn range_proof_with_invalid_size_fails() {
256 | // KZG setup simulation
257 | let rng = &mut test_rng();
258 | let tau = Scalar::rand(rng); // "secret" tau
259 | let powers = Powers::::unsafe_setup(tau, 4 * LOG_2_UPPER_BOUND);
260 |
261 | let z = Scalar::from(100u32);
262 | let proof =
263 | RangeProof::::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap();
264 | assert_eq!(
265 | proof.verify(LOG_2_UPPER_BOUND - 1, &powers),
266 | Err(CrateError::RangeProof(Error::ExpectedZeroPolynomial))
267 | );
268 | }
269 |
270 | #[test]
271 | fn range_proof_with_too_large_z_fails_1() {
272 | // KZG setup simulation
273 | let rng = &mut test_rng();
274 | let tau = Scalar::rand(rng); // "secret" tau
275 | let powers = Powers::::unsafe_setup(tau, 4 * LOG_2_UPPER_BOUND);
276 |
277 | let z = Scalar::from(256u32);
278 | assert_eq!(
279 | RangeProof::::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap_err(),
280 | CrateError::RangeProof(Error::ExpectedZeroPolynomial)
281 | );
282 | }
283 |
284 | #[test]
285 | fn range_proof_with_too_large_z_fails_2() {
286 | // KZG setup simulation
287 | let rng = &mut test_rng();
288 | let tau = Scalar::rand(rng); // "secret" tau
289 | let powers = Powers::::unsafe_setup(tau, 4 * LOG_2_UPPER_BOUND);
290 |
291 | let z = Scalar::from(300u32);
292 | assert_eq!(
293 | RangeProof::::new(z, LOG_2_UPPER_BOUND, &powers, rng).unwrap_err(),
294 | CrateError::RangeProof(Error::ExpectedZeroPolynomial)
295 | );
296 | }
297 | }
298 |
--------------------------------------------------------------------------------
/src/range_proof/poly.rs:
--------------------------------------------------------------------------------
1 | use super::Error;
2 | use crate::Error as CrateError;
3 | use ark_ff::{BigInteger, PrimeField};
4 | use ark_poly::univariate::DensePolynomial;
5 | use ark_poly::{DenseUVPolynomial, EvaluationDomain, GeneralEvaluationDomain};
6 | use ark_std::Zero;
7 |
8 | pub fn f(domain: &GeneralEvaluationDomain, z: S, r: S) -> DensePolynomial {
9 | // f is a linear polynomial: f(1) = z
10 | DensePolynomial::from_coefficients_vec(domain.ifft(&[z, r]))
11 | }
12 |
13 | pub fn g(
14 | domain: &GeneralEvaluationDomain,
15 | z: S,
16 | alpha: S,
17 | beta: S,
18 | ) -> DensePolynomial {
19 | // get bits for z -> consider only the first `n` bits
20 | let size = domain.size();
21 | let z_bits = &z.into_bigint().to_bits_le()[0..size];
22 | let mut evaluations: Vec = vec![S::zero(); size];
23 |
24 | // take the first evaluation point, i.e. (n-1)th bit of z
25 | evaluations[size - 1] = S::from(z_bits[size - 1]);
26 |
27 | // for the rest of bits (n-2 .. 0)
28 | // g_i = 2* g_(i+1) + z_i
29 | z_bits
30 | .iter()
31 | .enumerate()
32 | .rev()
33 | .skip(1)
34 | .for_each(|(i, &bit)| {
35 | evaluations[i] = S::from(2u8) * evaluations[i + 1] + S::from(bit as u8);
36 | });
37 |
38 | // compute g
39 | let g_poly = DensePolynomial::from_coefficients_vec(domain.ifft(&evaluations));
40 |
41 | // extended domain
42 | let domain_ext = GeneralEvaluationDomain::::new(size + 1).expect("valid domain");
43 |
44 | // Map the original g_poly to domain(n+1). Add random values alpha and beta as evaluations of g
45 | // at all even indices, g_evals[2k] matches the evaluation at some original root of unity.
46 | // Hence only update two odd indices with alpha and beta this makes g evaluate to the expected
47 | // evaluations at all roots of unity of domain size `n`, but makes is a different polynomial
48 | let mut g_evals = domain_ext.fft(&g_poly);
49 | g_evals[1] = alpha;
50 | g_evals[3] = beta;
51 |
52 | DensePolynomial::from_coefficients_vec(domain_ext.ifft(&g_evals))
53 | }
54 |
55 | pub fn w1_w2(
56 | domain: &GeneralEvaluationDomain,
57 | f_poly: &DensePolynomial,
58 | g_poly: &DensePolynomial,
59 | ) -> Result<(DensePolynomial, DensePolynomial), CrateError> {
60 | let one = S::one();
61 | let w_n_minus_1 = domain
62 | .elements()
63 | .last()
64 | .ok_or(CrateError::InvalidFftDomain(0))?;
65 |
66 | // polynomial: P(x) = x - w^(n-1)
67 | let x_minus_w_n_minus_1_poly = DensePolynomial::from_coefficients_slice(&[-w_n_minus_1, one]);
68 |
69 | // polynomial: P(x) = x^n - 1
70 | let x_n_minus_1_poly = DensePolynomial::from(domain.vanishing_polynomial());
71 |
72 | // polynomial: P(x) = x - 1
73 | let x_minus_1_poly = DensePolynomial::from_coefficients_slice(&[-one, one]);
74 |
75 | let g_minus_f_poly = g_poly - f_poly;
76 | let w1_poly = &(&g_minus_f_poly * &x_n_minus_1_poly) / &x_minus_1_poly;
77 |
78 | // polynomial: P(x) = 1
79 | let one_poly = DensePolynomial::from_coefficients_slice(&[one]);
80 | let one_minus_g_poly = &one_poly - g_poly;
81 | let w2_poly = &(&(g_poly * &one_minus_g_poly) * &x_n_minus_1_poly) / &x_minus_w_n_minus_1_poly;
82 |
83 | Ok((w1_poly, w2_poly))
84 | }
85 |
86 | pub fn w3(
87 | domain: &GeneralEvaluationDomain,
88 | domain_2n: &GeneralEvaluationDomain,
89 | g_poly: &DensePolynomial,
90 | ) -> Result, CrateError> {
91 | // w3: [g(X) - 2g(Xw)] * [1 - g(X) + 2g(Xw)] * [X - w^(n-1)]
92 | // degree of g = n - 1
93 | // degree of w3 = (2n - 1) + (2n - 1) + 1 = 4n - 1
94 | // the new domain can be of size 4n
95 | let domain_4n = GeneralEvaluationDomain::::new(2 * domain_2n.size())
96 | .ok_or(CrateError::InvalidFftDomain(2 * domain_2n.size()))?;
97 |
98 | // find evaluations of g in the new domain
99 | let mut g_evals = domain_4n.fft(g_poly);
100 |
101 | // since we have doubled the domain size, the roots of unity of the new domain will also occur
102 | // among the roots of unity of the original domain. hence, if g(X) <- g_evals[i] then g(Xw) <-
103 | // g_evals[i+4]
104 | g_evals.push(g_evals[0]);
105 | g_evals.push(g_evals[1]);
106 | g_evals.push(g_evals[2]);
107 | g_evals.push(g_evals[3]);
108 |
109 | // calculate evaluations of w3
110 | let w_n_minus_1 = domain
111 | .elements()
112 | .last()
113 | .ok_or(CrateError::InvalidFftDomain(0))?;
114 | let two = S::from(2u8);
115 | let w3_evals: Vec = domain_4n
116 | .elements()
117 | .enumerate()
118 | .map(|(i, x_i)| {
119 | let part_a = g_evals[i] - (two * g_evals[i + 4]);
120 | let part_b = S::one() - g_evals[i] + (two * g_evals[i + 4]);
121 | let part_c = x_i - w_n_minus_1;
122 | part_a * part_b * part_c
123 | })
124 | .collect();
125 |
126 | Ok(DensePolynomial::from_coefficients_vec(
127 | domain_4n.ifft(&w3_evals),
128 | ))
129 | }
130 |
131 | pub fn w_cap(
132 | domain: &GeneralEvaluationDomain,
133 | f_poly: &DensePolynomial,
134 | q_poly: &DensePolynomial,
135 | rho: S,
136 | ) -> DensePolynomial {
137 | let (rho_1, rho_2) = super::utils::rho_relations(domain.size(), rho);
138 | let rho_poly_1 = DensePolynomial::from_coefficients_slice(&[rho_1]);
139 | let rho_poly_2 = DensePolynomial::from_coefficients_slice(&[rho_2]);
140 | &(f_poly * &rho_poly_1) + &(q_poly * &rho_poly_2)
141 | }
142 |
143 | pub fn quotient(
144 | domain: &GeneralEvaluationDomain,
145 | w1_poly: &DensePolynomial,
146 | w2_poly: &DensePolynomial,
147 | w3_poly: &DensePolynomial,
148 | tau: S,
149 | ) -> Result, CrateError> {
150 | // find linear combination of w1, w2, w3
151 | let lc = w1_poly + &(w2_poly * tau) + w3_poly * tau.square();
152 | let (quotient_poly, rem) = lc
153 | .divide_by_vanishing_poly(*domain)
154 | .ok_or(CrateError::InvalidFftDomain(domain.size()))?;
155 | // since the linear combination should also satisfy all roots of unity, q_rem should be a zero
156 | // polynomial
157 | if !rem.is_zero() {
158 | Err(Error::ExpectedZeroPolynomial.into())
159 | } else {
160 | Ok(quotient_poly)
161 | }
162 | }
163 |
164 | #[cfg(test)]
165 | mod test {
166 | use crate::commit::kzg::Powers;
167 | use crate::tests::{Scalar, TestCurve};
168 | use ark_ec::pairing::Pairing;
169 | use ark_ec::CurveGroup;
170 | use ark_ff::{Field, PrimeField};
171 | use ark_poly::univariate::DensePolynomial;
172 | use ark_poly::{DenseUVPolynomial, EvaluationDomain, GeneralEvaluationDomain, Polynomial};
173 | use ark_std::{test_rng, UniformRand};
174 | use ark_std::{One, Zero};
175 |
176 | fn w2_w3_parts(
177 | w2: &DensePolynomial,
178 | w3: &DensePolynomial,
179 | tau: S,
180 | ) -> (DensePolynomial, DensePolynomial) {
181 | (w2 * tau, w3 * tau.square())
182 | }
183 |
184 | fn w1_part(
185 | domain: &GeneralEvaluationDomain,
186 | g_poly: &DensePolynomial,
187 | ) -> DensePolynomial {
188 | let one = S::one();
189 | let divisor = DensePolynomial::::from_coefficients_slice(&[-one, one]);
190 | &g_poly.mul_by_vanishing_poly(*domain) / &divisor
191 | }
192 |
193 | #[test]
194 | fn compute_f_poly_success() {
195 | let rng = &mut test_rng();
196 | let n = 8usize;
197 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
198 | let z = Scalar::from(2u8);
199 | let r = Scalar::from(4u8);
200 | let f_poly = super::f(&domain, z, r);
201 |
202 | let rho = Scalar::rand(rng);
203 |
204 | assert_eq!(f_poly.evaluate(&Scalar::one()), z);
205 | assert_eq!(f_poly.evaluate(&domain.group_gen()), r);
206 | assert_ne!(f_poly.evaluate(&rho), z);
207 | assert_ne!(f_poly.evaluate(&rho), r);
208 | }
209 | #[test]
210 | fn compute_g_poly_success() {
211 | let rng = &mut test_rng();
212 | // n = 8, 2^n = 256, 0 <= z < 2^n degree of polynomial should be (n - 1) it should also
213 | // evaluate to `z` at x = 1
214 | let n = 8usize;
215 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
216 | let z = Scalar::from(100u8);
217 |
218 | let alpha = Scalar::rand(rng);
219 | let beta = Scalar::rand(rng);
220 | let g_poly = super::g(&domain, z, alpha, beta);
221 | assert_eq!(g_poly.degree(), 2 * n - 1);
222 | assert_eq!(g_poly.evaluate(&Scalar::one()), z);
223 |
224 | // n2 = 4, 2^n2 = 16, 0 <= z < 2^n2 degree of polynomial should be (n2 - 1) it should also
225 | // evaluate to `z2` at x = 1
226 | let n = 8usize;
227 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
228 | let z = Scalar::from(13u8);
229 |
230 | let alpha = Scalar::rand(rng);
231 | let beta = Scalar::rand(rng);
232 | let g_poly = super::g(&domain, z, alpha, beta);
233 | assert_eq!(g_poly.degree(), 2 * n - 1);
234 | assert_eq!(g_poly.evaluate(&Scalar::one()), z);
235 | }
236 |
237 | #[test]
238 | fn compute_w1_w2_polys_success() {
239 | let rng = &mut test_rng();
240 |
241 | let n = 8usize;
242 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
243 |
244 | let one = Scalar::one();
245 | let zero = Scalar::zero();
246 | let r = Scalar::rand(rng);
247 | let alpha = Scalar::rand(rng);
248 | let beta = Scalar::rand(rng);
249 | let z = Scalar::from(92u8);
250 | let f_poly = super::f(&domain, z, r);
251 | let g_poly = super::g(&domain, z, alpha, beta);
252 |
253 | let (w1_poly, w2_poly) = super::w1_w2(&domain, &f_poly, &g_poly).unwrap();
254 |
255 | // both w1 and w2 should evaluate to 0 at x = 1
256 | assert_eq!(w1_poly.evaluate(&one), zero);
257 | assert_eq!(w2_poly.evaluate(&one), zero);
258 |
259 | // both w1 and w2 should evaluate to 0 at all roots of unity
260 | for root in domain.elements() {
261 | assert_eq!(w1_poly.evaluate(&root), zero);
262 | assert_eq!(w2_poly.evaluate(&root), zero);
263 | }
264 |
265 | let n_as_ref = Scalar::from(n as u8).into_bigint();
266 | // evaluate w1 at a random field element
267 | let r = Scalar::rand(rng);
268 | let part_a = g_poly.evaluate(&r);
269 | let part_b = f_poly.evaluate(&r);
270 | let part_c = (r.pow(n_as_ref) - one) / (r - one);
271 | let w1_expected = (part_a - part_b) * part_c;
272 | assert_eq!(w1_poly.evaluate(&r), w1_expected);
273 |
274 | // evaluate w2 at a random field element
275 | let w_n_minus_1 = domain.elements().last().unwrap();
276 | let r = Scalar::rand(rng);
277 | let part_a = g_poly.evaluate(&r);
278 | let part_b = one - part_a;
279 | let part_c = (r.pow(n_as_ref) - one) / (r - w_n_minus_1);
280 | let w2_expected = part_a * part_b * part_c;
281 | assert_eq!(w2_poly.evaluate(&r), w2_expected);
282 | }
283 |
284 | #[test]
285 | fn compute_w3_poly_success() {
286 | let rng = &mut test_rng();
287 |
288 | let n = 8usize;
289 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
290 | let domain_2n = GeneralEvaluationDomain::::new(2 * n).unwrap();
291 |
292 | let one = Scalar::one();
293 | let two = Scalar::from(2u8);
294 |
295 | let z = Scalar::from(83u8);
296 | let alpha = Scalar::rand(rng);
297 | let beta = Scalar::rand(rng);
298 | let g_poly = super::g(&domain, z, alpha, beta);
299 |
300 | let w3_poly = super::w3(&domain, &domain_2n, &g_poly).unwrap();
301 |
302 | // w3 should evaluate to 0 at all roots of unity for original domain
303 | for root in domain.elements() {
304 | assert!(w3_poly.evaluate(&root).is_zero());
305 | }
306 |
307 | // w3 degree should be 4n - 1
308 | assert_eq!(w3_poly.degree(), 4 * domain.size() - 1);
309 |
310 | // evaluate w3 at a random field element
311 | let w_n_minus_1 = domain.elements().last().unwrap();
312 | let r = Scalar::rand(rng);
313 | let part_a = g_poly.evaluate(&r) - two * g_poly.evaluate(&(r * domain.group_gen()));
314 | let part_b = one - g_poly.evaluate(&r) + two * g_poly.evaluate(&(r * domain.group_gen()));
315 | let part_c = r - w_n_minus_1;
316 | let w3_expected = part_a * part_b * part_c;
317 | assert_eq!(w3_poly.evaluate(&r), w3_expected);
318 |
319 | // evaluate w3 at another random field element
320 | let r = Scalar::rand(rng);
321 | let part_a = g_poly.evaluate(&r) - two * g_poly.evaluate(&(r * domain.group_gen()));
322 | let part_b = one - g_poly.evaluate(&r) + two * g_poly.evaluate(&(r * domain.group_gen()));
323 | let part_c = r - w_n_minus_1;
324 | let w3_expected = part_a * part_b * part_c;
325 | assert_eq!(w3_poly.evaluate(&r), w3_expected);
326 | }
327 |
328 | #[test]
329 | fn compute_w_cap_poly_success() {
330 | let rng = &mut test_rng();
331 |
332 | // domain setup
333 | let n = 8usize;
334 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
335 | let domain_2n = GeneralEvaluationDomain::::new(2 * n).unwrap();
336 | // KZG setup
337 | let tau = Scalar::rand(rng); // "secret" tau
338 | let powers = Powers::::unsafe_setup(tau, 4 * n);
339 |
340 | // random numbers
341 | let r = Scalar::rand(rng);
342 | let t = Scalar::rand(rng);
343 | let rho = Scalar::rand(rng);
344 | let alpha = Scalar::rand(rng);
345 | let beta = Scalar::rand(rng);
346 |
347 | // compute polynomials
348 | let z = Scalar::from(68u8);
349 | let f_poly = super::f(&domain, z, r);
350 | let g_poly = super::g(&domain, z, alpha, beta);
351 | let (w1_poly, w2_poly) = super::w1_w2(&domain, &f_poly, &g_poly).unwrap();
352 | let w3_poly = super::w3(&domain, &domain_2n, &g_poly).unwrap();
353 | let q_poly = super::quotient(&domain, &w1_poly, &w2_poly, &w3_poly, t).unwrap();
354 | let w_cap_poly = super::w_cap(&domain, &f_poly, &q_poly, rho);
355 |
356 | // compute commitments
357 | let f_commitment = powers.commit_g1(&f_poly).into_affine();
358 | let q_commitment = powers.commit_g1(&q_poly).into_affine();
359 | let w_cap_commitment_expected = powers.commit_g1(&w_cap_poly);
360 |
361 | // calculate w_cap commitment fact that commitment scheme is additively homomorphic
362 | let w_cap_commitment_calculated = super::super::utils::w_cap::<::G1>(
363 | domain.size(),
364 | f_commitment,
365 | q_commitment,
366 | rho,
367 | );
368 |
369 | assert_eq!(w_cap_commitment_expected, w_cap_commitment_calculated);
370 |
371 | // check evaluations
372 | let w_cap_eval = w_cap_poly.evaluate(&rho);
373 | let g_eval = g_poly.evaluate(&rho);
374 | let g_omega_eval = g_poly.evaluate(&(rho * domain.group_gen()));
375 | let sum = super::super::utils::w1_w2_w3_evals_sum(&domain, g_eval, g_omega_eval, rho, t);
376 | assert_eq!(sum, w_cap_eval);
377 | }
378 |
379 | #[test]
380 | fn compute_w1_part_success() {
381 | let rng = &mut test_rng();
382 | let n = 8usize;
383 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
384 | let z = Scalar::from(92u8);
385 | let alpha = Scalar::rand(rng);
386 | let beta = Scalar::rand(rng);
387 | let g_poly = super::g(&domain, z, alpha, beta);
388 |
389 | let rho = Scalar::rand(rng);
390 | let g_eval = g_poly.evaluate(&rho);
391 |
392 | let n_as_ref = Scalar::from(domain.size() as u8).into_bigint();
393 | let one = Scalar::one();
394 | let rho_n_minus_1 = rho.pow(n_as_ref) - one;
395 |
396 | let w1_part_poly = w1_part(&domain, &g_poly);
397 |
398 | assert_eq!(
399 | w1_part_poly.evaluate(&rho),
400 | g_eval * rho_n_minus_1 / (rho - one)
401 | )
402 | }
403 |
404 | #[test]
405 | fn test_compute_w2_w3_part() {
406 | let rng = &mut test_rng();
407 |
408 | let n = 8usize;
409 | let domain = GeneralEvaluationDomain::::new(n).unwrap();
410 | let domain_2n = GeneralEvaluationDomain::::new(2 * n).unwrap();
411 |
412 | let z = Scalar::from(92u8);
413 | let r = Scalar::rand(rng);
414 | let alpha = Scalar::rand(rng);
415 | let beta = Scalar::rand(rng);
416 | let f_poly = super::f(&domain, z, r);
417 | let g_poly = super::g(&domain, z, alpha, beta);
418 | let (_, w2) = super::w1_w2(&domain, &f_poly, &g_poly).unwrap();
419 | let w3 = super::w3(&domain, &domain_2n, &g_poly).unwrap();
420 |
421 | let tau = Scalar::rand(rng);
422 | let rho = Scalar::rand(rng);
423 | let g_eval = g_poly.evaluate(&rho);
424 | let g_omega_eval = g_poly.evaluate(&(rho * domain.group_gen()));
425 |
426 | let (_, rho_n_minus_1) = super::super::utils::rho_relations(domain.size(), rho);
427 | let one = Scalar::one();
428 | let two = Scalar::from(2u8);
429 | let w_n_minus_1 = domain.elements().last().unwrap();
430 |
431 | let (w2_part_poly, w3_part_poly) = w2_w3_parts(&w2, &w3, tau);
432 |
433 | assert_eq!(
434 | w2_part_poly.evaluate(&rho),
435 | tau * g_eval * (one - g_eval) * (rho_n_minus_1) / (rho - w_n_minus_1)
436 | );
437 |
438 | assert_eq!(w3_part_poly.evaluate(&rho), {
439 | let part_a = g_eval - (two * g_omega_eval);
440 | let part_b = one - part_a;
441 | let part_c = rho - w_n_minus_1;
442 | tau * tau * part_a * part_b * part_c
443 | });
444 | }
445 | }
446 |
--------------------------------------------------------------------------------
/src/range_proof/utils.rs:
--------------------------------------------------------------------------------
1 | use ark_ec::CurveGroup;
2 | use ark_ff::PrimeField;
3 | use ark_poly::{EvaluationDomain, GeneralEvaluationDomain};
4 | use ark_std::ops::{AddAssign, Mul};
5 | use ark_std::Zero;
6 |
7 | // returns (rho^n - 1) / (rho - 1) and (rho^n - 1)
8 | pub fn rho_relations(size: usize, rho: S) -> (S, S) {
9 | let n_as_ref = S::from(size as u8).into_bigint();
10 | let one = S::one();
11 | let rho_n_minus_1 = rho.pow(n_as_ref) - one;
12 | let rho_n_minus_1_by_rho_minus_1 = rho_n_minus_1 / (rho - one);
13 |
14 | (rho_n_minus_1_by_rho_minus_1, rho_n_minus_1)
15 | }
16 |
17 | // computes the sum of
18 | // - w1(x) = g * (x^n - 1) / (x - 1) // note that we don't compute (g - f) here
19 | // - w2(x) = g * (1 - g) * (x^n - 1) / (x - omega^{n - 1})
20 | // - w3(x) = (g(x) - 2 * g(x * omega)) * (1 - g(x) + 2 * g(x * omega)) * (x - omega^{n - 1})
21 | //
22 | // where g = g(rho), f = f(rho), i.e. the polynomial evaluations at point rho, n is the domain size
23 | // and omega denotes the roots of unity
24 | pub fn w1_w2_w3_evals_sum(
25 | domain: &GeneralEvaluationDomain,
26 | g_eval: S,
27 | g_omega_eval: S,
28 | rho: S,
29 | tau: S,
30 | ) -> S {
31 | let (rho_n_minus_1_by_rho_minus_1, rho_n_minus_1) = rho_relations(domain.size(), rho);
32 | let one = S::one();
33 | let two = S::from(2u8);
34 | let w_n_minus_1 = domain.elements().last().unwrap();
35 | // w1_part
36 | let w1_eval = g_eval * rho_n_minus_1_by_rho_minus_1;
37 | // w2
38 | let w2_eval = g_eval * (one - g_eval) * rho_n_minus_1 / (rho - w_n_minus_1);
39 | // w3
40 | let w3_eval = {
41 | let part_a = g_eval - (two * g_omega_eval);
42 | let part_b = one - part_a;
43 | let part_c = rho - w_n_minus_1;
44 | part_a * part_b * part_c
45 | };
46 |
47 | w1_eval + tau * w2_eval + tau.square() * w3_eval
48 | }
49 |
50 | // returns w_cap(x) = f(x) * (rho^n - 1) / (rho - 1) + q(x) * (rho^n - 1)
51 | pub fn w_cap(
52 | size: usize,
53 | f_commitment: C::Affine,
54 | q_commitment: C::Affine,
55 | rho: C::ScalarField,
56 | ) -> C::Affine {
57 | let (rho_relation_1, rho_relation_2) = rho_relations(size, rho);
58 | let f_commit = f_commitment * rho_relation_1;
59 | let q_commit = q_commitment * rho_relation_2;
60 | (f_commit + q_commit).into()
61 | }
62 |
63 | pub fn aggregate(values: &[T], by: S) -> T
64 | where
65 | S: PrimeField,
66 | T: Sized + Zero + Mul + AddAssign<>::Output> + Copy,
67 | {
68 | let mut acc = S::one();
69 | let mut result = T::zero();
70 |
71 | for &value in values {
72 | let tmp = value * acc;
73 | result += tmp;
74 | acc *= by;
75 | }
76 |
77 | result
78 | }
79 |
--------------------------------------------------------------------------------
/src/tests/mod.rs:
--------------------------------------------------------------------------------
1 | pub use ark_bls12_381::{Bls12_381 as TestCurve, G1Affine};
2 | use ark_ec::pairing::Pairing;
3 | use ark_ff::PrimeField;
4 | use ark_poly::univariate::DensePolynomial;
5 | use criterion as _;
6 | pub use sha3::Keccak256 as TestHash;
7 |
8 | pub const N: usize = Scalar::MODULUS_BIT_SIZE as usize / crate::encrypt::elgamal::MAX_BITS + 1;
9 |
10 | pub type Scalar = ::ScalarField;
11 | pub type UniPoly = DensePolynomial;
12 |
13 | /*
14 | pub type Elgamal = crate::encrypt::elgamal::ExponentialElgamal<::G1>;
15 | pub type ElgamalEncryptionProof = crate::veck::kzg_elgamal::EncryptionProof<{ N }, BlsCurve, Keccak256>;
16 | pub type KzgElgamalProof = crate::veck::kzg_elgamal::Proof<{ N }, BlsCurve, Keccak256>;
17 | pub type DleqProof = crate::dleq::Proof<::G1, Keccak256>;
18 | pub type RangeProof = crate::range_proof::RangeProof;
19 | pub type PaillierEncryptionProof = crate::veck::kzg_paillier::Proof;
20 | */
21 |
--------------------------------------------------------------------------------
/src/veck/kzg/elgamal/encryption.rs:
--------------------------------------------------------------------------------
1 | use crate::commit::kzg::Powers;
2 | use crate::encrypt::elgamal::{Cipher, ExponentialElgamal as Elgamal, SplitScalar, MAX_BITS};
3 | use crate::encrypt::EncryptionEngine;
4 | use crate::range_proof::RangeProof;
5 | use ark_ec::pairing::Pairing;
6 | use ark_ec::{AffineRepr, CurveGroup};
7 | use ark_std::rand::Rng;
8 | use digest::Digest;
9 | #[cfg(feature = "parallel")]
10 | use rayon::prelude::*;
11 |
12 | /// A publicly verifiable proof based on the Elgamal encryption scheme.
13 | #[derive(Clone)]
14 | pub struct EncryptionProof {
15 | /// The actual Elgamal ciphertexts of the encrypted data points.
16 | pub ciphers: Vec