├── .github └── workflows │ ├── clippy.yml │ └── test.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── constraints.rs ├── lib.rs ├── mala_nezhadansari ├── constraints.rs └── mod.rs └── schnorr_blind ├── constraints.rs └── mod.rs /.github/workflows/clippy.yml: -------------------------------------------------------------------------------- 1 | name: Clippy 2 | on: [push, pull_request] 3 | jobs: 4 | clippy_check: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v1 8 | - run: rustup component add clippy 9 | - uses: actions-rs/clippy-check@v1 10 | with: 11 | token: ${{ secrets.GITHUB_TOKEN }} 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push, pull_request] 3 | env: 4 | CARGO_TERM_COLOR: always 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - name: Build 11 | run: cargo build --verbose 12 | - name: Run tests 13 | run: | 14 | cargo test --verbose 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-ec-blind-signatures" 3 | version = "0.0.1" 4 | edition = "2021" 5 | repository = "https://github.com/aragonzkresearch/ark-ec-blind-signatures" 6 | 7 | [dependencies] 8 | ark-ff = { version = "^0.3.0", default-features = false } 9 | ark-std = { version = "^0.3.0", default-features = false } 10 | ark-r1cs-std = { version = "^0.3.0", default-features = false } 11 | ark-ec = { version = "^0.3.0", default-features = false } 12 | ark-bn254 = { version = "^0.3.0", default-features = false } 13 | ark-ed-on-bn254 = { version = "^0.3.0", default-features = true, features = [ "r1cs" ] } 14 | ark-crypto-primitives = { version = "^0.3.0", default-features = true, features = [ "r1cs" ] } 15 | # ark-sponge = { version = "^0.3.0", default-features = true, features = [ "r1cs" ] } 16 | # ark-sponge = { git = "https://github.com/arkworks-rs/sponge.git", rev = "41843d179dc4655869955297833d096d1962120f", default-features=true, features=["r1cs"] } 17 | arkworks-utils = { git = "https://github.com/aragonzkresearch/arkworks-gadgets", name="arkworks-utils", features=["poseidon_bn254_x5_4"] } 18 | arkworks-native-gadgets = { git = "https://github.com/aragonzkresearch/arkworks-gadgets", name="arkworks-native-gadgets"} 19 | arkworks-r1cs-gadgets = { git = "https://github.com/aragonzkresearch/arkworks-gadgets", name="arkworks-r1cs-gadgets"} 20 | ark-relations = { version = "^0.3.0", default-features = false } 21 | ark-snark = { version = "^0.3.0", default-features = false } 22 | tracing = { version = "0.1", default-features = false, features = [ "attributes" ] } 23 | tracing-subscriber = { version = "0.2" } 24 | derivative = { version = "2.0", features = ["use_core"] } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ark-ec-blind-signatures [![Test](https://github.com/aragonzkresearch/ark-ec-blind-signatures/workflows/Test/badge.svg)](https://github.com/aragonzkresearch/ark-ec-blind-signatures/actions?query=workflow%3ATest) [![Clippy](https://github.com/aragonzkresearch/ark-ec-blind-signatures/workflows/Clippy/badge.svg)](https://github.com/aragonzkresearch/ark-ec-blind-signatures/actions?query=workflow%3AClippy) 2 | 3 | > Warning: experimental code, do not use in production. 4 | 5 | [Blind signature](https://en.wikipedia.org/wiki/Blind_signature) over elliptic curve implementation (native & r1cs constraints) using [arkworks](https://github.com/arkworks-rs). 6 | 7 | Schemes implemented: 8 | - mala_nezhadansari: *"[New Blind Signature Schemes Based on the (Elliptic Curve) Discrete Logarithm Problem](https://sci-hub.st/10.1109/iccke.2013.6682844)"* paper by Hamid Mala, Nafiseh Nezhadansari. Note that in this scheme signatures are malleable. Number of constraints for the verification: 9785. 9 | - shcnorr_blind: *"[Blind Schnorr Signatures and Signed ElGamal Encryption in the Algebraic Group Model](https://eprint.iacr.org/2019/877)"* paper by Georg Fuchsbauer, Antoine Plouviez, and Yannick Seurin. Number of constraints for the verification: 6052. 10 | 11 | 12 | Target: Groth16 over Bn254 (for Ethereum), ed-on-bn254 ([BabyJubJub](https://github.com/barryWhiteHat/baby_jubjub)) for the signatures. 13 | -------------------------------------------------------------------------------- /src/constraints.rs: -------------------------------------------------------------------------------- 1 | use ark_r1cs_std::prelude::*; 2 | use ark_relations::r1cs::SynthesisError; 3 | 4 | use crate::BlindSignatureScheme; 5 | use ark_ff::PrimeField; 6 | use arkworks_r1cs_gadgets::poseidon::PoseidonGadget; 7 | 8 | pub trait BlindSigVerifyGadget { 9 | type ParametersVar: AllocVar + Clone; 10 | type PublicKeyVar: AllocVar + Clone; 11 | type SignatureVar: AllocVar + Clone; 12 | type Msg; 13 | type MsgVar: AllocVar + Clone; 14 | 15 | fn verify( 16 | parameters: &Self::ParametersVar, 17 | poseidon_hash: &PoseidonGadget, 18 | m: &Self::MsgVar, 19 | s: &Self::SignatureVar, 20 | q: &Self::PublicKeyVar, 21 | ) -> Result, SynthesisError>; 22 | } 23 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use ark_std::rand::Rng; 2 | 3 | // #[cfg(feature="r1cs")] 4 | pub mod constraints; 5 | 6 | pub mod mala_nezhadansari; 7 | pub mod schnorr_blind; 8 | 9 | use ark_ff::PrimeField; 10 | use arkworks_native_gadgets::poseidon; 11 | 12 | pub trait BlindSignatureScheme { 13 | type Parameters; 14 | type Fq; 15 | type Fr; 16 | type ConstraintF: PrimeField; 17 | type PointAffine; 18 | type SecretKey; 19 | type PublicKey; 20 | // type Msg; 21 | type BlindedSignature; 22 | type Signature; 23 | type UserSecretData; 24 | 25 | fn setup(hash: &poseidon::Poseidon) -> Self::Parameters; 26 | 27 | fn keygen( 28 | parameters: &Self::Parameters, 29 | rng: &mut R, 30 | ) -> (Self::PublicKey, Self::SecretKey); 31 | 32 | fn new_request_params( 33 | parameters: &Self::Parameters, 34 | rng: &mut R, 35 | ) -> (Self::Fr, Self::PointAffine); 36 | 37 | fn blind_sign(sk: Self::SecretKey, r: Self::Fr, m_blinded: Self::Fr) -> Self::BlindedSignature; 38 | 39 | fn unblind(s_blinded: Self::Fr, u: &Self::UserSecretData) -> Self::Signature; 40 | 41 | fn non_blind_sign( 42 | parameters: &Self::Parameters, 43 | rng: &mut R, 44 | sk: Self::SecretKey, 45 | m: &[Self::ConstraintF], 46 | ) -> Result; 47 | 48 | fn blind( 49 | parameters: &Self::Parameters, 50 | rng: &mut R, 51 | m: &[Self::ConstraintF], 52 | signer_pk: Self::PublicKey, 53 | signer_r: Self::PointAffine, 54 | ) -> Result<(Self::Fr, Self::UserSecretData), ark_crypto_primitives::Error>; 55 | 56 | fn verify( 57 | parameters: &Self::Parameters, 58 | m: &[Self::ConstraintF], 59 | s: Self::Signature, 60 | q: Self::PublicKey, 61 | ) -> bool; 62 | } 63 | -------------------------------------------------------------------------------- /src/mala_nezhadansari/constraints.rs: -------------------------------------------------------------------------------- 1 | use crate::mala_nezhadansari::{ConstraintF, Parameters, PublicKey, Signature}; 2 | 3 | use ark_ec::ProjectiveCurve; 4 | use ark_ed_on_bn254::{constraints::EdwardsVar, EdwardsParameters, FqParameters}; 5 | use ark_ff::{fields::Fp256, to_bytes, PrimeField}; 6 | use ark_r1cs_std::{ 7 | alloc::{AllocVar, AllocationMode}, 8 | bits::uint8::UInt8, 9 | boolean::Boolean, 10 | eq::EqGadget, 11 | fields::fp::FpVar, 12 | groups::GroupOpsBounds, 13 | prelude::CurveVar, 14 | ToBitsGadget, 15 | }; 16 | use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError}; 17 | use ark_std::ops::Mul; 18 | 19 | use core::{borrow::Borrow, marker::PhantomData}; 20 | use derivative::Derivative; 21 | 22 | // hash 23 | use arkworks_native_gadgets::poseidon as poseidon_native; 24 | // use arkworks_r1cs_gadgets::poseidon; 25 | use arkworks_r1cs_gadgets::poseidon::{FieldHasherGadget, PoseidonGadget}; 26 | 27 | #[derive(Derivative)] 28 | #[derivative( 29 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 30 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 31 | )] 32 | pub struct PublicKeyVar>> 33 | where 34 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 35 | { 36 | pub pub_key: GC, 37 | #[doc(hidden)] 38 | _group: PhantomData<*const C>, 39 | } 40 | 41 | impl AllocVar, ConstraintF> for PublicKeyVar 42 | where 43 | C: ProjectiveCurve, 44 | GC: CurveVar>, 45 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 46 | { 47 | fn new_variable>>( 48 | cs: impl Into>>, 49 | f: impl FnOnce() -> Result, 50 | mode: AllocationMode, 51 | ) -> Result { 52 | let pub_key = GC::new_variable(cs, f, mode)?; 53 | Ok(Self { 54 | pub_key, 55 | _group: PhantomData, 56 | }) 57 | } 58 | } 59 | 60 | #[derive(Clone, Debug)] 61 | pub struct Msg(pub [ConstraintF; MSG_LEN]); 62 | 63 | #[derive(Derivative)] 64 | #[derivative( 65 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 66 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 67 | )] 68 | pub struct MsgVar>> 69 | where 70 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 71 | { 72 | m: [FpVar>; MSG_LEN], 73 | _gc: PhantomData, 74 | } 75 | impl MsgVar 76 | where 77 | C: ProjectiveCurve, 78 | GC: CurveVar>, 79 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 80 | { 81 | pub fn new(m: [FpVar>; MSG_LEN]) -> Self { 82 | Self { 83 | m, 84 | _gc: PhantomData, 85 | } 86 | } 87 | } 88 | 89 | impl AllocVar, ConstraintF> 90 | for MsgVar 91 | where 92 | C: ProjectiveCurve, 93 | GC: CurveVar>, 94 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 95 | { 96 | fn new_variable>>( 97 | cs: impl Into>>, 98 | f: impl FnOnce() -> Result, 99 | mode: AllocationMode, 100 | ) -> Result { 101 | f().and_then(|m| { 102 | let m = m.borrow(); 103 | let cs = cs.into(); 104 | let msg_vec: Vec>> = 105 | Vec::new_variable(cs, || Ok(m.clone().0), mode)?; 106 | let m: [FpVar>; MSG_LEN] = 107 | msg_vec 108 | .try_into() 109 | .unwrap_or_else(|v: Vec>>| { 110 | // WIP 111 | panic!( 112 | "Expected Vec of length: {}, actual length: {}", 113 | MSG_LEN, 114 | v.len() 115 | ) 116 | }); 117 | Ok(Self { 118 | m, 119 | _gc: PhantomData, 120 | }) 121 | }) 122 | } 123 | } 124 | 125 | #[derive(Derivative)] 126 | #[derivative( 127 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 128 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 129 | )] 130 | pub struct SignatureVar>> 131 | where 132 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 133 | { 134 | s: Vec>>, 135 | r: GC, 136 | _curve: PhantomData, 137 | } 138 | 139 | impl AllocVar, ConstraintF> for SignatureVar 140 | where 141 | C: ProjectiveCurve, 142 | GC: CurveVar>, 143 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 144 | { 145 | fn new_variable>>( 146 | cs: impl Into>>, 147 | f: impl FnOnce() -> Result, 148 | mode: AllocationMode, 149 | ) -> Result { 150 | f().and_then(|val| { 151 | let cs = cs.into(); 152 | // let s = val.borrow().s; 153 | let mut s = Vec::>>::new(); 154 | let s_bytes = to_bytes![val.borrow().s].unwrap(); 155 | #[allow(clippy::needless_range_loop)] 156 | for i in 0..s_bytes.len() { 157 | s.push(UInt8::>::new_variable( 158 | cs.clone(), 159 | || Ok(s_bytes[i]), 160 | mode, 161 | )?); 162 | } 163 | 164 | let r = GC::new_variable(cs, || Ok(val.borrow().r), mode)?; 165 | 166 | Ok(Self { 167 | s, 168 | r, 169 | _curve: PhantomData, 170 | }) 171 | }) 172 | } 173 | } 174 | 175 | #[derive(Clone)] 176 | pub struct ParametersVar>> 177 | where 178 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 179 | { 180 | generator: GC, 181 | _curve: PhantomData, 182 | } 183 | 184 | impl AllocVar, ConstraintF> for ParametersVar 185 | where 186 | C: ProjectiveCurve, 187 | GC: CurveVar>, 188 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 189 | { 190 | fn new_variable>>( 191 | cs: impl Into>>, 192 | f: impl FnOnce() -> Result, 193 | mode: AllocationMode, 194 | ) -> Result { 195 | f().and_then(|val| { 196 | let cs = cs.into(); 197 | let generator = GC::new_variable(cs, || Ok(val.borrow().generator), mode)?; 198 | Ok(Self { 199 | generator, 200 | _curve: PhantomData, 201 | }) 202 | }) 203 | } 204 | } 205 | 206 | pub struct BlindSigVerifyGadget< 207 | const MSG_LEN: usize, 208 | C: ProjectiveCurve, 209 | GC: CurveVar>, 210 | > where 211 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 212 | { 213 | _params: Parameters, // TODO review if needed, maybe delete 214 | _gc: PhantomData, 215 | } 216 | 217 | impl>> 218 | BlindSigVerifyGadget 219 | where 220 | C: ProjectiveCurve, 221 | GC: CurveVar>, 222 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 223 | ark_r1cs_std::groups::curves::twisted_edwards::AffineVar< 224 | EdwardsParameters, 225 | FpVar>, 226 | >: From, 227 | ::BaseField: PrimeField, 228 | FpVar<::BaseField>: Mul>>, 229 | FpVar<::BaseField>: From>>, 230 | { 231 | pub fn verify( 232 | parameters: &ParametersVar, 233 | poseidon_hash: &PoseidonGadget>, 234 | m: &MsgVar, 235 | s: &SignatureVar, 236 | q: &PublicKeyVar, 237 | ) -> Result>, SynthesisError> { 238 | let sG = parameters 239 | .generator 240 | .scalar_mul_le(s.s.to_bits_le()?.iter())?; 241 | 242 | // Note: in a circuit that aggregates multiple verifications, the hashing step could be 243 | // done outside the signature verification, once for all 1 votes and once for all 0 votes, 244 | // saving lots of constraints 245 | let hm = poseidon_hash.hash(&m.m)?; 246 | let r = EdwardsVar::from(s.r.clone()); // WIP 247 | let rx_fpvar: FpVar> = r.x.into(); 248 | 249 | // G * s == R + Q * (R.x * H(m)) 250 | let Q_rx_hm_0 = q.pub_key.scalar_mul_le(rx_fpvar.to_bits_le()?.iter())?; 251 | let Q_rx_hm = Q_rx_hm_0.scalar_mul_le(hm.to_bits_le()?.iter())?; 252 | let RHS = s.r.clone() + Q_rx_hm; 253 | 254 | sG.is_eq(&RHS) 255 | } 256 | } 257 | 258 | pub struct BlindSigBatchVerifyGadget< 259 | const NUM_SIGS: usize, 260 | const MSG_LEN: usize, 261 | C: ProjectiveCurve, 262 | GC: CurveVar>, 263 | > where 264 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 265 | { 266 | _params: Parameters, // TODO review if needed, maybe delete 267 | _gc: PhantomData, 268 | } 269 | 270 | impl< 271 | const NUM_SIGS: usize, 272 | const MSG_LEN: usize, 273 | C: ProjectiveCurve, 274 | GC: CurveVar>, 275 | > BlindSigBatchVerifyGadget 276 | where 277 | C: ProjectiveCurve, 278 | GC: CurveVar>, 279 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 280 | ark_r1cs_std::groups::curves::twisted_edwards::AffineVar< 281 | EdwardsParameters, 282 | FpVar>, 283 | >: From, 284 | ::BaseField: PrimeField, 285 | FpVar<::BaseField>: Mul>>, 286 | FpVar<::BaseField>: From>>, 287 | { 288 | pub fn batch_verify( 289 | parameters: &ParametersVar, 290 | poseidon_hash: &PoseidonGadget>, 291 | m: &MsgVar, 292 | sigs: &[SignatureVar], 293 | q: &PublicKeyVar, 294 | ) -> Result>, SynthesisError> { 295 | // Note: in a circuit that aggregates multiple verifications, the hashing step could be 296 | // done outside the signature verification, once for all 1 votes and once for all 0 votes, 297 | // saving lots of constraints 298 | let hm = poseidon_hash.hash(&m.m)?; 299 | 300 | #[allow(clippy::needless_range_loop)] 301 | for i in 0..NUM_SIGS { 302 | let sG = parameters 303 | .generator 304 | .scalar_mul_le(sigs[i].s.to_bits_le()?.iter())?; 305 | 306 | let r = EdwardsVar::from(sigs[i].r.clone()); // WIP 307 | let rx_fpvar: FpVar> = r.x.into(); 308 | 309 | // G * s == R + Q * (R.x * H(m)) 310 | let Q_rx_hm_0 = q.pub_key.scalar_mul_le(rx_fpvar.to_bits_le()?.iter())?; 311 | let Q_rx_hm = Q_rx_hm_0.scalar_mul_le(hm.to_bits_le()?.iter())?; 312 | let RHS = sigs[i].r.clone() + Q_rx_hm; 313 | sG.enforce_equal(&RHS)?; 314 | } 315 | Ok(Boolean::TRUE) 316 | } 317 | } 318 | 319 | // example of circuit using BlindSigVerifyGadget to verify a single blind signature 320 | #[derive(Clone)] 321 | pub struct BlindSigVerifyCircuit< 322 | const MSG_LEN: usize, 323 | C: ProjectiveCurve, 324 | GC: CurveVar>, 325 | > where 326 | ::BaseField: PrimeField, 327 | { 328 | _group: PhantomData<*const GC>, 329 | pub params: Parameters, 330 | pub poseidon_hash_native: poseidon_native::Poseidon>, 331 | pub signature: Option>, 332 | pub pub_key: Option>, 333 | pub message: Option>, 334 | } 335 | 336 | impl>> 337 | ConstraintSynthesizer> for BlindSigVerifyCircuit 338 | where 339 | C: ProjectiveCurve, 340 | GC: CurveVar>, 341 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 342 | ark_r1cs_std::groups::curves::twisted_edwards::AffineVar< 343 | EdwardsParameters, 344 | FpVar>, 345 | >: From, 346 | ::BaseField: PrimeField, 347 | FpVar<::BaseField>: Mul>>, 348 | FpVar<::BaseField>: From>>, 349 | { 350 | #[tracing::instrument(target = "r1cs", skip(self, cs))] 351 | fn generate_constraints( 352 | self, 353 | cs: ConstraintSystemRef>, 354 | ) -> Result<(), SynthesisError> { 355 | let parameters = 356 | ParametersVar::new_constant(ark_relations::ns!(cs, "parameters"), &self.params)?; 357 | 358 | let pub_key = 359 | PublicKeyVar::::new_input(ark_relations::ns!(cs, "public key"), || { 360 | self.pub_key.ok_or(SynthesisError::AssignmentMissing) 361 | })?; 362 | let m = MsgVar::::new_input(ark_relations::ns!(cs, "message"), || { 363 | self.message.ok_or(SynthesisError::AssignmentMissing) 364 | })?; 365 | let signature = 366 | SignatureVar::::new_witness(ark_relations::ns!(cs, "signature"), || { 367 | self.signature.ok_or(SynthesisError::AssignmentMissing) 368 | })?; 369 | #[allow(clippy::redundant_clone)] 370 | let poseidon_hash = PoseidonGadget::>::from_native( 371 | &mut cs.clone(), 372 | self.poseidon_hash_native, 373 | ) 374 | .unwrap(); 375 | 376 | let v = BlindSigVerifyGadget::::verify( 377 | ¶meters, 378 | &poseidon_hash, 379 | &m, 380 | &signature, 381 | &pub_key, 382 | )?; 383 | v.enforce_equal(&Boolean::TRUE) 384 | } 385 | } 386 | 387 | // example of circuit using BlindSigVerifyGadget to verify a batch of blind signatures 388 | #[derive(Clone)] 389 | pub struct BlindSigBatchVerifyCircuit< 390 | const NUM_SIGS: usize, 391 | const MSG_LEN: usize, 392 | C: ProjectiveCurve, 393 | GC: CurveVar>, 394 | > where 395 | ::BaseField: PrimeField, 396 | { 397 | _group: PhantomData<*const GC>, 398 | pub params: Parameters, 399 | pub poseidon_hash_native: poseidon_native::Poseidon>, 400 | pub signatures: Option>>, 401 | pub pub_key: Option>, 402 | pub message: Option>, 403 | } 404 | 405 | impl< 406 | const NUM_SIGS: usize, 407 | const MSG_LEN: usize, 408 | C: ProjectiveCurve, 409 | GC: CurveVar>, 410 | > ConstraintSynthesizer> for BlindSigBatchVerifyCircuit 411 | where 412 | C: ProjectiveCurve, 413 | GC: CurveVar>, 414 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 415 | ark_r1cs_std::groups::curves::twisted_edwards::AffineVar< 416 | EdwardsParameters, 417 | FpVar>, 418 | >: From, 419 | ::BaseField: PrimeField, 420 | FpVar<::BaseField>: Mul>>, 421 | FpVar<::BaseField>: From>>, 422 | { 423 | #[tracing::instrument(target = "r1cs", skip(self, cs))] 424 | fn generate_constraints( 425 | self, 426 | cs: ConstraintSystemRef>, 427 | ) -> Result<(), SynthesisError> { 428 | let parameters = 429 | ParametersVar::new_constant(ark_relations::ns!(cs, "parameters"), &self.params)?; 430 | 431 | let pub_key = 432 | PublicKeyVar::::new_input(ark_relations::ns!(cs, "public key"), || { 433 | self.pub_key.ok_or(SynthesisError::AssignmentMissing) 434 | })?; 435 | let m = MsgVar::::new_input(ark_relations::ns!(cs, "message"), || { 436 | self.message.ok_or(SynthesisError::AssignmentMissing) 437 | })?; 438 | 439 | let mut signatures: Vec> = Vec::new(); 440 | for i in 0..NUM_SIGS { 441 | let signature = self.signatures.as_ref().and_then(|s| s.get(i)); 442 | 443 | let signature = 444 | SignatureVar::::new_witness(ark_relations::ns!(cs, "signature"), || { 445 | signature.ok_or(SynthesisError::AssignmentMissing) 446 | })?; 447 | signatures.push(signature); 448 | } 449 | 450 | #[allow(clippy::redundant_clone)] 451 | let poseidon_hash = PoseidonGadget::>::from_native( 452 | &mut cs.clone(), 453 | self.poseidon_hash_native, 454 | ) 455 | .unwrap(); 456 | 457 | let v = BlindSigBatchVerifyGadget::::batch_verify( 458 | ¶meters, 459 | &poseidon_hash, 460 | &m, 461 | &signatures, 462 | &pub_key, 463 | )?; 464 | v.enforce_equal(&Boolean::TRUE) 465 | } 466 | } 467 | 468 | #[cfg(test)] 469 | mod test { 470 | use super::*; 471 | use crate::mala_nezhadansari::{poseidon_setup_params, BlindSigScheme}; 472 | use ark_ed_on_bn254::constraints::EdwardsVar as BabyJubJubVar; 473 | use ark_ed_on_bn254::EdwardsProjective as BabyJubJub; 474 | 475 | use arkworks_native_gadgets::poseidon; 476 | use arkworks_utils::Curve; 477 | 478 | use ark_relations::r1cs::ConstraintSystem; 479 | 480 | type Fq = ::BaseField; 481 | // type Fr = ::ScalarField; 482 | type S = BlindSigScheme; 483 | 484 | fn generate_single_sig_native_data( 485 | poseidon_hash: &poseidon::Poseidon, 486 | ) -> ( 487 | Parameters, 488 | PublicKey, 489 | Msg<3, BabyJubJub>, 490 | Signature, 491 | ) { 492 | let mut rng = ark_std::test_rng(); 493 | let params = S::setup(); 494 | let (pk, sk) = S::keygen(¶ms, &mut rng); 495 | let (k, signer_r) = S::new_request_params(¶ms, &mut rng); 496 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 497 | let (m_blinded, u) = S::blind(¶ms, &mut rng, &poseidon_hash, &m, signer_r).unwrap(); 498 | let s_blinded = S::blind_sign(sk, k, m_blinded); 499 | let s = S::unblind(s_blinded, &u); 500 | let verified = S::verify(¶ms, &poseidon_hash, &m, s.clone(), pk); 501 | assert!(verified); 502 | (params, pk, Msg(m), s) 503 | } 504 | 505 | fn generate_batch_sig_native_data( 506 | poseidon_hash: &poseidon::Poseidon, 507 | n: usize, 508 | ) -> ( 509 | Parameters, 510 | PublicKey, 511 | Msg<3, BabyJubJub>, 512 | Vec>, 513 | ) { 514 | let mut rng = ark_std::test_rng(); 515 | let params = S::setup(); 516 | let (pk, sk) = S::keygen(¶ms, &mut rng); 517 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 518 | let mut signatures: Vec> = Vec::new(); 519 | for _ in 0..n { 520 | let (k, signer_r) = S::new_request_params(¶ms, &mut rng); 521 | let (m_blinded, u) = S::blind(¶ms, &mut rng, &poseidon_hash, &m, signer_r).unwrap(); 522 | let s_blinded = S::blind_sign(sk, k, m_blinded); 523 | let s = S::unblind(s_blinded, &u); 524 | let verified = S::verify(¶ms, &poseidon_hash, &m, s.clone(), pk); 525 | assert!(verified); 526 | signatures.push(s); 527 | } 528 | (params, pk, Msg(m), signatures) 529 | } 530 | 531 | #[test] 532 | fn test_single_verify() { 533 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 534 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 535 | const MSG_LEN: usize = 3; 536 | 537 | // create signature using native-rust lib 538 | let (params, pk, m, s) = generate_single_sig_native_data(&poseidon_hash); 539 | 540 | // use the constraint system to verify the signature 541 | type SG = BlindSigVerifyGadget; 542 | let cs = ConstraintSystem::::new_ref(); 543 | 544 | let params_var = 545 | ParametersVar::::new_constant(cs.clone(), params).unwrap(); 546 | let signature_var = 547 | SignatureVar::::new_witness(cs.clone(), || Ok(&s)).unwrap(); 548 | let pk_var = 549 | PublicKeyVar::::new_witness(cs.clone(), || Ok(&pk)).unwrap(); 550 | let m_var = MsgVar::::new_witness(cs.clone(), || Ok(m)) 551 | .unwrap(); 552 | let poseidon_hash_var = 553 | PoseidonGadget::::from_native(&mut cs.clone(), poseidon_hash).unwrap(); 554 | 555 | let valid_sig = SG::verify( 556 | ¶ms_var, 557 | &poseidon_hash_var, 558 | &m_var, 559 | &signature_var, 560 | &pk_var, 561 | ) 562 | .unwrap(); 563 | valid_sig.enforce_equal(&Boolean::::TRUE).unwrap(); 564 | assert!(cs.is_satisfied().unwrap()); 565 | } 566 | 567 | #[test] 568 | fn test_single_verify_constraint_system() { 569 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 570 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 571 | const MSG_LEN: usize = 3; 572 | 573 | // create signature using native-rust lib 574 | let (params, pk, m, s) = generate_single_sig_native_data(&poseidon_hash); 575 | 576 | // use the constraint system to verify the signature 577 | let circuit = BlindSigVerifyCircuit:: { 578 | params, 579 | poseidon_hash_native: poseidon_hash.clone(), 580 | signature: Some(s), 581 | pub_key: Some(pk), 582 | message: Some(m), 583 | _group: PhantomData, 584 | }; 585 | let cs = ConstraintSystem::::new_ref(); 586 | circuit.generate_constraints(cs.clone()).unwrap(); 587 | let is_satisfied = cs.is_satisfied().unwrap(); 588 | assert!(is_satisfied); 589 | println!("num_constraints={:?}", cs.num_constraints()); 590 | } 591 | 592 | #[test] 593 | fn test_batch_verify_constraint_system() { 594 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 595 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 596 | const MSG_LEN: usize = 3; 597 | 598 | // create signatures using native-rust lib 599 | const NUM_SIGS: usize = 5; 600 | let (params, pk, m, sigs) = generate_batch_sig_native_data(&poseidon_hash, NUM_SIGS); 601 | 602 | // use the constraint system to verify the batch of signatures 603 | let circuit = BlindSigBatchVerifyCircuit:: { 604 | params, 605 | poseidon_hash_native: poseidon_hash.clone(), 606 | signatures: Some(sigs), 607 | pub_key: Some(pk), 608 | message: Some(m), 609 | _group: PhantomData, 610 | }; 611 | let cs = ConstraintSystem::::new_ref(); 612 | circuit.generate_constraints(cs.clone()).unwrap(); 613 | let is_satisfied = cs.is_satisfied().unwrap(); 614 | assert!(is_satisfied); 615 | println!("num_constraints={:?}", cs.num_constraints()); 616 | } 617 | } 618 | -------------------------------------------------------------------------------- /src/mala_nezhadansari/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | #![allow(clippy::many_single_char_names)] 3 | 4 | // #[cfg(feature="r1cs")] 5 | pub mod constraints; 6 | 7 | use ark_ec::{models::twisted_edwards_extended::GroupAffine, AffineCurve, ProjectiveCurve}; 8 | 9 | use ark_ff::{to_bytes, BigInteger256, Field, FpParameters, PrimeField}; 10 | 11 | use ark_std::marker::PhantomData; 12 | use ark_std::{rand::Rng, UniformRand}; 13 | use derivative::Derivative; 14 | 15 | // hash 16 | use arkworks_native_gadgets::poseidon; 17 | use arkworks_native_gadgets::poseidon::FieldHasher; 18 | use arkworks_utils::{ 19 | bytes_matrix_to_f, bytes_vec_to_f, poseidon_params::setup_poseidon_params, Curve, 20 | }; 21 | 22 | // WIP 23 | use ark_ed_on_bn254::{EdwardsAffine, EdwardsParameters}; 24 | 25 | pub type ConstraintF = <::BaseField as Field>::BasePrimeField; 26 | pub type SecretKey = ::ScalarField; 27 | pub type PublicKey = ::Affine; 28 | pub type BlindedSignature = ::ScalarField; 29 | 30 | // #[derive(Derivative)] 31 | #[derive(Clone, Default, Debug)] 32 | pub struct Signature { 33 | s: C::ScalarField, // ScalarField == Fr 34 | r: ::Affine, 35 | } 36 | 37 | #[derive(Clone, Default, Debug)] 38 | pub struct UserSecretData { 39 | a: C::ScalarField, 40 | b: C::ScalarField, 41 | r: C::Affine, 42 | } 43 | impl UserSecretData { 44 | fn new_empty(parameters: &Parameters) -> Self { 45 | UserSecretData { 46 | a: C::ScalarField::from(0_u32), 47 | b: C::ScalarField::from(0_u32), 48 | r: parameters.generator, // WIP 49 | } 50 | } 51 | } 52 | 53 | #[derive(Derivative)] 54 | #[derivative(Clone(bound = "C: ProjectiveCurve"), Debug)] 55 | pub struct Parameters { 56 | pub generator: C::Affine, 57 | } 58 | 59 | pub struct BlindSigScheme { 60 | _group: PhantomData, 61 | } 62 | 63 | impl BlindSigScheme 64 | where 65 | C::ScalarField: PrimeField, 66 | GroupAffine: From<::Affine>, // WIP 67 | { 68 | pub fn setup() -> Parameters { 69 | let generator = C::prime_subgroup_generator().into(); 70 | Parameters { generator } 71 | } 72 | 73 | // signer 74 | pub fn keygen(parameters: &Parameters, rng: &mut R) -> (PublicKey, SecretKey) { 75 | let secret_key = C::ScalarField::rand(rng); 76 | let public_key = parameters.generator.mul(secret_key).into(); 77 | (public_key, secret_key) 78 | } 79 | 80 | pub fn new_request_params( 81 | parameters: &Parameters, 82 | rng: &mut R, 83 | ) -> (C::ScalarField, C::Affine) { 84 | let k = C::ScalarField::rand(rng); 85 | let R = parameters.generator.mul(k).into(); 86 | (k, R) 87 | } 88 | 89 | pub fn blind_sign( 90 | sk: SecretKey, 91 | k: C::ScalarField, 92 | m_blinded: C::ScalarField, 93 | ) -> BlindedSignature { 94 | sk * m_blinded + k 95 | } 96 | 97 | // new_k_and_R returns a new k \in Fr, and R=k * G, such that R.x \in Fr 98 | fn new_k_and_R(parameters: &Parameters, rng: &mut R) -> (C::ScalarField, C::Affine) 99 | where 100 | ::ScalarField: From, 101 | { 102 | let k = C::ScalarField::rand(rng); 103 | 104 | let R: C::Affine = parameters.generator.mul(k.into_repr()).into(); 105 | let r = EdwardsAffine::from(R); // WIP 106 | 107 | let one = BigInteger256::from(1u64); 108 | let x_repr = r.x.into_repr(); 109 | let modulus = <::Params as FpParameters>::MODULUS; 110 | let modulus_repr = BigInteger256::try_from(modulus.into()).unwrap(); 111 | 112 | if !(x_repr >= one && x_repr < modulus_repr) { 113 | // TODO maybe add a counter of attempts with a limit 114 | return Self::new_k_and_R(parameters, rng); 115 | } 116 | 117 | (k, R) 118 | } 119 | 120 | // non_blind_sign performs a non-blind signature, which can be verified with the same check 121 | // than a blind-signature 122 | pub fn non_blind_sign( 123 | parameters: &Parameters, 124 | rng: &mut R, 125 | poseidon_hash: &poseidon::Poseidon>, 126 | sk: SecretKey, 127 | m: &[ConstraintF], 128 | ) -> Result, ark_crypto_primitives::Error> 129 | where 130 | ::ScalarField: From, 131 | { 132 | let (k, R) = Self::new_k_and_R(parameters, rng); 133 | let r = EdwardsAffine::from(R); // WIP 134 | let x_fr = C::ScalarField::from(r.x.into_repr()); 135 | 136 | let hm = poseidon_hash.hash(m)?; 137 | let hm_fr = C::ScalarField::from_le_bytes_mod_order(&to_bytes!(hm)?); // WIP TMP 138 | 139 | let s = k + (x_fr * hm_fr) * sk; 140 | Ok(Signature { s, r: R }) 141 | } 142 | 143 | // requester 144 | pub fn new_blind_params( 145 | parameters: &Parameters, 146 | rng: &mut R, 147 | signer_r: C::Affine, 148 | ) -> UserSecretData 149 | where 150 | ::ScalarField: From, 151 | { 152 | let mut u: UserSecretData = UserSecretData::new_empty(parameters); 153 | u.a = C::ScalarField::rand(rng); 154 | u.b = C::ScalarField::rand(rng); 155 | 156 | // R = aR' + bG 157 | let aR = signer_r.mul(u.a.into_repr()); 158 | let bG = parameters.generator.mul(u.b.into_repr()); 159 | u.r = aR.into_affine() + bG.into_affine(); 160 | 161 | let r = EdwardsAffine::from(u.r); // WIP 162 | let one = BigInteger256::from(1u64); 163 | let x_repr = r.x.into_repr(); 164 | let modulus = <::Params as FpParameters>::MODULUS; 165 | let modulus_repr = BigInteger256::try_from(modulus.into()).unwrap(); 166 | 167 | if !(x_repr >= one && x_repr < modulus_repr) { 168 | // TODO maybe add a counter of attempts with a limit 169 | return Self::new_blind_params(parameters, rng, signer_r); 170 | } 171 | u 172 | } 173 | 174 | pub fn blind( 175 | parameters: &Parameters, 176 | rng: &mut R, 177 | poseidon_hash: &poseidon::Poseidon>, 178 | m: &[ConstraintF], 179 | signer_r: C::Affine, 180 | ) -> Result<(C::ScalarField, UserSecretData), ark_crypto_primitives::Error> 181 | where 182 | ::ScalarField: From, 183 | { 184 | let u = Self::new_blind_params(parameters, rng, signer_r); 185 | 186 | // get X coordinate, as in new_blind_params we already checked that R.x is inside Fr and 187 | // will not overflow (giving None) 188 | let r = EdwardsAffine::from(u.r); // WIP 189 | let x_fr = C::ScalarField::from(r.x.into_repr()); 190 | 191 | // m' = a^-1 rx h(m) 192 | // TODO hash(m) must be \in Fr 193 | let hm = poseidon_hash.hash(m)?; 194 | // let hm_fr = C::ScalarField::from_repr(hm.into_repr()).unwrap(); 195 | let hm_fr = C::ScalarField::from_le_bytes_mod_order(&to_bytes!(hm)?); // WIP TMP 196 | let m_blinded = u.a.inverse().unwrap() * x_fr * hm_fr; 197 | // let m_blinded = C::ScalarField::from(u.a.inverse().unwrap() * x_fr) * hm_fr; 198 | 199 | Ok((m_blinded, u)) 200 | } 201 | 202 | pub fn unblind(s_blinded: C::ScalarField, u: &UserSecretData) -> Signature { 203 | // s = a s' + b 204 | let s = u.a * s_blinded + u.b; 205 | Signature { s, r: u.r } 206 | } 207 | 208 | pub fn verify( 209 | parameters: &Parameters, 210 | poseidon_hash: &poseidon::Poseidon>, 211 | m: &[ConstraintF], 212 | s: Signature, 213 | q: PublicKey, 214 | ) -> bool 215 | where 216 | ::ScalarField: From, 217 | { 218 | let sG = parameters.generator.mul(s.s.into_repr()); 219 | 220 | // TODO the output of hash(m) must be \in Fr 221 | let hm = poseidon_hash.hash(m).unwrap(); 222 | // let hm_fr = C::ScalarField::from_repr(hm.into_repr()).unwrap(); 223 | let hm_fr = C::ScalarField::from_le_bytes_mod_order(&to_bytes!(hm).unwrap()); // WIP TMP 224 | 225 | // check that s.R.x is in Fr 226 | let r = EdwardsAffine::from(s.r); // WIP 227 | let one = BigInteger256::from(1u64); 228 | let x_repr = r.x.into_repr(); 229 | let modulus = <::Params as FpParameters>::MODULUS; 230 | let modulus_repr = BigInteger256::try_from(modulus.into()).unwrap(); 231 | if !(x_repr >= one && x_repr < modulus_repr) { 232 | return false; 233 | } 234 | // get s.R.x 235 | let x_fr = C::ScalarField::from(r.x.into_repr()); 236 | let right = s.r + q.mul((x_fr * hm_fr).into_repr()).into_affine(); 237 | 238 | sG.into_affine() == right 239 | } 240 | } 241 | 242 | // poseidon 243 | pub fn poseidon_setup_params( 244 | curve: Curve, 245 | exp: i8, 246 | width: u8, 247 | ) -> poseidon::PoseidonParameters { 248 | let pos_data = setup_poseidon_params(curve, exp, width).unwrap(); 249 | 250 | let mds_f = bytes_matrix_to_f(&pos_data.mds); 251 | let rounds_f = bytes_vec_to_f(&pos_data.rounds); 252 | 253 | poseidon::PoseidonParameters { 254 | mds_matrix: mds_f, 255 | round_keys: rounds_f, 256 | full_rounds: pos_data.full_rounds, 257 | partial_rounds: pos_data.partial_rounds, 258 | sbox: poseidon::sbox::PoseidonSbox(pos_data.exp), 259 | width: pos_data.width, 260 | } 261 | } 262 | 263 | #[cfg(test)] 264 | mod tests { 265 | use super::*; 266 | use ark_ed_on_bn254::EdwardsProjective; 267 | pub type Fq = ark_ed_on_bn254::Fq; // base field 268 | // pub type Fr = ark_ed_on_bn254::Fr; // scalar field 269 | 270 | #[test] 271 | fn test_blind_signature_flow_native() { 272 | type S = BlindSigScheme; 273 | 274 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 275 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 276 | 277 | let mut rng = ark_std::test_rng(); 278 | 279 | let params = S::setup(); 280 | let (pk, sk) = S::keygen(¶ms, &mut rng); 281 | 282 | let (k, signer_r) = S::new_request_params(¶ms, &mut rng); 283 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 284 | 285 | let (m_blinded, u) = S::blind(¶ms, &mut rng, &poseidon_hash, &m, signer_r).unwrap(); 286 | 287 | let s_blinded = S::blind_sign(sk, k, m_blinded); 288 | 289 | let s = S::unblind(s_blinded, &u); 290 | 291 | let verified = S::verify(¶ms, &poseidon_hash, &m, s, pk); 292 | assert!(verified); 293 | } 294 | 295 | #[test] 296 | fn test_non_blind_signature() { 297 | type S = BlindSigScheme; 298 | 299 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 300 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 301 | 302 | let mut rng = ark_std::test_rng(); 303 | 304 | let params = S::setup(); 305 | let (pk, sk) = S::keygen(¶ms, &mut rng); 306 | 307 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 308 | let s = S::non_blind_sign(¶ms, &mut rng, &poseidon_hash, sk, &m).unwrap(); 309 | 310 | // verify using the same verification method used for blind-signatures 311 | let verified = S::verify(¶ms, &poseidon_hash, &m, s, pk); 312 | assert!(verified); 313 | } 314 | } 315 | -------------------------------------------------------------------------------- /src/schnorr_blind/constraints.rs: -------------------------------------------------------------------------------- 1 | use crate::schnorr_blind::{ConstraintF, Msg, Parameters, PublicKey, Signature}; 2 | use crate::{constraints::BlindSigVerifyGadget, BlindSignatureScheme}; 3 | 4 | use ark_ec::ProjectiveCurve; 5 | use ark_ed_on_bn254::{constraints::EdwardsVar, EdwardsParameters, FqParameters}; 6 | use ark_ff::{fields::Fp256, to_bytes, PrimeField}; 7 | use ark_r1cs_std::{ 8 | alloc::{AllocVar, AllocationMode}, 9 | bits::uint8::UInt8, 10 | boolean::Boolean, 11 | eq::EqGadget, 12 | fields::fp::FpVar, 13 | groups::GroupOpsBounds, 14 | prelude::CurveVar, 15 | ToBitsGadget, 16 | }; 17 | use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError}; 18 | use ark_std::ops::Mul; 19 | 20 | use core::{borrow::Borrow, marker::PhantomData}; 21 | use derivative::Derivative; 22 | 23 | // hash 24 | use arkworks_native_gadgets::poseidon as poseidon_native; 25 | use arkworks_r1cs_gadgets::poseidon::{FieldHasherGadget, PoseidonGadget}; 26 | 27 | #[derive(Derivative)] 28 | #[derivative( 29 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 30 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 31 | )] 32 | pub struct PublicKeyVar>> 33 | where 34 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 35 | { 36 | pub pub_key: GC, 37 | #[doc(hidden)] 38 | _group: PhantomData<*const C>, 39 | } 40 | 41 | impl AllocVar, ConstraintF> for PublicKeyVar 42 | where 43 | C: ProjectiveCurve, 44 | GC: CurveVar>, 45 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 46 | { 47 | fn new_variable>>( 48 | cs: impl Into>>, 49 | f: impl FnOnce() -> Result, 50 | mode: AllocationMode, 51 | ) -> Result { 52 | let pub_key = GC::new_variable(cs, f, mode)?; 53 | Ok(Self { 54 | pub_key, 55 | _group: PhantomData, 56 | }) 57 | } 58 | } 59 | 60 | #[derive(Derivative)] 61 | #[derivative( 62 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 63 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 64 | )] 65 | pub struct MsgVar>> 66 | where 67 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 68 | { 69 | m: [FpVar>; MSG_LEN], 70 | _gc: PhantomData, 71 | } 72 | impl MsgVar 73 | where 74 | C: ProjectiveCurve, 75 | GC: CurveVar>, 76 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 77 | { 78 | pub fn new(m: [FpVar>; MSG_LEN]) -> Self { 79 | Self { 80 | m, 81 | _gc: PhantomData, 82 | } 83 | } 84 | } 85 | 86 | impl AllocVar, ConstraintF> 87 | for MsgVar 88 | where 89 | C: ProjectiveCurve, 90 | GC: CurveVar>, 91 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 92 | { 93 | fn new_variable>>( 94 | cs: impl Into>>, 95 | f: impl FnOnce() -> Result, 96 | mode: AllocationMode, 97 | ) -> Result { 98 | f().and_then(|m| { 99 | let m = m.borrow(); 100 | let cs = cs.into(); 101 | let msg_vec: Vec>> = 102 | Vec::new_variable(cs, || Ok(m.clone().0), mode)?; 103 | let m: [FpVar>; MSG_LEN] = 104 | msg_vec 105 | .try_into() 106 | .unwrap_or_else(|v: Vec>>| { 107 | // WIP 108 | panic!( 109 | "Expected Vec of length: {}, actual length: {}", 110 | MSG_LEN, 111 | v.len() 112 | ) 113 | }); 114 | Ok(Self { 115 | m, 116 | _gc: PhantomData, 117 | }) 118 | }) 119 | } 120 | } 121 | 122 | #[derive(Derivative)] 123 | #[derivative( 124 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 125 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 126 | )] 127 | pub struct SignatureVar>> 128 | where 129 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 130 | { 131 | s: Vec>>, 132 | r: GC, 133 | _curve: PhantomData, 134 | } 135 | 136 | impl AllocVar, ConstraintF> for SignatureVar 137 | where 138 | C: ProjectiveCurve, 139 | GC: CurveVar>, 140 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 141 | { 142 | fn new_variable>>( 143 | cs: impl Into>>, 144 | f: impl FnOnce() -> Result, 145 | mode: AllocationMode, 146 | ) -> Result { 147 | f().and_then(|val| { 148 | let cs = cs.into(); 149 | // let s = val.borrow().s; 150 | let mut s = Vec::>>::new(); 151 | let s_bytes = to_bytes![val.borrow().s].unwrap(); 152 | #[allow(clippy::needless_range_loop)] 153 | for i in 0..s_bytes.len() { 154 | s.push(UInt8::>::new_variable( 155 | cs.clone(), 156 | || Ok(s_bytes[i]), 157 | mode, 158 | )?); 159 | } 160 | 161 | let r = GC::new_variable(cs, || Ok(val.borrow().r), mode)?; 162 | 163 | Ok(Self { 164 | s, 165 | r, 166 | _curve: PhantomData, 167 | }) 168 | }) 169 | } 170 | } 171 | 172 | #[derive(Clone)] 173 | pub struct ParametersVar>> 174 | where 175 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 176 | { 177 | generator: GC, 178 | _curve: PhantomData, 179 | } 180 | 181 | impl AllocVar, ConstraintF> for ParametersVar 182 | where 183 | C: ProjectiveCurve, 184 | GC: CurveVar>, 185 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 186 | { 187 | fn new_variable>>( 188 | cs: impl Into>>, 189 | f: impl FnOnce() -> Result, 190 | mode: AllocationMode, 191 | ) -> Result { 192 | f().and_then(|val| { 193 | let cs = cs.into(); 194 | let generator = GC::new_variable(cs, || Ok(val.borrow().generator), mode)?; 195 | Ok(Self { 196 | generator, 197 | _curve: PhantomData, 198 | }) 199 | }) 200 | } 201 | } 202 | 203 | pub struct BlindSchnorrVerifyGadget< 204 | const MSG_LEN: usize, 205 | C: ProjectiveCurve, 206 | GC: CurveVar>, 207 | > where 208 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 209 | { 210 | _params: Parameters, // TODO review if needed, maybe delete 211 | _gc: PhantomData, 212 | } 213 | 214 | impl< 215 | S: BlindSignatureScheme, 216 | const MSG_LEN: usize, 217 | C: ProjectiveCurve, 218 | GC: CurveVar>, 219 | > BlindSigVerifyGadget> for BlindSchnorrVerifyGadget 220 | where 221 | C: ProjectiveCurve, 222 | GC: CurveVar>, 223 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 224 | ark_r1cs_std::groups::curves::twisted_edwards::AffineVar< 225 | EdwardsParameters, 226 | FpVar>, 227 | >: From, 228 | ::BaseField: PrimeField, 229 | FpVar<::BaseField>: Mul>>, 230 | FpVar<::BaseField>: From>>, 231 | 232 | ParametersVar: 233 | AllocVar<::Parameters, ::BaseField>, 234 | PublicKeyVar: 235 | AllocVar<::PublicKey, ::BaseField>, 236 | SignatureVar: 237 | AllocVar<::Signature, ::BaseField>, 238 | { 239 | type ParametersVar = ParametersVar; 240 | type PublicKeyVar = PublicKeyVar; 241 | type SignatureVar = SignatureVar; 242 | type Msg = Msg; 243 | type MsgVar = MsgVar; 244 | 245 | fn verify( 246 | parameters: &ParametersVar, 247 | poseidon_hash: &PoseidonGadget>, 248 | m: &MsgVar, 249 | s: &SignatureVar, 250 | q: &PublicKeyVar, 251 | ) -> Result>, SynthesisError> { 252 | let sG = parameters 253 | .generator 254 | .scalar_mul_le(s.s.to_bits_le()?.iter())?; 255 | 256 | // Note: in a circuit that aggregates multiple verifications, the hashing step could be 257 | // done outside the signature verification, once for all 1 votes and once for all 0 votes, 258 | // saving lots of constraints 259 | let r = EdwardsVar::from(s.r.clone()); // WIP 260 | let hm = poseidon_hash.hash(&m.m)?; 261 | let to_hash = [r.x.into(), r.y.into(), hm]; 262 | let h = poseidon_hash.hash(&to_hash)?; 263 | 264 | // G * s == R + H(R, m) * Q 265 | let RHS = s.r.clone() + q.pub_key.scalar_mul_le(h.to_bits_le()?.iter())?; 266 | 267 | sG.is_eq(&RHS) 268 | } 269 | } 270 | 271 | // example of circuit using BlindSigVerifyGadget to verify a single blind signature 272 | #[derive(Clone)] 273 | pub struct BlindSigVerifyCircuit< 274 | S: BlindSignatureScheme, 275 | const MSG_LEN: usize, 276 | C: ProjectiveCurve, 277 | GC: CurveVar>, 278 | > where 279 | ::BaseField: PrimeField, 280 | { 281 | _s: PhantomData, 282 | _group: PhantomData<*const GC>, 283 | pub params: Parameters, 284 | pub poseidon_hash_native: poseidon_native::Poseidon>, 285 | pub signature: Option>, 286 | pub pub_key: Option>, 287 | pub message: Option>, 288 | } 289 | 290 | impl< 291 | S: BlindSignatureScheme, 292 | const MSG_LEN: usize, 293 | C: ProjectiveCurve, 294 | GC: CurveVar>, 295 | > ConstraintSynthesizer> for BlindSigVerifyCircuit 296 | where 297 | C: ProjectiveCurve, 298 | GC: CurveVar>, 299 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 300 | ark_r1cs_std::groups::curves::twisted_edwards::AffineVar< 301 | EdwardsParameters, 302 | FpVar>, 303 | >: From, 304 | ::BaseField: PrimeField, 305 | FpVar<::BaseField>: Mul>>, 306 | FpVar<::BaseField>: From>>, 307 | 308 | ParametersVar: 309 | AllocVar<::Parameters, ::BaseField>, 310 | PublicKeyVar: 311 | AllocVar<::PublicKey, ::BaseField>, 312 | SignatureVar: 313 | AllocVar<::Signature, ::BaseField>, 314 | 315 | Parameters: Borrow<::Parameters>, 316 | PublicKey: Borrow<::PublicKey>, 317 | Signature: Borrow<::Signature>, 318 | { 319 | #[tracing::instrument(target = "r1cs", skip(self, cs))] 320 | fn generate_constraints( 321 | self, 322 | cs: ConstraintSystemRef>, 323 | ) -> Result<(), SynthesisError> { 324 | let parameters = 325 | ParametersVar::new_constant(ark_relations::ns!(cs, "parameters"), self.params)?; 326 | 327 | let pub_key = 328 | PublicKeyVar::::new_input(ark_relations::ns!(cs, "public key"), || { 329 | self.pub_key.ok_or(SynthesisError::AssignmentMissing) 330 | })?; 331 | let m = MsgVar::::new_input(ark_relations::ns!(cs, "message"), || { 332 | self.message.ok_or(SynthesisError::AssignmentMissing) 333 | })?; 334 | let signature = 335 | SignatureVar::::new_witness(ark_relations::ns!(cs, "signature"), || { 336 | self.signature.ok_or(SynthesisError::AssignmentMissing) 337 | })?; 338 | #[allow(clippy::redundant_clone)] 339 | let poseidon_hash = PoseidonGadget::>::from_native( 340 | &mut cs.clone(), 341 | self.poseidon_hash_native, 342 | ) 343 | .unwrap(); 344 | 345 | let v = as BlindSigVerifyGadget< 346 | S, 347 | ConstraintF, 348 | >>::verify(¶meters, &poseidon_hash, &m, &signature, &pub_key)?; 349 | v.enforce_equal(&Boolean::TRUE) 350 | } 351 | } 352 | 353 | #[cfg(test)] 354 | mod test { 355 | use super::*; 356 | use crate::schnorr_blind::{poseidon_setup_params, SchnorrBlindSig}; 357 | use crate::BlindSignatureScheme; 358 | use ark_ed_on_bn254::constraints::EdwardsVar as BabyJubJubVar; 359 | use ark_ed_on_bn254::EdwardsProjective as BabyJubJub; 360 | 361 | use arkworks_native_gadgets::poseidon; 362 | use arkworks_utils::Curve; 363 | 364 | use ark_relations::r1cs::ConstraintSystem; 365 | 366 | type Fq = ::BaseField; 367 | // type Fr = ::ScalarField; 368 | type S = SchnorrBlindSig; 369 | 370 | fn generate_single_sig_native_data( 371 | poseidon_hash: &poseidon::Poseidon, 372 | ) -> ( 373 | Parameters, 374 | PublicKey, 375 | Msg<3, BabyJubJub>, 376 | Signature, 377 | ) { 378 | let mut rng = ark_std::test_rng(); 379 | let params = S::setup(poseidon_hash); 380 | let (pk, sk) = S::keygen(¶ms, &mut rng); 381 | let (k, signer_r) = S::new_request_params(¶ms, &mut rng); 382 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 383 | let (m_blinded, u) = S::blind(¶ms, &mut rng, &m, pk, signer_r).unwrap(); 384 | let s_blinded = S::blind_sign(sk, k, m_blinded); 385 | let s = S::unblind(s_blinded, &u); 386 | let verified = S::verify(¶ms, &m, s.clone(), pk); 387 | assert!(verified); 388 | (params, pk, Msg(m), s) 389 | } 390 | 391 | #[test] 392 | fn test_single_verify() { 393 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 394 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 395 | const MSG_LEN: usize = 3; 396 | 397 | // create signature using native-rust lib 398 | let (params, pk, m, s) = generate_single_sig_native_data(&poseidon_hash); 399 | 400 | // use the constraint system to verify the signature 401 | let cs = ConstraintSystem::::new_ref(); 402 | 403 | let params_var = 404 | ParametersVar::::new_constant(cs.clone(), params).unwrap(); 405 | let signature_var = 406 | SignatureVar::::new_witness(cs.clone(), || Ok(&s)).unwrap(); 407 | let pk_var = 408 | PublicKeyVar::::new_witness(cs.clone(), || Ok(&pk)).unwrap(); 409 | let m_var = MsgVar::::new_witness(cs.clone(), || Ok(m)) 410 | .unwrap(); 411 | let poseidon_hash_var = 412 | PoseidonGadget::::from_native(&mut cs.clone(), poseidon_hash).unwrap(); 413 | 414 | let valid_sig = 415 | as BlindSigVerifyGadget< 416 | S, 417 | ConstraintF, 418 | >>::verify( 419 | ¶ms_var, 420 | &poseidon_hash_var, 421 | &m_var, 422 | &signature_var, 423 | &pk_var, 424 | ) 425 | .unwrap(); 426 | valid_sig.enforce_equal(&Boolean::::TRUE).unwrap(); 427 | assert!(cs.is_satisfied().unwrap()); 428 | } 429 | 430 | #[test] 431 | fn test_single_verify_constraint_system() { 432 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 433 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 434 | const MSG_LEN: usize = 3; 435 | 436 | // create signature using native-rust lib 437 | let (params, pk, m, s) = generate_single_sig_native_data(&poseidon_hash); 438 | 439 | // use the constraint system to verify the signature 440 | let circuit = BlindSigVerifyCircuit:: { 441 | params, 442 | poseidon_hash_native: poseidon_hash.clone(), 443 | signature: Some(s), 444 | pub_key: Some(pk), 445 | message: Some(m), 446 | _group: PhantomData, 447 | _s: PhantomData, 448 | }; 449 | let cs = ConstraintSystem::::new_ref(); 450 | circuit.generate_constraints(cs.clone()).unwrap(); 451 | let is_satisfied = cs.is_satisfied().unwrap(); 452 | assert!(is_satisfied); 453 | println!("num_constraints={:?}", cs.num_constraints()); 454 | } 455 | } 456 | -------------------------------------------------------------------------------- /src/schnorr_blind/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | #![allow(clippy::many_single_char_names)] 3 | 4 | use crate::BlindSignatureScheme; 5 | 6 | // #[cfg(feature="r1cs")] 7 | pub mod constraints; 8 | 9 | use ark_ec::{models::twisted_edwards_extended::GroupAffine, AffineCurve, ProjectiveCurve}; 10 | 11 | use ark_ff::{to_bytes, BigInteger256, Field, Fp256, FpParameters, PrimeField}; 12 | 13 | use ark_std::marker::PhantomData; 14 | use ark_std::{rand::Rng, UniformRand}; 15 | use derivative::Derivative; 16 | 17 | // hash 18 | use arkworks_native_gadgets::poseidon; 19 | use arkworks_native_gadgets::poseidon::FieldHasher; 20 | use arkworks_utils::{ 21 | bytes_matrix_to_f, bytes_vec_to_f, poseidon_params::setup_poseidon_params, Curve, 22 | }; 23 | 24 | // WIP 25 | use ark_ed_on_bn254::{EdwardsAffine, EdwardsParameters, FqParameters}; 26 | 27 | pub type ConstraintF = <::BaseField as Field>::BasePrimeField; 28 | pub type SecretKey = ::ScalarField; 29 | pub type PublicKey = ::Affine; 30 | pub type BlindedSignature = ::ScalarField; 31 | 32 | #[derive(Clone, Debug)] 33 | pub struct Msg(pub [ConstraintF; MSG_LEN]); 34 | 35 | #[derive(Clone, Default, Debug)] 36 | pub struct Signature { 37 | s: C::ScalarField, // ScalarField == Fr 38 | r: ::Affine, 39 | } 40 | 41 | #[derive(Clone, Default, Debug)] 42 | pub struct UserSecretData { 43 | alpha: C::ScalarField, 44 | beta: C::ScalarField, 45 | R: C::Affine, 46 | } 47 | impl UserSecretData { 48 | fn new_empty(parameters: &Parameters) -> Self { 49 | UserSecretData { 50 | alpha: C::ScalarField::from(0_u32), 51 | beta: C::ScalarField::from(0_u32), 52 | R: parameters.generator, // WIP 53 | } 54 | } 55 | } 56 | 57 | #[derive(Derivative)] 58 | #[derivative(Clone(bound = "C: ProjectiveCurve"), Debug)] 59 | pub struct Parameters { 60 | pub generator: C::Affine, 61 | pub poseidon_hash: poseidon::Poseidon>, 62 | // pub poseidon_hash: Box>>, // WIP 63 | } 64 | 65 | pub struct SchnorrBlindSig { 66 | _group: PhantomData, 67 | } 68 | 69 | impl BlindSignatureScheme for SchnorrBlindSig 70 | where 71 | C::ScalarField: PrimeField, 72 | GroupAffine: From<::Affine>, // WIP 73 | ::ScalarField: From, 74 | <::BaseField as Field>::BasePrimeField: From>, 75 | { 76 | type Parameters = Parameters; 77 | type Fq = C::BaseField; 78 | type Fr = C::ScalarField; 79 | type ConstraintF = ConstraintF; // WIP merge it with Fq 80 | type PointAffine = C::Affine; 81 | type SecretKey = SecretKey; 82 | type PublicKey = PublicKey; 83 | // type Msg = Msg; 84 | type BlindedSignature = BlindedSignature; 85 | type Signature = Signature; 86 | type UserSecretData = UserSecretData; 87 | 88 | fn setup(poseidon_hash: &poseidon::Poseidon>) -> Self::Parameters { 89 | let generator = C::prime_subgroup_generator().into(); 90 | Parameters { 91 | generator, 92 | poseidon_hash: poseidon_hash.clone(), // WIP 93 | } 94 | } 95 | 96 | // signer 97 | fn keygen( 98 | parameters: &Self::Parameters, 99 | rng: &mut R, 100 | ) -> (Self::PublicKey, Self::SecretKey) { 101 | let secret_key = C::ScalarField::rand(rng); 102 | let public_key = parameters.generator.mul(secret_key).into(); 103 | (public_key, secret_key) 104 | } 105 | 106 | fn new_request_params( 107 | parameters: &Self::Parameters, 108 | rng: &mut R, 109 | ) -> (Self::Fr, Self::PointAffine) { 110 | let r = C::ScalarField::rand(rng); 111 | let R_ = parameters.generator.mul(r).into(); 112 | (r, R_) 113 | } 114 | 115 | fn blind_sign(sk: SecretKey, r: Self::Fr, m_blinded: Self::Fr) -> Self::BlindedSignature { 116 | r + m_blinded * sk 117 | } 118 | 119 | // non_blind_sign performs a non-blind signature, which can be verified with the same check 120 | // than a blind-signature 121 | fn non_blind_sign( 122 | parameters: &Self::Parameters, 123 | rng: &mut R, 124 | sk: Self::SecretKey, 125 | m: &[ConstraintF], 126 | ) -> Result, ark_crypto_primitives::Error> 127 | where 128 | ::ScalarField: From, 129 | <::BaseField as Field>::BasePrimeField: From>, 130 | { 131 | let (r, R) = Self::new_k_and_R(parameters, rng); 132 | let R_ed = EdwardsAffine::from(R); // WIP 133 | 134 | let hm = parameters.poseidon_hash.hash(m)?; 135 | let to_hash: [ConstraintF; 3] = [R_ed.x.into(), R_ed.y.into(), hm]; 136 | let h = parameters.poseidon_hash.hash(&to_hash)?; 137 | let h_fr = C::ScalarField::from_le_bytes_mod_order(&to_bytes!(h)?); // WIP TMP 138 | 139 | let s = r + h_fr * sk; 140 | Ok(Signature { s, r: R }) 141 | } 142 | 143 | fn blind( 144 | parameters: &Self::Parameters, 145 | rng: &mut R, 146 | m: &[Self::ConstraintF], 147 | signer_pk: Self::PublicKey, 148 | signer_r: Self::PointAffine, 149 | ) -> Result<(Self::Fr, Self::UserSecretData), ark_crypto_primitives::Error> 150 | where 151 | ::ScalarField: From, 152 | <::BaseField as Field>::BasePrimeField: From>, 153 | { 154 | let u = Self::new_blind_params(parameters, rng, signer_pk, signer_r); 155 | 156 | // get X coordinate, as in new_blind_params we already checked that R.x is inside Fr and 157 | // will not overflow (giving None) 158 | let r = EdwardsAffine::from(u.R); // WIP 159 | 160 | // m' = H(R, m) + beta 161 | // TODO hash(R, m) must be \in Fr 162 | let hm_0 = parameters.poseidon_hash.hash(m)?; 163 | let to_hash: [ConstraintF; 3] = [r.x.into(), r.y.into(), hm_0]; 164 | let h = parameters.poseidon_hash.hash(&to_hash)?; 165 | let h_fr = C::ScalarField::from_le_bytes_mod_order(&to_bytes!(h)?); // WIP TMP 166 | let m_blinded = h_fr + u.beta; 167 | 168 | Ok((m_blinded, u)) 169 | } 170 | 171 | fn unblind(s_blinded: Self::Fr, u: &Self::UserSecretData) -> Self::Signature { 172 | // s = s' + alpha 173 | let s = s_blinded + u.alpha; 174 | Signature { s, r: u.R } 175 | } 176 | 177 | fn verify( 178 | parameters: &Self::Parameters, 179 | m: &[Self::ConstraintF], 180 | s: Self::Signature, 181 | q: Self::PublicKey, 182 | ) -> bool 183 | where 184 | ::ScalarField: From, 185 | <::BaseField as Field>::BasePrimeField: From>, 186 | { 187 | let sG = parameters.generator.mul(s.s.into_repr()); 188 | 189 | let r = EdwardsAffine::from(s.r); // WIP: let r = s.r.into_affine(); 190 | 191 | // TODO the output of hash(R, m) must be \in Fr 192 | let hm_0 = parameters.poseidon_hash.hash(m).unwrap(); 193 | let to_hash: [ConstraintF; 3] = [r.x.into(), r.y.into(), hm_0]; 194 | let h = parameters.poseidon_hash.hash(&to_hash).unwrap(); 195 | let h_fr = C::ScalarField::from_le_bytes_mod_order(&to_bytes!(h).unwrap()); // WIP TMP 196 | 197 | // TODO the output of hash(R, m) must be \in Fr 198 | let one = BigInteger256::from(1u64); 199 | let x_repr = r.x.into_repr(); 200 | let modulus = <::Params as FpParameters>::MODULUS; 201 | let modulus_repr = BigInteger256::try_from(modulus.into()).unwrap(); 202 | if !(x_repr >= one && x_repr < modulus_repr) { 203 | return false; 204 | } 205 | let right = s.r + q.mul(h_fr.into_repr()).into_affine(); 206 | 207 | sG.into_affine() == right 208 | } 209 | } 210 | 211 | impl SchnorrBlindSig 212 | where 213 | C::ScalarField: PrimeField, 214 | GroupAffine: From<::Affine>, // WIP 215 | { 216 | // new_k_and_R returns a new k \in Fr, and R=k * G, such that R.x \in Fr 217 | fn new_k_and_R(parameters: &Parameters, rng: &mut R) -> (C::ScalarField, C::Affine) 218 | where 219 | ::ScalarField: From, 220 | { 221 | // TODO, for Schnorr, the H(R, m) needs to be \in Fr, not R.x 222 | let k = C::ScalarField::rand(rng); 223 | 224 | let R: C::Affine = parameters.generator.mul(k.into_repr()).into(); 225 | let r = EdwardsAffine::from(R); // WIP 226 | 227 | let one = BigInteger256::from(1u64); 228 | let x_repr = r.x.into_repr(); 229 | let modulus = <::Params as FpParameters>::MODULUS; 230 | let modulus_repr = BigInteger256::try_from(modulus.into()).unwrap(); 231 | 232 | if !(x_repr >= one && x_repr < modulus_repr) { 233 | // TODO maybe add a counter of attempts with a limit 234 | return Self::new_k_and_R(parameters, rng); 235 | } 236 | 237 | (k, R) 238 | } 239 | 240 | // requester 241 | fn new_blind_params( 242 | parameters: &Parameters, 243 | rng: &mut R, 244 | signer_pk: PublicKey, 245 | signer_r: C::Affine, 246 | ) -> UserSecretData 247 | where 248 | ::ScalarField: From, 249 | { 250 | let mut u: UserSecretData = UserSecretData::new_empty(parameters); 251 | u.alpha = C::ScalarField::rand(rng); 252 | u.beta = C::ScalarField::rand(rng); 253 | 254 | // R = R' + alpha * G + beta * X 255 | let alphaG = parameters.generator.mul(u.alpha.into_repr()); 256 | let betaPk = signer_pk.mul(u.beta.into_repr()); 257 | u.R = signer_r + alphaG.into_affine() + betaPk.into_affine(); 258 | 259 | let R = EdwardsAffine::from(u.R); // WIP 260 | let one = BigInteger256::from(1u64); 261 | let x_repr = R.x.into_repr(); 262 | let modulus = <::Params as FpParameters>::MODULUS; 263 | let modulus_repr = BigInteger256::try_from(modulus.into()).unwrap(); 264 | 265 | if !(x_repr >= one && x_repr < modulus_repr) { 266 | // TODO maybe add a counter of attempts with a limit 267 | return Self::new_blind_params(parameters, rng, signer_pk, signer_r); 268 | } 269 | u 270 | } 271 | } 272 | 273 | // poseidon 274 | pub fn poseidon_setup_params( 275 | curve: Curve, 276 | exp: i8, 277 | width: u8, 278 | ) -> poseidon::PoseidonParameters { 279 | let pos_data = setup_poseidon_params(curve, exp, width).unwrap(); 280 | 281 | let mds_f = bytes_matrix_to_f(&pos_data.mds); 282 | let rounds_f = bytes_vec_to_f(&pos_data.rounds); 283 | 284 | poseidon::PoseidonParameters { 285 | mds_matrix: mds_f, 286 | round_keys: rounds_f, 287 | full_rounds: pos_data.full_rounds, 288 | partial_rounds: pos_data.partial_rounds, 289 | sbox: poseidon::sbox::PoseidonSbox(pos_data.exp), 290 | width: pos_data.width, 291 | } 292 | } 293 | 294 | #[cfg(test)] 295 | mod tests { 296 | use super::*; 297 | use ark_ed_on_bn254::EdwardsProjective; 298 | pub type Fq = ark_ed_on_bn254::Fq; // base field 299 | // pub type Fr = ark_ed_on_bn254::Fr; // scalar field 300 | 301 | #[test] 302 | fn test_blind_signature_flow_native() { 303 | type S = SchnorrBlindSig; 304 | 305 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 306 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 307 | 308 | let mut rng = ark_std::test_rng(); 309 | 310 | let params = S::setup(&poseidon_hash); 311 | let (pk, sk) = S::keygen(¶ms, &mut rng); 312 | 313 | let (r, signer_R) = S::new_request_params(¶ms, &mut rng); 314 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 315 | 316 | let (m_blinded, u) = S::blind(¶ms, &mut rng, &m, pk, signer_R).unwrap(); 317 | 318 | let s_blinded = S::blind_sign(sk, r, m_blinded); 319 | 320 | let s = S::unblind(s_blinded, &u); 321 | 322 | let verified = S::verify(¶ms, &m, s, pk); 323 | assert!(verified); 324 | } 325 | 326 | #[test] 327 | fn test_non_blind_signature() { 328 | type S = SchnorrBlindSig; 329 | 330 | let poseidon_params = poseidon_setup_params::(Curve::Bn254, 5, 4); 331 | let poseidon_hash = poseidon::Poseidon::new(poseidon_params); 332 | 333 | let mut rng = ark_std::test_rng(); 334 | 335 | let params = S::setup(&poseidon_hash); 336 | let (pk, sk) = S::keygen(¶ms, &mut rng); 337 | 338 | let m = [Fq::from(1234), Fq::from(5689), Fq::from(3456)]; 339 | let s = S::non_blind_sign(¶ms, &mut rng, sk, &m).unwrap(); 340 | 341 | // verify using the same verification method used for blind-signatures 342 | let verified = S::verify(¶ms, &m, s, pk); 343 | assert!(verified); 344 | } 345 | } 346 | --------------------------------------------------------------------------------