├── .gitignore ├── LICENCE ├── README.md ├── TIMELINE.md ├── demo.py ├── docs ├── ath-floss-pres.tex ├── gsoc-summit-pres.tex ├── metrics.bib ├── metrics.tex ├── pdf │ ├── ath-floss-pres.pdf │ └── metrics.pdf └── zeus-chart.eps ├── flz16 ├── __init__.py ├── crs.py ├── ilin2.py ├── prover.py ├── tests │ ├── __init__.py │ ├── test_prover_verifier.py │ └── test_utils.py ├── utils.py └── verifier.py ├── libffpy ├── __init__.py ├── demo.py ├── libff_wrapper.cpp ├── libff_wrapper.h ├── libffpy.pxd ├── libffpy.pyx ├── setup.py └── tests │ ├── __init__.py │ ├── test_bignum.py │ ├── test_g1.py │ ├── test_g2.py │ └── test_gt.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.pyc 3 | *.so 4 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Implementation of a Re-Encryption Mix-Net 2 | ====================================================== 3 | 4 | This module implements the re-encryption mix-net 5 | presented by Fauzi et al. in their paper: 6 | ["A Shuffle Argument Secure in the Generic 7 | Model"](https://eprint.iacr.org/2016/866.pdf). 8 | 9 | The motivation behind this implementation is 10 | to replace the mix-net used by 11 | the e-voting application, [Zeus](https://github.com/grnet/zeus) 12 | in favor of a faster one. 13 | However it can be used by anyone that needs a 14 | mix-net implementation. 15 | That is, 16 | apart from e-voting, 17 | the mix-net can be used for other tasks such as surveys 18 | and the collection of data from various IoT 19 | (Internet of Things) devices. 20 | 21 | The implementation was based on an existing 22 | [prototype](https://github.com/grnet/ac16) 23 | of the same re-encryption mix-net. 24 | 25 | 26 | Python 27 | ====== 28 | 29 | The module requires **Python 2.7**. 30 | 31 | 32 | Installing Dependencies 33 | ======================= 34 | 35 | 1. Install [libsnark](https://github.com/scipr-lab/libsnark) following 36 | the instructions on its GitHub page. 37 | 2. Install [libff](https://github.com/scipr-lab/libff) following 38 | the instructions on its GitHub page. 39 | 3. Install package dependencies 40 | ``` 41 | sudo apt-get install python python-pip 42 | ``` 43 | 4. Install Cython 44 | ``` 45 | pip install cython 46 | ``` 47 | 48 | Dependencies Notes 49 | ================== 50 | 51 | We faced some issues while installing libff and libsnark on Ubuntu 16.04 LTS. 52 | If the installation process doesn't work try the following: 53 | 54 | - Install libsnark on `/usr/` with 55 | ``` 56 | make install PREFIX=/usr 57 | ``` 58 | after compiling it. 59 | 60 | - After installing libff, inside the cloned repo copy 61 | the third party libraries to the local includes. 62 | ``` 63 | cp -R depends /usr/local/include/ 64 | ``` 65 | 66 | - Add to the libff library (before compiling it) the `-fPIC` 67 | flag on CMakeLists. Specifically on the 68 | `CMakeLists.txt` file add `-fPIC` to the existing flags on `CMAKE_CXX_FLAGS` 69 | and `CMAKE_EXE_LINKER_FLAGS`. 70 | 71 | - In order to avoid libff outputting profiling info change the variables 72 | `inhibit_profiling_info` and `inhibit_profiling_counters` to `true` on 73 | `libff/common/profiling.cpp` before compiling the library. 74 | 75 | Installing libffpy 76 | ================== 77 | 78 | Inside the libffpy folder run: 79 | 80 | ``` 81 | python setup.py install 82 | ``` 83 | 84 | Installing Package 85 | ================== 86 | 87 | On the root directory run: 88 | 89 | ``` 90 | python setup.py install 91 | ``` 92 | 93 | Implementation 94 | ============== 95 | 96 | libffpy 97 | ------- 98 | 99 | The mix-net proposed by Fauzi et al requires elliptic curve computations. 100 | A suitable library that provides support for elliptic curve computations 101 | is [libff](https://github.com/scipr-lab/libff). 102 | 103 | Since libff is implemented in C++ we used Cython to create a wrapper 104 | for some of the features of libff. The Cython wrapper can be found in 105 | the folder `libffpy`. While not a complete wrapper, it can be 106 | used independently by anyone that needs the features provided by 107 | libff. 108 | 109 | The curve we used is bn128 and libff implements 110 | the [ate pairing](https://github.com/herumi/ate-pairing) 111 | for its bilinear pairing computations. 112 | 113 | Mix-Net Module 114 | -------------- 115 | 116 | The mix-net is implemented using Python. It requires a working 117 | installation of libffpy. 118 | 119 | 120 | Challenges 121 | ========== 122 | 123 | - **Elliptic Curve Multiplications**: The real bottleneck of the prototype 124 | is its performance. The prototype's 125 | performance was much slower than other implementations in C++. After some 126 | specific metrics we identified that the issue was that the multiplications 127 | on the elliptic curve elements were slow. The library implementing those 128 | multiplications was [bplib](https://github.com/gdanezis/bplib/). 129 | 130 | - **bplip vs libff**: Since the bottleneck were the multiplications on the elliptic 131 | curve, we looked at replacements for bplib. One such replacement is libff. bplib 132 | uses libraries provided by OpenSSL for its elliptic curve computations. 133 | We defined specific metrics and compared the underlying C code of bplib 134 | with libff. The results showed that libff was indeed faster than OpenSSL, 135 | so we moved forward with the implementation of libffpy. 136 | 137 | TODOs 138 | ===== 139 | 140 | - **CRS (Common Reference String)**: In order for the mix-net to be truly decentralized and anonymous 141 | there needs to be a mechanism to create the CRS anonymously. 142 | 143 | - **Integration with Zeus** 144 | 145 | Usage 146 | ===== 147 | 148 | There exists a demo in the file `demo.py` of the root directory 149 | that shows the basic workflow of the mix-net module. 150 | 151 | Organization 152 | ============ 153 | 154 | This [project](https://summerofcode.withgoogle.com/projects/#6269134514946048) 155 | was developed as part of the [Google Summer of Code]( 156 | https://summerofcode.withgoogle.com) program. 157 | 158 | Student: Vitalis Salis 159 | 160 | Mentors: 161 | 162 | - [Dimitris Mitropoulos](http://dimitro.gr/) 163 | - Georgios Tsoukalas 164 | - [Panos Louridas](https://istlab.dmst.aueb.gr/content/members/m_louridas.html) 165 | 166 | Organization: [Open Technologies Alliance - GFOSS](https://gfoss.eu/) 167 | -------------------------------------------------------------------------------- /TIMELINE.md: -------------------------------------------------------------------------------- 1 | Timeline 2 | ======== 3 | 4 | * Week 1 - Week 2: Experiment with the existing mix-net implementation on Zeus. 5 | See how the mix-net works and study related papers. Work on the 6 | implementation of a Common Reference String. 7 | 8 | * Week 3 - Week 4: Identify which of the existing mix-net publications are fit 9 | to be implemented. Examine all possible candidates and after some discussion 10 | with my mentor decide which one fits our needs. 11 | 12 | * Week 5 - Week 10: Implement a new re-encryption mix-net prototype based on 13 | the work of Weeks 1-4. 14 | 15 | * Week 10 - Week 12: Test the prototype and deploy to production. Do various 16 | checks in real-time scenarios. 17 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | import datetime, sys 2 | 3 | from flz16.crs import CRS 4 | from flz16.prover import Prover 5 | from flz16.verifier import Verifier 6 | from flz16.utils import make_s_randoms, random_permutation,\ 7 | encrypt_messages, make_tables, decrypt_messages 8 | 9 | n = int(sys.argv[1]) 10 | 11 | start = datetime.datetime.now() 12 | 13 | crs = CRS(n) 14 | s_randoms = make_s_randoms(n, crs.order) 15 | sigma = random_permutation(n) 16 | ciphertexts = encrypt_messages(crs.order, crs.pk1, crs.pk2, list(range(n))) 17 | prover = Prover(crs) 18 | proof = prover.prove(n, ciphertexts, sigma, s_randoms) 19 | 20 | verifier = Verifier(crs) 21 | print verifier.verify(ciphertexts, proof) 22 | 23 | TABLES = make_tables(crs.pk1, crs.pk2, crs.n) 24 | shuffled_ms = decrypt_messages(crs.gamma, TABLES, proof['shuffled_ciphertexts']) 25 | 26 | end = datetime.datetime.now() 27 | print "ellapsed: %s" % (end - start) 28 | -------------------------------------------------------------------------------- /docs/ath-floss-pres.tex: -------------------------------------------------------------------------------- 1 | \documentclass{beamer} 2 | 3 | \usepackage[utf8]{inputenc} 4 | \usepackage{graphicx} 5 | \usepackage{biblatex} 6 | 7 | \title{Re-Encryption Mix-Net Module} 8 | \author{Vitalis Salis} 9 | \date{2017} 10 | 11 | \begin{document} 12 | \frame{\titlepage} 13 | 14 | \begin{frame} 15 | \frametitle{Zeus} 16 | \begin{itemize} 17 | \item Web-based open-audit e-voting system. 18 | \item Open source.\footnote{\url{https://github.com/grnet/zeus}} 19 | \item Derived from Helios\footnote{ 20 | \url{https://github.com/benadida/helios} 21 | }. 22 | \item Uses the Sako-Kilian re-encryption mix-net for anonymity. 23 | \item Already used by various institutions for elections. 24 | \end{itemize} 25 | \end{frame} 26 | 27 | \begin{frame} 28 | \begin{figure} 29 | \centering 30 | \includegraphics[width=12cm,height=7cm,keepaspectratio]{zeus-chart.eps} 31 | \caption{Registered and actual voters on Zeus.} 32 | \end{figure} 33 | \end{frame} 34 | 35 | \begin{frame} 36 | \frametitle{The Issue} 37 | \begin{itemize} 38 | \item The re-encryption mix-net used by Zeus is impractical. 39 | \item It requires a lot of costly, performance wise, cryptographic. 40 | operations, leading to longer times to get the election results. 41 | \item I.e for 10,000 votes the mixnet might take up to 8 hours! 42 | \item Our goal is to create an open source Python module that 43 | implements a faster re-encryption mix-net for applications 44 | requiring anonymity. 45 | \end{itemize} 46 | \end{frame} 47 | 48 | \begin{frame} 49 | \frametitle{Faster Mix-Nets} 50 | \begin{itemize} 51 | \item In order to overcome this issue, we've been looking on new 52 | research about mix-nets that guarantee faster performance. 53 | \item The best candidate we identified is proposed by Fauzi et al, 54 | from the University of Tartu.\footnote{ 55 | \url{https://eprint.iacr.org/2016/866} 56 | }. 57 | \item The mix-net is based on elliptic curves. 58 | \end{itemize} 59 | \end{frame} 60 | 61 | \begin{frame} 62 | \frametitle{Existing Prototypes} 63 | \begin{itemize} 64 | \item A Python prototype that implements the mix-net proposed by 65 | Fauzi et al, was developed by GRNET\footnote{ 66 | \url{https://github.com/grnet/ac16/} 67 | }. 68 | \item Still, the prototype wasn't satisfying. 69 | \item The main issue we identified was that multiplications on the 70 | elliptic curve structure are slow. 71 | \item The library implementing those multiplications is OpenSSL. 72 | \item A good replacement for OpenSSL is a similar library, 73 | libff.\footnote{\url{https://github.com/scipr-lab/libff}} 74 | \end{itemize} 75 | \end{frame} 76 | 77 | \begin{frame} 78 | \frametitle{Metrics} 79 | \begin{itemize} 80 | \item In order to compare these libraries we have defined specific 81 | metrics. 82 | \item Our profiling involved a test case where we performed 83 | thousands of multiplications from C on both libraries:\newline 84 | $g ^ \rho$ 85 | where $g$ is the generator of the elliptic curve group and 86 | $\rho$ is a 256 bit number. 87 | \item libff yielded up to 6 times better performance than OpenSSL. 88 | \item So, we moved forward with the implementation of a libff 89 | wrapper for Python. 90 | \end{itemize} 91 | \end{frame} 92 | 93 | \begin{frame} 94 | \frametitle{Wrapping libff With Cython} 95 | \begin{itemize} 96 | \item libff is implemented in C++. 97 | \item So it needs to be wrapped by Python in order to be used as a 98 | Python module. 99 | \item No such wrapper exists, so we set out to create one. 100 | \item We identified that Cython is the best candidate for wrapping 101 | libff. 102 | \item The wrapper exists as a separate open source module 103 | so it can be used by other Python projects that need to use libff. 104 | \end{itemize} 105 | \end{frame} 106 | 107 | \begin{frame} 108 | \frametitle{Comparing Wrappers} 109 | \begin{itemize} 110 | \item After creating the Cython wrapper for libff, in order to 111 | verify that it is indeed better than the Python wrapper for 112 | OpenSSL, we defined specific metrics. 113 | \item Our profiling involved a test case where we performed 114 | thousands of multiplications from Python on both wrappers. 115 | \item The results validated our hypothesis, so we'll use the Cython 116 | wrapper for the implementation of the re-encryption mix-net module. 117 | \end{itemize} 118 | \end{frame} 119 | 120 | \begin{frame} 121 | \frametitle{Future Work} 122 | \begin{itemize} 123 | \item Python Module 124 | \item Integration with Zeus 125 | \item Testing 126 | \end{itemize} 127 | \end{frame} 128 | \begin{frame} 129 | \center{\url{https://github.com/eellak/gsoc17module-zeus}} 130 | \end{frame} 131 | \end{document} 132 | -------------------------------------------------------------------------------- /docs/gsoc-summit-pres.tex: -------------------------------------------------------------------------------- 1 | \documentclass{beamer} 2 | 3 | \usepackage[utf8]{inputenc} 4 | \usepackage{graphicx} 5 | \usepackage{biblatex} 6 | 7 | \title{Re-Encryption Mix-Net Module} 8 | \date{2017} 9 | 10 | \begin{document} 11 | \frame{\titlepage} 12 | 13 | \begin{frame} 14 | \frametitle{Zeus} 15 | \begin{itemize} 16 | \item Web-based open-audit e-voting system. 17 | \item Open source.\footnote{\url{https://github.com/grnet/zeus}} 18 | \item Derived from Helios\footnote{ 19 | \url{https://github.com/benadida/helios} 20 | }. 21 | \item Uses the Sako-Kilian re-encryption mix-net for anonymity. 22 | \item Already used by various institutions for elections. 23 | \item \textbf{Aim}: Implement a faster re-encryption mix-net for better 24 | performance. 25 | \end{itemize} 26 | \end{frame} 27 | 28 | \begin{frame} 29 | \begin{figure} 30 | \centering 31 | \includegraphics[width=12cm,height=7cm,keepaspectratio]{zeus-chart.eps} 32 | \caption{Registered and actual voters on Zeus.} 33 | \end{figure} 34 | \end{frame} 35 | 36 | \begin{frame} 37 | \frametitle{The Issue} 38 | \begin{itemize} 39 | \item The re-encryption mix-net used by Zeus is impractical. 40 | \item It requires a lot of costly, performance wise, cryptographic. 41 | operations, leading to longer times to get the election results. 42 | \item I.e for 10,000 votes the mixnet might take up to 8 hours! 43 | \item Our goal is to create an open source Python module that 44 | implements a faster re-encryption mix-net for applications 45 | requiring anonymity. 46 | \end{itemize} 47 | \end{frame} 48 | 49 | \begin{frame} 50 | \frametitle{Faster Mix-Nets} 51 | \begin{itemize} 52 | \item In order to overcome this issue, we've been looking on new 53 | research about mix-nets that guarantee faster performance. 54 | \item The best candidate we identified is proposed by Fauzi et al, 55 | from the University of Tartu.\footnote{ 56 | \url{https://eprint.iacr.org/2016/866} 57 | }. 58 | \item The mix-net is based on elliptic curves. 59 | \end{itemize} 60 | \end{frame} 61 | 62 | \begin{frame} 63 | \frametitle{Existing Prototypes} 64 | \begin{itemize} 65 | \item A Python prototype that implements the mix-net proposed by 66 | Fauzi et al, was developed by GRNET\footnote{ 67 | \url{https://github.com/grnet/ac16/} 68 | }. 69 | \item Still, the prototype wasn't satisfying. 70 | \item The main issue we identified was that multiplications on the 71 | elliptic curve structure are slow. 72 | \item The library implementing those multiplications is OpenSSL. 73 | \item A good replacement for OpenSSL is a similar library, 74 | libff.\footnote{\url{https://github.com/scipr-lab/libff}} 75 | \end{itemize} 76 | \end{frame} 77 | 78 | \begin{frame} 79 | \frametitle{Metrics} 80 | \begin{itemize} 81 | \item In order to compare these libraries we have defined specific 82 | metrics. 83 | \item Our profiling involved a test case where we performed 84 | thousands of multiplications from C on both libraries:\newline 85 | $g ^ \rho$ 86 | where $g$ is the generator of the elliptic curve group and 87 | $\rho$ is a 256 bit number. 88 | \item libff yielded up to 6 times better performance than OpenSSL. 89 | \item So, we moved forward with the implementation of a libff 90 | wrapper for Python. 91 | \end{itemize} 92 | \end{frame} 93 | 94 | \begin{frame} 95 | \frametitle{Wrapping libff With Cython} 96 | \begin{itemize} 97 | \item libff is implemented in C++. 98 | \item So it needs to be wrapped by Python in order to be used as a 99 | Python module. 100 | \item No such wrapper exists, so we set out to create one. 101 | \item We identified that Cython is the best candidate for wrapping 102 | libff. 103 | \item The wrapper exists as a separate open source module 104 | so it can be used by other Python projects that need to use libff. 105 | \end{itemize} 106 | \end{frame} 107 | 108 | \begin{frame} 109 | \frametitle{Comparing Wrappers} 110 | \begin{itemize} 111 | \item After creating the Cython wrapper for libff, in order to 112 | verify that it is indeed better than the Python wrapper for 113 | OpenSSL, we defined specific metrics. 114 | \item Our profiling involved a test case where we performed 115 | thousands of multiplications from Python on both wrappers. 116 | \item The results validated our hypothesis, so we used the Cython 117 | wrapper for the implementation of the re-encryption mix-net module. 118 | \end{itemize} 119 | \end{frame} 120 | 121 | \begin{frame} 122 | \center{\url{https://github.com/eellak/gsoc17module-zeus}} 123 | \end{frame} 124 | \end{document} 125 | -------------------------------------------------------------------------------- /docs/metrics.bib: -------------------------------------------------------------------------------- 1 | @conference{ 2 | shufflearg, 3 | author="Prastudu Fauzi and Helger Lipmaa and Michal Zajac", 4 | title="A Shuffle Argument Secure in the Generic Model", 5 | url="https://eprint.iacr.org/2016/866.pdf" 6 | } 7 | 8 | @misc{ 9 | prototype, 10 | author="Panos Louridas and Dimitris Mitropoulos and Georgios Tsoukalas and Georgios Korfiatis", 11 | title="Implementation of the shuffle argument", 12 | url="https://github.com/grnet/ac16" 13 | } 14 | 15 | @article{ 16 | numpy, 17 | author = {Stéfan van der Walt and S. Chris Colbert and Gaël Varoquaux}, 18 | title = {The NumPy Array: A Structure for Efficient Numerical Computation}, 19 | journal = {Computing in Science \& Engineering}, 20 | volume = {13}, 21 | number = {2}, 22 | pages = {22-30}, 23 | year = {2011}, 24 | doi = {10.1109/MCSE.2011.37}, 25 | URL = { 26 | http://aip.scitation.org/doi/abs/10.1109/MCSE.2011.37 27 | }, 28 | eprint = { 29 | http://aip.scitation.org/doi/pdf/10.1109/MCSE.2011.37 30 | } 31 | } 32 | 33 | @misc{ 34 | bplib, 35 | author = "George Danezis", 36 | title = "A bilinear pairing library for petlib", 37 | howpublished = {\url{https://github.com/gdanezis/bplib}} 38 | } 39 | 40 | @misc{ 41 | libsnark, 42 | author = "SCIPR Lab", 43 | title = "A {C}++ library for {zkSNARK} proofs", 44 | howpublished = {\url{https://github.com/scipr-lab/libsnark}} 45 | } 46 | 47 | @misc{libff, 48 | author = "SCIPR Lab", 49 | title = "libff: C++ library for Finite Fields and Elliptic Curves", 50 | howpublished = {\url{https://github.com/scipr-lab/libff}} 51 | } 52 | -------------------------------------------------------------------------------- /docs/metrics.tex: -------------------------------------------------------------------------------- 1 | \documentclass{article} 2 | 3 | \usepackage{url} 4 | \usepackage{graphicx} 5 | \usepackage{listings} 6 | \usepackage{todonotes} 7 | \usepackage{algorithm} 8 | \usepackage{algpseudocode} 9 | 10 | \usepackage{minted} 11 | 12 | \presetkeys{todonotes}{fancyline, color=yellow!30}{} 13 | 14 | \date{} 15 | \begin{document} 16 | 17 | \title{Metrics for the AsiaCrypt16 Implementation} 18 | 19 | \author{Vitalis Salis} 20 | 21 | \maketitle 22 | \begin{abstract} 23 | We have computed some metrics for the prototype implementation 24 | \cite{prototype} of a mixnet based on the shuffle argument proposed 25 | by Fauzi et al \cite{shufflearg}. The goal of these metrics is to 26 | identify aspects of the code that are slow and find suitable 27 | replacements for them. 28 | \end{abstract} 29 | 30 | \section{Introduction} 31 | 32 | The prototype implementation of the mixnet proposed by Fauzi et al, 33 | produces multiple implementation difficulties. On implementations of 34 | cryptographic protocols it is typical to use C for your cryptographic 35 | computations. Yet the prototype is implemented using Python, so it has 36 | to switch between Python and C for its operations. This may be a 37 | bottleneck of the prototype and the reason some operations are slower 38 | than they should. Another reason may be that the underlying C 39 | cryptographic operations themselves are not efficient, and a different 40 | C implementation might improve matters. The two reasons are not 41 | exclusive, and one might compound the other. 42 | 43 | \section{Metrics} 44 | 45 | Table 1 contains a list of metrics for the various operations of the 46 | prototype. Most of the time is taken by the prover and the verifier, 47 | as expected, because these have the most computations that produce a 48 | context switch between Python and C. 49 | 50 | \begin{table} 51 | \begin{tabular}{ |p{3cm}|p{5cm}|p{3cm}| } 52 | \hline 53 | \multicolumn{3}{|c|}{Metrics}\\ 54 | \hline 55 | Operation & Short Description & Time per 100 voters\\ 56 | \hline 57 | Initialization & Creates the elliptic Curve and private keys & 364ms\\ 58 | Encryption & Encrypts the votes & 674ms\\ 59 | Random Permutations & Creates random numbers & 1ms\\ 60 | Proof & The shuffle & 2085ms\\ 61 | Verification & Verification of the shuffle & 2738ms\\ 62 | Decryption & Decrypts the votes & 489ms\\ 63 | \hline 64 | \end{tabular} 65 | \caption{Metrics} 66 | \end{table} 67 | 68 | The time taken by each of these operations is linear, meaning that for 69 | 200 ciphertexts the numbers on the table are doubled. 70 | 71 | \section{Context Switches} 72 | 73 | A context switch happens when a Python program communicates with a C 74 | program for various cryptographic computations. The reasoning behind 75 | believing that a context switch may be the bottleneck of the application 76 | is that Python needs to create a PyObject containing the 77 | data it wants to communicate, and C also needs to create a PyObject to 78 | return the result of the computations. 79 | 80 | The prover has various steps. In order to validate our theory about 81 | context switches we measured each of these steps. Two of those steps, 82 | while having the same number of iterations, had a significant time 83 | difference. In particular, \mintinline{python}{step2a} below took 84 | 100ms, while \mintinline{python}{step3a} took 700ms. 85 | 86 | \begin{minted}[breaklines]{python} 87 | def step2a(sigma, A1, randoms, g1_poly_zero, g1rho, g1_poly_squares): 88 | pi_1sp = [] 89 | inverted_sigma = inverse_perm(sigma) 90 | for inv_i, ri, Ai1 in zip(inverted_sigma, randoms, A1): 91 | g1i_poly_sq = g1_poly_squares[inv_i] 92 | v = (2 * ri) * (Ai1 + g1_poly_zero) - (ri * ri) * g1rho + g1i_poly_sq 93 | pi_1sp.append(v) 94 | return pi_1sp 95 | \end{minted} 96 | 97 | \begin{minted}[breaklines]{python} 98 | def step3a(sigma, ciphertexts, s_randoms, pk1, pk2): 99 | v1s_prime = [] 100 | v2s_prime = [] 101 | for perm_i, s_random in zip(sigma, s_randoms): 102 | (v1, v2) = ciphertexts[perm_i] 103 | v1s_prime.append(tuple_add(v1, enc(pk1, s_random[0], s_random[1], 0))) 104 | v2s_prime.append(tuple_add(v2, enc(pk2, s_random[0], s_random[1], 0))) 105 | return list(zip(v1s_prime, v2s_prime)) 106 | \end{minted} 107 | 108 | \noindent 109 | First we attributed the time difference to various calls to zip and to tuple 110 | creation. After removing all the calls to zip we didn't notice any significant 111 | difference. This seemed to validate the context switches theory, because the 112 | slower step contained more context switches per iteration. 113 | 114 | But that's not the case. Using cProfile we identified the main 115 | reason behind this difference. The slower step does more multiplications on 116 | elliptic curve elements. While it is expected that multiplication will be slower 117 | than addition, the difference was enough to dismiss the context switches theory. 118 | 119 | Multiplication on our elliptic curve elements takes 575ms per 300 120 | multiplications, while addition takes 5ms for 400 additions. If the real 121 | problem were context switches, then the addition wouldn't have such a huge 122 | difference with the multiplication, because it has more operations hence 123 | more context switches. 124 | 125 | 126 | \section{Comparing bplib and libsnark} 127 | 128 | The prototype implementation uses the bplib\cite{bplib} Python module. 129 | bplib implements bilinear pairings on elliptic curves while also supporting 130 | elliptic curve operations using the openssl library. 131 | 132 | Another implementation supporting elliptic curve computations and bilinear 133 | pairings is libsnark\cite{libsnark}. 134 | 135 | The common characteristics of these libraries are that they both use the 136 | Ate Pairing and they use windowed exponentiation for 137 | optimization purposes. 138 | 139 | A key difference of these implementations is that bplib uses the 140 | curve Fp254BNb, while libsnark uses bn128 which is a patch on the 141 | Fp254BNb curve. Also, libsnark supports vectorized exponentiation 142 | which boosts up its performance. 143 | 144 | In order to compare these two libraries and validate our theory that 145 | libsnark is faster than bplib, we created two different tests 146 | using bplib and libsnark on each one. The tests did multiplications 147 | (the bottleneck of the prototype) on both elliptic curve groups. 148 | 149 | The results validated our theory. Multiplying elements on the G2 150 | group using libsnark yielded a performance of 0.38s/1000 ciphertexts 151 | while using openssl yielded 3.22s/1000. On G1 libsnark produced 152 | 0.13s/1000 while bplib produced 0.96s/1000 multiplications. 153 | 154 | 155 | \section{Wrapping libsnark with Cython} 156 | 157 | Since libsnark computes multiplications faster than the openssl 158 | implementation, the most obvious solution is to replace openssl 159 | with libsnark. The best candidate for this job is Cython, because 160 | it offers the performance aspects of C, while providing the functionality 161 | of Python. In order to validate that Cython, indeed will yield better 162 | performance we created a basic Cython application that does multiplications 163 | on the G2 group of the libsnark elliptic curve. 164 | 165 | The results were positive. A multiplication on the G2 group using Cython 166 | takes about 0.5ms while on our prototype implementation, that uses bplib, 167 | a multiplication takes about 2ms. So that's a 4x boost in performance. 168 | 169 | Also our Cython implementation didn't implement vectorized multiplications, 170 | so there's still room for optimizations. 171 | 172 | 173 | \section{Solutions} 174 | 175 | Since the real bottleneck are the multiplications on G2 elements, 176 | the most obvious solution is to use optimizations on the multiplication 177 | process. 178 | 179 | As mentioned, libsnark computes multiplications faster than our 180 | current implementation. Yet libsnark is written in C++ and we want to 181 | use a Python module. A Python wrapper for libsnark would be useful, 182 | for our needs and the open source community. In fact, we do not really 183 | need the full libsnark library; the Elliptic curve parts have been 184 | factored out to libff~\cite{libff}, so a Python wrapper for libff 185 | could be implemented. 186 | 187 | 188 | \bibliographystyle{plain} 189 | \bibliography{metrics} 190 | 191 | \end{document} 192 | -------------------------------------------------------------------------------- /docs/pdf/ath-floss-pres.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eellak/gsoc17module-zeus/21cf8055ff58c670e96bc197e5cadf54f6b22b45/docs/pdf/ath-floss-pres.pdf -------------------------------------------------------------------------------- /docs/pdf/metrics.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eellak/gsoc17module-zeus/21cf8055ff58c670e96bc197e5cadf54f6b22b45/docs/pdf/metrics.pdf -------------------------------------------------------------------------------- /flz16/__init__.py: -------------------------------------------------------------------------------- 1 | from crs import CRS 2 | from prover import Prover 3 | from verifier import Verifier 4 | 5 | import utils 6 | -------------------------------------------------------------------------------- /flz16/crs.py: -------------------------------------------------------------------------------- 1 | from libffpy import LibffPy, BigNum 2 | 3 | class CRS: 4 | def __init__(self, n): 5 | self.n = n 6 | self.lff = LibffPy(n) 7 | self.order = self.lff.order() 8 | self.gen1 = self.lff.gen1() 9 | self.gen2 = self.lff.gen2() 10 | self.gt = self.lff.pair(self.gen1, self.gen2) 11 | self.pair = self.lff.pair 12 | 13 | chi = self.order.random() 14 | alpha = self.order.random() 15 | rho = self.order.random(nonzero=True) 16 | beta = self.order.random(nonzero=True) 17 | self.gamma = self.order.random(nonorder=True) 18 | 19 | polys_all = self.generate_pis(chi, n) 20 | poly_zero = polys_all[0] 21 | polys = polys_all[1:] 22 | 23 | self.g1_polys = [poly * self.gen1 for poly in polys] 24 | self.g1rho = rho * self.gen1 25 | # init window table for g1rho 26 | self.g1rho.initWindowTable(n) 27 | 28 | self.g1alpha = (alpha + poly_zero) * self.gen1 29 | self.g1_poly_zero = poly_zero * self.gen1 30 | self.g1_poly_zero.initWindowTable(n) 31 | 32 | inv_rho = rho.mod_inverse() 33 | self.g1_poly_squares = [] 34 | for poly in polys: 35 | nom = (poly + poly_zero) ** 2 - 1 36 | self.g1_poly_squares.append((nom * inv_rho) * self.gen1) 37 | 38 | inv_beta = beta.mod_inverse() 39 | g1hat = (rho * inv_beta) * self.gen1 40 | h1 = self.gamma * g1hat 41 | 42 | g1hat.initWindowTable(n) 43 | h1.initWindowTable(n) 44 | self.pk1 = (g1hat, h1) 45 | 46 | self.g2_polys = [poly * self.gen2 for poly in polys] 47 | self.g2rho = rho * self.gen2 48 | # init window table for g2rho 49 | self.g2rho.initWindowTable(n) 50 | 51 | self.g2alpha = (-alpha + poly_zero) * self.gen2 52 | h2 = self.gamma * self.gen2 53 | 54 | h2.initWindowTable(n) 55 | self.pk2 = (self.gen2, h2) 56 | 57 | self.g2beta = beta * self.gen2 58 | 59 | self.pair_alpha = self.gt ** (1 - alpha ** 2) 60 | poly_sum = sum([poly for poly in polys]) 61 | self.g1_sum = poly_sum * self.gen1 62 | self.g2_sum = poly_sum * self.gen2 63 | 64 | def generate_pis(self, chi, n): 65 | if chi <= n + 1: 66 | raise ValueError( 67 | "chi should be greater than n + 1, chi=%s n+1=%s" % (chi, n + 1) 68 | ) 69 | 70 | pis = [] 71 | 72 | prod = BigNum(1) 73 | # prod = (x - w_1) (x - w_2) ... (x - w_{n+1}) 74 | for j in range(1, n + 2): 75 | prod = prod * (chi - j) 76 | 77 | # denoms[0] = 1 / (w_1 - w_2) (w_1 - w_3) ... (w_1 - w_{n + 1}) 78 | # denoms[1] = 1 / (w_2 - w_1) (w_2 - w_3) ... (w_2 - w_{n + 1}) 79 | # denoms[n] = 1 / (w_{n+1}- w_1) (w_{n+1} - w_2) ... (w_{n+1} - w_n) 80 | denoms = self.compute_denominators(n + 1) 81 | 82 | missing_factor = chi - (n + 1) 83 | 84 | ln_plus1 = prod * missing_factor.mod_inverse() 85 | ln_plus1 = ln_plus1 * denoms[n].mod_inverse() 86 | 87 | # P_0 is special 88 | pis.append(ln_plus1 - BigNum(1)) 89 | 90 | two = BigNum(2) 91 | for i in range(1, n + 1): 92 | missing_factor = chi - i 93 | l_i = prod * missing_factor.mod_inverse() 94 | l_i = l_i * denoms[i - 1].mod_inverse() 95 | pis.append(two * l_i + ln_plus1) 96 | 97 | return pis 98 | 99 | def compute_denominators(self, k): 100 | denominators = [] 101 | temp = BigNum(1) 102 | for i in range(1, k + 1): 103 | if i == 1: 104 | for j in range(2, k + 1): 105 | elem = i - j; 106 | temp = temp * elem 107 | elif i == k: 108 | elem = 1 - k; 109 | temp = temp * elem 110 | else: 111 | inverse = BigNum(i - 1 - k) 112 | inverse = inverse.mod_inverse() 113 | elem = i - 1 114 | temp = temp * elem 115 | temp = temp * inverse 116 | denominators.append(temp) 117 | 118 | return denominators 119 | -------------------------------------------------------------------------------- /flz16/ilin2.py: -------------------------------------------------------------------------------- 1 | def enc(pk, s1, s2, m): 2 | g, h = pk 3 | return (s1*h, s2*(g + h), (m + s1 + s2) * g) 4 | 5 | def dec(c, sk, table): 6 | c1, c2, c3 = c 7 | e1 = (-sk).mod_inverse() 8 | e2 = (-(sk + 1)).mod_inverse() 9 | v = (c3 + e2*c2 + e1*c1) 10 | return table[v] 11 | 12 | def make_table(g, n): 13 | table = {} 14 | for i in range(n): 15 | elem = (i * g) 16 | table[elem] = i 17 | return table 18 | -------------------------------------------------------------------------------- /flz16/prover.py: -------------------------------------------------------------------------------- 1 | from libffpy import G1Py, G2Py 2 | from utils import inverse_perm 3 | from ilin2 import enc 4 | 5 | class Prover: 6 | def __init__(self, crs): 7 | self.crs = crs 8 | 9 | def get_infs(self): 10 | inf1 = G1Py.inf() 11 | inf2 = G2Py.inf() 12 | return inf1, inf2 13 | 14 | def tuple_map(self, func, tpl): 15 | return tuple(map(func, tpl)) 16 | 17 | 18 | def tuple_add(self, tpl1, tpl2): 19 | zipped = zip(tpl1, tpl2) 20 | return tuple(z[0] + z[1] for z in zipped) 21 | 22 | def step1a(self, sigma): 23 | crs = self.crs 24 | randoms = [crs.order.random() for i in range(crs.n - 1)] 25 | inverted_sigma = inverse_perm(sigma) 26 | 27 | A1 = [] 28 | A2 = [] 29 | for inv_i, ri in zip(inverted_sigma, randoms): 30 | p1_value = crs.g1_polys[inv_i] 31 | p2_value = crs.g2_polys[inv_i] 32 | a1i = p1_value + ri * crs.g1rho 33 | a2i = p2_value + ri * crs.g2rho 34 | A1.append(a1i) 35 | A2.append(a2i) 36 | 37 | return randoms, A1, A2 38 | 39 | def step1b(self, randoms): 40 | rand_n = - sum(randoms) 41 | randoms.append(rand_n) 42 | return randoms 43 | 44 | def step1c(self, A1, A2): 45 | inf1, inf2 = self.get_infs() 46 | 47 | prod1 = sum(A1, inf1) 48 | prod2 = sum(A2, inf2) 49 | 50 | a1n = self.crs.g1_sum - prod1 51 | a2n = self.crs.g2_sum - prod2 52 | 53 | A1.append(a1n) 54 | A2.append(a2n) 55 | 56 | return A1, A2 57 | 58 | def step2a(self, sigma, A1, randoms): 59 | crs = self.crs 60 | 61 | pi_1sp = [] 62 | inverted_sigma = inverse_perm(sigma) 63 | 64 | for inv_i, ri, Ai1 in zip(inverted_sigma, randoms, A1): 65 | g1i_poly_sq = crs.g1_poly_squares[inv_i] 66 | v = (2 * ri) * Ai1 + (2 * ri) * crs.g1_poly_zero - (ri * ri) * crs.g1rho + g1i_poly_sq 67 | pi_1sp.append(v) 68 | 69 | return pi_1sp 70 | 71 | def step3a(self, sigma, ciphertexts, s_randoms): 72 | crs = self.crs 73 | 74 | v1s_prime = [] 75 | v2s_prime = [] 76 | for perm_i, s_random in zip(sigma, s_randoms): 77 | (v1, v2) = ciphertexts[perm_i] 78 | v1s_prime.append(self.tuple_add(v1, enc(self.crs.pk1, s_random[0], s_random[1], 0))) 79 | v2s_prime.append(self.tuple_add(v2, enc(self.crs.pk2, s_random[0], s_random[1], 0))) 80 | 81 | return list(zip(v1s_prime, v2s_prime)) 82 | 83 | def step4a(self, s_randoms): 84 | crs = self.crs 85 | 86 | rs = tuple([crs.order.random() for i in range(2)]) 87 | (rs1, rs2) = rs 88 | pi_c1_1 = rs1 * crs.g2rho 89 | pi_c1_2 = rs2 * crs.g2rho 90 | for si, g2_polyi in zip(s_randoms, crs.g2_polys): 91 | si1, si2 = si 92 | pi_c1_1 += si1 * g2_polyi 93 | pi_c1_2 += si2 * g2_polyi 94 | 95 | return rs, (pi_c1_1, pi_c1_2) 96 | 97 | def step4b(self, ciphertexts, rs, randoms): 98 | crs = self.crs 99 | 100 | pi_c2_1 = enc(crs.pk1, rs[0], rs[1], 0) 101 | pi_c2_2 = enc(crs.pk2, rs[0], rs[1], 0) 102 | for ciphertext, ri in zip(ciphertexts, randoms): 103 | v1, v2 = ciphertext 104 | pi_c2_1 = self.tuple_add(pi_c2_1, self.tuple_map(lambda x: ri * x, v1)) 105 | pi_c2_2 = self.tuple_add(pi_c2_2, self.tuple_map(lambda x: ri * x, v2)) 106 | 107 | return pi_c2_1, pi_c2_2 108 | 109 | def prove(self, n, ciphertexts, sigma, s_randoms): 110 | proof = dict.fromkeys(['shuffled_ciphertexts', 'pi_1sp', 'pi_c1_1',\ 111 | 'pi_c1_2', 'pi_c2_1', 'pi_c2_2', 'A1', 'A2']) 112 | randoms, A1, A2 = self.step1a(sigma) 113 | randoms = self.step1b(randoms) 114 | A1, A2 = self.step1c(A1, A2) 115 | proof['pi_1sp'] = self.step2a(sigma, A1, randoms) 116 | proof['shuffled_ciphertexts'] = self.step3a(sigma, ciphertexts, s_randoms) 117 | rs, (proof['pi_c1_1'], proof['pi_c1_2']) = self.step4a(s_randoms) 118 | proof['pi_c2_1'], proof['pi_c2_2'] = self.step4b(ciphertexts, rs, randoms) 119 | 120 | proof['A1'] = A1[:-1] 121 | proof['A2'] = A2[:-1] 122 | 123 | return proof 124 | -------------------------------------------------------------------------------- /flz16/tests/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for the re-encryption mixnet module 3 | """ 4 | 5 | from test_utils import UtilsTest 6 | from test_prover_verifier import ProverVerifierTest 7 | -------------------------------------------------------------------------------- /flz16/tests/test_prover_verifier.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from crs import CRS 4 | from prover import Prover 5 | from verifier import Verifier 6 | from utils import make_s_randoms, random_permutation,\ 7 | encrypt_messages, make_tables, decrypt_messages 8 | 9 | class ProverVerifierTest(unittest.TestCase): 10 | def setUp(self): 11 | n = 10 12 | 13 | crs = CRS(n) 14 | s_randoms = make_s_randoms(n, crs.order) 15 | sigma = random_permutation(n) 16 | ciphertexts = encrypt_messages(crs.order, crs.pk1, crs.pk2, list(range(n))) 17 | prover = Prover(crs) 18 | self.proof = prover.prove(n, ciphertexts, sigma, s_randoms) 19 | self.crs = crs 20 | self.ciphertexts = ciphertexts 21 | 22 | def test_verifier(self): 23 | verifier = Verifier(self.crs) 24 | 25 | self.assertEqual(verifier.verify(self.ciphertexts, self.proof), (True, True, True)) 26 | 27 | prevshuffle = self.proof['shuffled_ciphertexts'] 28 | g1 = self.crs.lff.gen1() 29 | g2 = self.crs.lff.gen2() 30 | self.proof['shuffled_ciphertexts'][3] = ((g1, g1, g1), (g2, g2, g2)) 31 | 32 | self.assertEqual(verifier.verify(self.ciphertexts, self.proof), (True, False, False)) 33 | 34 | self.proof['shuffled_ciphertexts'] = prevshuffle 35 | self.crs.g1alpha = self.crs.g1alpha * 2 36 | verifier = Verifier(self.crs) 37 | 38 | self.assertEqual(verifier.verify(self.ciphertexts, self.proof), (False, False, False)) 39 | -------------------------------------------------------------------------------- /flz16/tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from libffpy.libffpy import LibffPy, BigNum 4 | from utils import make_tables, encrypt, decrypt 5 | 6 | class UtilsTest(unittest.TestCase): 7 | def setUp(self): 8 | self.MAX = 1000 9 | self.lff = LibffPy(self.MAX) 10 | 11 | def key_gen(self, g, sk): 12 | h = g * sk 13 | return (g, h) 14 | 15 | def test_make_tables(self): 16 | sk = BigNum.getOrder().random() 17 | pk1 = self.key_gen(self.lff.gen1(), sk) 18 | pk2 = self.key_gen(self.lff.gen2(), sk) 19 | table1, table2 = make_tables(pk1, pk2, self.MAX) 20 | 21 | self.assertEqual(table1[666 * pk1[0]], 666) 22 | self.assertEqual(table2[666 * pk2[0]], 666) 23 | 24 | self.assertNotEqual(table1[2 * pk1[0]], 666) 25 | self.assertNotEqual(table2[3 * pk2[0]], 666) 26 | 27 | def test_encdec(self): 28 | sk = BigNum.getOrder().random() 29 | 30 | pk1 = self.key_gen(self.lff.gen1(), sk) 31 | pk2 = self.key_gen(self.lff.gen2(), sk) 32 | 33 | order = BigNum.getOrder() 34 | c1, c2 = encrypt(order, pk1, pk2, 666) 35 | 36 | tables = make_tables(pk1, pk2, self.MAX) 37 | self.assertEqual(decrypt((c1, c2), sk, tables), (666, 666)) 38 | 39 | import random 40 | ps = random.sample(range(self.MAX), 100) 41 | for i in range(100): 42 | c1, c2 = encrypt(order, pk1, pk2, ps[i]) 43 | self.assertEqual(decrypt((c1, c2), sk, tables), (ps[i], ps[i])) 44 | -------------------------------------------------------------------------------- /flz16/utils.py: -------------------------------------------------------------------------------- 1 | import random 2 | import ilin2 3 | 4 | def make_s_randoms(n, order): 5 | return [[order.random() for j in range(2)] for i in range(n)] 6 | 7 | def random_permutation(n): 8 | system_random = random.SystemRandom() 9 | s = list(range(n)) 10 | random.shuffle(s, random=system_random.random) 11 | return s 12 | 13 | def encrypt(order, pk1, pk2, m): 14 | s1 = order.random() 15 | s2 = order.random() 16 | c1 = ilin2.enc(pk1, s1, s2, m) 17 | c2 = ilin2.enc(pk2, s1, s2, m) 18 | return c1, c2 19 | 20 | def decrypt(cs, secret, tables): 21 | m1 = ilin2.dec(cs[0], secret, tables[0]) 22 | m2 = ilin2.dec(cs[1], secret, tables[1]) 23 | return m1, m2 24 | 25 | def encrypt_messages(order, pk1, pk2, messages): 26 | return [encrypt(order, pk1, pk2, message) for message in messages] 27 | 28 | def decrypt_messages(secret, tables, ciphertexts): 29 | return [decrypt(cs, secret, tables) for cs in ciphertexts] 30 | 31 | def make_tables(pk1, pk2, n): 32 | table1 = ilin2.make_table(pk1[0], n) 33 | table2 = ilin2.make_table(pk2[0], n) 34 | return table1, table2 35 | 36 | def inverse_perm(s): 37 | r = [None] * len(s) 38 | for index, value in enumerate(s): 39 | r[value] = index 40 | return r 41 | -------------------------------------------------------------------------------- /flz16/verifier.py: -------------------------------------------------------------------------------- 1 | from prover import Prover 2 | 3 | from libffpy import GTPy 4 | 5 | class Verifier: 6 | def __init__(self, crs): 7 | self.crs = crs 8 | 9 | def get_infT(self): 10 | return GTPy.one() 11 | 12 | def step1(self, prover, A1, A2): 13 | return prover.step1c(A1, A2) 14 | 15 | def step2(self): 16 | crs = self.crs 17 | 18 | p1 = [crs.order.random() for i in range(crs.n)] 19 | p2 = [crs.order.random() for j in range(3)] 20 | p3 = [[crs.order.random() for j in range(3)] 21 | for i in range(crs.n)] 22 | p4 = [crs.order.random() for j in range(3)] 23 | return p1, p2, p3, p4 24 | 25 | def step3(self, prover, A1, A2, p1, pi_1sp): 26 | crs = self.crs 27 | 28 | inf1, inf2 = prover.get_infs() 29 | infT = self.get_infT() 30 | prodT = infT 31 | prod1 = inf1 32 | sum_p = 0 33 | for (Ai1, Ai2, p1i, pi_1spi) in zip(A1, A2, p1, pi_1sp): 34 | prodT *= crs.pair(p1i * (Ai1 + crs.g1alpha), Ai2 + crs.g2alpha) 35 | prod1 += p1i * pi_1spi 36 | sum_p = sum_p + p1i 37 | right = crs.pair(prod1, crs.g2rho) * (crs.pair_alpha ** sum_p) 38 | return prodT == right 39 | 40 | def step4(self, prover, p2, p3, pi_c2_1, pi_c2_2, v_primes): 41 | crs = self.crs 42 | 43 | inf1, inf2 = prover.get_infs() 44 | 45 | def pi_c_prod(inf, pi_c2_): 46 | prod_c2_ = inf 47 | for (p2j, pi_c2_j) in zip(p2, pi_c2_): 48 | prod_c2_ += p2j * pi_c2_j 49 | return prod_c2_ 50 | 51 | def nested_prods(inf, flag): 52 | outer_prod = inf 53 | for vi_prime, p3i in zip(v_primes, p3): 54 | inner_prod = inf 55 | vi_f_prime = vi_prime[flag] 56 | for (vi_f_prime_j, p3ij) in zip(vi_f_prime, p3i): 57 | inner_prod += p3ij * vi_f_prime_j 58 | outer_prod += inner_prod 59 | return outer_prod 60 | 61 | left = crs.pair(crs.g1rho, pi_c_prod(inf2, pi_c2_2) + nested_prods(inf2, 1)) 62 | right = crs.pair(pi_c_prod(inf1, pi_c2_1) + nested_prods(inf1, 0), crs.g2beta) 63 | return left == right 64 | 65 | def step5(self, prover, pi_c1_1, pi_c1_2, pi_c2_1, p4): 66 | crs = self.crs 67 | 68 | inf1, _ = prover.get_infs() 69 | g1hat, h1 = crs.pk1 70 | pair1 = crs.pair(g1hat, p4[1] * pi_c1_2 + p4[2] * (pi_c1_1 + pi_c1_2)) 71 | pair2 = crs.pair(h1, p4[0] * pi_c1_1 + p4[1] * pi_c1_2) 72 | prod = inf1 73 | for (p4j, pi_c2_1j) in zip(p4, pi_c2_1): 74 | prod += p4j * pi_c2_1j 75 | pair3 = crs.pair(prod, crs.g2rho) 76 | return pair1 * pair2 * pair3.inv() 77 | 78 | def step6(self, prover, ciphertexts, v_primes, A2, p4, R): 79 | crs = self.crs 80 | def do_inner(vi): 81 | vi1 = vi[0] 82 | inf1, _ = prover.get_infs() 83 | inner_prod = inf1 84 | for (p4j, vi1j) in zip(p4, vi1): 85 | inner_prod += p4j * vi1j 86 | return inner_prod 87 | 88 | infT = self.get_infT() 89 | outer_numer = infT 90 | for (vi_prime, g2_poly_i) in zip(v_primes, crs.g2_polys): 91 | outer_numer *= crs.pair(do_inner(vi_prime), g2_poly_i) 92 | 93 | outer_denom = infT 94 | for (vi, Ai2) in zip(ciphertexts, A2): 95 | outer_denom *= crs.pair(do_inner(vi), Ai2) 96 | 97 | return outer_numer * outer_denom.inv() == R 98 | 99 | def verify(self, ciphertexts, proof): 100 | prover = Prover(self.crs) 101 | 102 | A1, A2 = self.step1(prover, proof['A1'], proof['A2']) 103 | p1, p2, p3, p4 = self.step2() 104 | perm_ok = self.step3(prover, A1, A2, p1, proof['pi_1sp']) 105 | valid = self.step4(prover, p2, p3, proof['pi_c2_1'],\ 106 | proof['pi_c2_2'], proof['shuffled_ciphertexts']) 107 | R = self.step5(prover, proof['pi_c1_1'], proof['pi_c1_2'], proof['pi_c2_1'], p4) 108 | consistent = self.step6(prover, ciphertexts,\ 109 | proof['shuffled_ciphertexts'], A2, p4, R) 110 | return perm_ok, valid, consistent 111 | -------------------------------------------------------------------------------- /libffpy/__init__.py: -------------------------------------------------------------------------------- 1 | from libffpy import * 2 | -------------------------------------------------------------------------------- /libffpy/demo.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import datetime 3 | from libffpy import LibffPy, BigNum 4 | 5 | n = int(sys.argv[1]) 6 | 7 | l = LibffPy(n) 8 | g2 = l.gen2() 9 | g1 = l.gen1() 10 | 11 | 12 | start = datetime.datetime.now() 13 | bg = [BigNum() for _ in xrange(n - 1)] 14 | end = datetime.datetime.now() 15 | print "BigNum creation ellapsed: %s" % (end - start) 16 | 17 | 18 | s = reduce((lambda x,y: x + y), bg) 19 | 20 | bg.append(bg[0].getOrder() + 1 - s) 21 | 22 | 23 | start = datetime.datetime.now() 24 | res = [g2 * e for e in bg] 25 | end = datetime.datetime.now() 26 | print "G2 Multiplication ellapsed: %s" % (end - start) 27 | 28 | s = reduce((lambda x,y: x+ y), res) 29 | print "Test passed: %s" % (s == g2) 30 | 31 | start = datetime.datetime.now() 32 | res = [g1 * e for e in bg] 33 | end = datetime.datetime.now() 34 | print "G1 multiplication ellapsed: %s" % (end - start) 35 | -------------------------------------------------------------------------------- /libffpy/libff_wrapper.cpp: -------------------------------------------------------------------------------- 1 | #include "libff_wrapper.h" 2 | 3 | size_t get_g2_exp_window_size(size_t g2_exp_count) { 4 | return get_exp_window_size>(g2_exp_count); 5 | } 6 | 7 | window_table> get_g2_window_table(size_t window_size, G2 elem) { 8 | return get_window_table(Fr::size_in_bits(), window_size, elem); 9 | } 10 | 11 | G2 g2_mul(size_t window_size, window_table> *g2_table, Fr other) { 12 | return windowed_exp(Fr::size_in_bits(), window_size, *g2_table, other); 13 | } 14 | 15 | size_t get_g1_exp_window_size(size_t g1_exp_count) { 16 | return get_exp_window_size>(g1_exp_count); 17 | } 18 | 19 | window_table> get_g1_window_table(size_t window_size, G1 elem) { 20 | return get_window_table(Fr::size_in_bits(), window_size, elem); 21 | } 22 | 23 | G1 g1_mul(size_t window_size, window_table> *g1_table, Fr other) { 24 | return windowed_exp(Fr::size_in_bits(), window_size, *g1_table, other); 25 | } 26 | 27 | Fr Fr_get_random_nonzero() { 28 | Fr elem = Fr::random_element(); 29 | while (elem == Fr::zero()) { 30 | elem = Fr::random_element(); 31 | } 32 | return elem; 33 | } 34 | 35 | Fr Fr_get_random_nonorder() { 36 | Fr elem = Fr::random_element(); 37 | while (elem == Fr::zero() && elem != Fr::one()) { 38 | elem = Fr::random_element(); 39 | } 40 | return elem; 41 | } 42 | -------------------------------------------------------------------------------- /libffpy/libff_wrapper.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "gmp.h" 3 | #include "algebra/fields/bigint.hpp" 4 | #include "algebra/curves/public_params.hpp" 5 | #include "algebra/curves/bn128/bn128_pp.hpp" 6 | #include "algebra/scalar_multiplication/multiexp.hpp" 7 | 8 | using namespace libff; 9 | 10 | typedef bn128_pp curve; 11 | 12 | size_t get_g2_exp_window_size(size_t g2_exp_count); 13 | window_table> get_g2_window_table(size_t window_size, G2 elem); 14 | G2 g2_mul(size_t window_size, window_table> *g2_table, Fr other); 15 | 16 | size_t get_g1_exp_window_size(size_t g1_exp_count); 17 | window_table> get_g1_window_table(size_t window_size, G1 elem); 18 | G1 g1_mul(size_t window_size, window_table> *g1_table, Fr other); 19 | 20 | Fr Fr_get_random_nonzero(); 21 | Fr Fr_get_random_nonorder(); 22 | -------------------------------------------------------------------------------- /libffpy/libffpy.pxd: -------------------------------------------------------------------------------- 1 | from libcpp cimport bool, string 2 | 3 | 4 | cdef extern from "libff_wrapper.h": 5 | cdef cppclass curve: 6 | pass 7 | 8 | cdef cppclass bignum: 9 | pass 10 | 11 | cdef cppclass fp1"bn::Fp": 12 | string.string toString(int) 13 | 14 | cdef cppclass fp2"bn::Fp2": 15 | string.string toString(int) 16 | 17 | cdef cppclass window_table[G]: 18 | window_table() except + 19 | window_table(window_table f) except + 20 | 21 | cdef void init_public_params "curve::init_public_params"() 22 | 23 | cdef cppclass Fr[curve]: 24 | Fr() except + 25 | Fr(Fr[curve] f) except + 26 | Fr(long long n) except + 27 | Fr(bignum b) except + 28 | 29 | Fr[curve] operator+(Fr[curve] other) except + 30 | Fr[curve] operator+(long long int other) except + 31 | Fr[curve] operator-(Fr[curve] other) except + 32 | Fr[curve] operator-(long long int other) except + 33 | Fr[curve] operator-() except + 34 | Fr[curve] operator*(Fr[curve] other) except + 35 | Fr[curve] operator*(long long other) except + 36 | Fr[curve] operator^(unsigned long other) except + 37 | bool operator==(Fr[curve] other) except + 38 | Fr[curve] inverse() except + 39 | void cprint"print"() except + 40 | 41 | cdef cppclass G2[curve]: 42 | G2() except + 43 | G2(G2[curve] g) except + 44 | 45 | G2[curve] operator+(G2[curve] other) except + 46 | G2[curve] operator-(G2[curve] other) except + 47 | bool operator==(G2[curve] other) except + 48 | void cprint"print"() except + 49 | void to_affine_coordinates() except + 50 | fp2 *coord 51 | 52 | cdef cppclass G1[curve]: 53 | G1() except + 54 | G1(G1[curve] g) except + 55 | 56 | G1[curve] operator+(G1[curve] other) except + 57 | G1[curve] operator-(G1[curve] other) except + 58 | bool operator==(G1 other) except + 59 | void cprint"print"() except + 60 | void to_affine_coordinates() except + 61 | fp1 *coord 62 | 63 | cdef cppclass GT[curve]: 64 | GT() except + 65 | GT(GT[curve] g) except + 66 | 67 | GT[curve] operator^(Fr[curve] fr) except + 68 | GT[curve] operator*(GT[curve] other) except + 69 | GT[curve] unitary_inverse() except + 70 | bool operator==(GT other) except + 71 | void cprint"print"() except + 72 | 73 | G1[curve] operator*(Fr[curve], G1[curve]) except + 74 | G2[curve] operator*(Fr[curve], G2[curve]) except + 75 | 76 | cdef size_t get_g2_exp_window_size(size_t g2_exp_count) 77 | cdef G2[curve] g2_mul(size_t window_size, window_table[G2[curve]] *g2_table, Fr[curve] other) 78 | cdef window_table[G2[curve]] get_g2_window_table(size_t window_size, G2[curve] elem) 79 | 80 | cdef size_t get_g1_exp_window_size(size_t g1_exp_count) 81 | cdef G1[curve] g1_mul(size_t window_size, window_table[G1[curve]] *g1_table, Fr[curve] other) 82 | cdef window_table[G1[curve]] get_g1_window_table(size_t window_size, G1[curve] elem) 83 | cdef GT[curve] reduced_pairing "curve::reduced_pairing"(G1[curve] g1, G2[curve] g2) 84 | 85 | cdef bignum get_order "Fr::field_char"() 86 | cdef Fr[curve] Fr_get_random "Fr::random_element"() 87 | cdef Fr[curve] Fr_get_random_nonzero() 88 | cdef Fr[curve] Fr_get_random_nonorder() 89 | 90 | cdef G1[curve] get_g1_gen "G1::one"() 91 | cdef G2[curve] get_g2_gen "G2::one"() 92 | 93 | cdef G1[curve] get_g1_zero "G1::zero"() 94 | cdef G2[curve] get_g2_zero "G2::zero"() 95 | 96 | cdef GT[curve] get_gt_one "GT::one"() 97 | -------------------------------------------------------------------------------- /libffpy/libffpy.pyx: -------------------------------------------------------------------------------- 1 | cimport libffpy 2 | 3 | from libcpp.string cimport string 4 | 5 | cdef class BigNum: 6 | cdef Fr[curve] *_thisptr 7 | 8 | def __cinit__(self, num=None, init=True): 9 | if init: 10 | if num is not None and (isinstance(num, int) or isinstance(num, long)): 11 | self._thisptr = new Fr[curve](num) 12 | else: 13 | self._thisptr = new Fr[curve](Fr_get_random()) 14 | 15 | def __dealloc__(self): 16 | self.free() 17 | 18 | def free(self): 19 | if self._thisptr != NULL: 20 | del self._thisptr 21 | 22 | @staticmethod 23 | def getOrder(): 24 | cdef Fr[curve] *newptr 25 | cdef BigNum res = BigNum(init=False) 26 | 27 | newptr = new Fr[curve](get_order()) 28 | res.setElem(newptr) 29 | 30 | return res 31 | 32 | cdef setElem(self, Fr[curve] *b): 33 | self.free() 34 | self._thisptr = b 35 | 36 | cdef Fr[curve] *getElemRef(self): 37 | return self._thisptr 38 | 39 | cdef BigNum createElem(self, Fr[curve]* b): 40 | cdef BigNum bg = BigNum(init=False) 41 | bg.setElem(b) 42 | return bg 43 | 44 | cpdef BigNum add(self, BigNum other): 45 | cdef Fr[curve] *newptr 46 | newptr = new Fr[curve](self.getElemRef()[0] + other.getElemRef()[0]) 47 | return self.createElem(newptr) 48 | 49 | cpdef BigNum addInt(self, long long other): 50 | cdef Fr[curve] *newptr 51 | newptr = new Fr[curve](self.getElemRef()[0] + other) 52 | return self.createElem(newptr) 53 | 54 | cpdef BigNum subInt(self, long long other, neg=False): 55 | cdef Fr[curve] *newptr 56 | if neg: 57 | newptr = new Fr[curve](-self.getElemRef()[0] + other) 58 | else: 59 | newptr = new Fr[curve](self.getElemRef()[0] - other) 60 | 61 | return self.createElem(newptr) 62 | 63 | cpdef BigNum sub(self, BigNum other): 64 | cdef Fr[curve] *newptr 65 | newptr = new Fr[curve](self.getElemRef()[0] - other.getElemRef()[0]) 66 | return self.createElem(newptr) 67 | 68 | cpdef eq(self, BigNum other): 69 | return self.getElemRef()[0] == other.getElemRef()[0] 70 | 71 | cpdef BigNum pow(self, unsigned long p): 72 | cdef Fr[curve] *newptr 73 | newptr = new Fr[curve](self.getElemRef()[0] ^ p) 74 | return self.createElem(newptr) 75 | 76 | cpdef BigNum mod_inverse(self): 77 | cdef Fr[curve] *newptr 78 | newptr = new Fr[curve](self.getElemRef()[0].inverse()) 79 | return self.createElem(newptr) 80 | 81 | cpdef BigNum random(self, nonzero=False, nonorder=False): 82 | cdef Fr[curve] *newptr 83 | if nonzero: 84 | newptr = new Fr[curve](Fr_get_random_nonzero()) 85 | elif nonorder: 86 | newptr = new Fr[curve](Fr_get_random_nonorder()) 87 | else: 88 | newptr = new Fr[curve](Fr_get_random()) 89 | return self.createElem(newptr) 90 | 91 | def __add__(x, y): 92 | cdef BigNum bgleft, bgright 93 | cdef long long intright 94 | 95 | if not (isinstance(x, BigNum) or isinstance(y, BigNum)): 96 | return NotImplemented 97 | 98 | if isinstance(x, BigNum): 99 | if isinstance(y, BigNum): 100 | bgleft = x 101 | bgright = y 102 | return bgleft.add(bgright) 103 | elif isinstance(y, int) or isinstance(y, long): 104 | bgleft = x 105 | intright = y 106 | return bgleft.addInt(intright) 107 | else: 108 | return NotImplemented 109 | 110 | # y is bignum 111 | if isinstance(x, int) or isinstance(x, long): 112 | bgleft = y 113 | intright = x 114 | return bgleft.addInt(intright) 115 | 116 | return NotImplemented 117 | 118 | 119 | def __sub__(x, y): 120 | cdef BigNum bgleft, bgright 121 | cdef long long intright 122 | 123 | if not (isinstance(x, BigNum) or isinstance(y, BigNum)): 124 | return NotImplemented 125 | 126 | if isinstance(x, BigNum): 127 | if isinstance(y, BigNum): 128 | bgleft = x 129 | bgright = y 130 | return bgleft.sub(bgright) 131 | elif isinstance(y, int) or isinstance(y, long): 132 | bgleft = x 133 | intright = y 134 | return bgleft.subInt(intright) 135 | else: 136 | return NotImplemented 137 | 138 | # y is bignum 139 | if isinstance(x, int) or isinstance(x, long): 140 | bgleft = y 141 | intright = x 142 | return bgleft.subInt(intright, neg=True) 143 | 144 | return NotImplemented 145 | 146 | cpdef BigNum mul(self, BigNum other): 147 | cdef Fr[curve] *newptr 148 | newptr = new Fr[curve](self.getElemRef()[0] * other.getElemRef()[0]) 149 | return self.createElem(newptr) 150 | 151 | cpdef BigNum mulInt(self, long long other): 152 | cdef Fr[curve] *newptr 153 | newptr = new Fr[curve](self.getElemRef()[0] * other) 154 | return self.createElem(newptr) 155 | 156 | def __mul__(x, y): 157 | cdef BigNum left, right 158 | cdef long long intright 159 | if not (isinstance(x, BigNum) or isinstance(y, BigNum)): 160 | return NotImplemented 161 | 162 | if isinstance(x, BigNum): 163 | left = x 164 | if isinstance(y, BigNum): 165 | right = y 166 | return left.mul(right) 167 | 168 | if isinstance(y, int) or isinstance(y, long): 169 | intright = y 170 | return left.mulInt(intright) 171 | 172 | left = y 173 | if isinstance(x, int): 174 | intright = x 175 | return left.mulInt(intright) 176 | 177 | return NotImplemented 178 | 179 | 180 | def __pow__(x, y, z): 181 | cdef BigNum bg 182 | cdef unsigned long p 183 | if not isinstance(x, BigNum): 184 | return NotImplemented 185 | 186 | if not (isinstance(y, int) or isinstance(y, long)): 187 | return NotImplemented 188 | 189 | bg = x 190 | p = y 191 | 192 | return bg.pow(p) 193 | 194 | def __richcmp__(x, y, int op): 195 | cdef BigNum left, right 196 | 197 | if op != 2: 198 | # not == 199 | return NotImplemented 200 | 201 | if not (isinstance(x, BigNum) and isinstance(y, BigNum)): 202 | return NotImplemented 203 | 204 | left = x 205 | right = y 206 | 207 | return left.eq(right) 208 | 209 | def __neg__(self): 210 | cdef Fr[curve] *newptr 211 | newptr = new Fr[curve](-self.getElemRef()[0]) 212 | return self.createElem(newptr) 213 | 214 | cpdef pyprint(self): 215 | self.getElemRef()[0].cprint() 216 | 217 | 218 | cdef class G1Py: 219 | cdef G1[curve] *_thisptr 220 | cdef size_t g1_exp_count 221 | cdef size_t g1_window_size 222 | cdef window_table[G1[curve]] *g1_table 223 | 224 | def __cinit__(self, init=True): 225 | if init: 226 | self._thisptr = new G1[curve](get_g1_gen()) 227 | 228 | def __dealloc__(self): 229 | self.free() 230 | if self.g1_table != NULL: 231 | del self.g1_table 232 | 233 | def initWindowTable(self, int n): 234 | self.g1_exp_count = 4 * n + 7; 235 | self.g1_window_size = get_g1_exp_window_size(self.g1_exp_count) 236 | self.g1_table = new window_table[G1[curve]](get_g1_window_table(self.g1_window_size, self.getElemRef()[0])) 237 | 238 | @staticmethod 239 | def inf(): 240 | cdef G1[curve] *newptr 241 | cdef G1Py g = G1Py(init=False) 242 | newptr = new G1[curve](get_g1_zero()) 243 | g.setElem(newptr) 244 | return g 245 | 246 | def free(self): 247 | if self._thisptr != NULL: 248 | del self._thisptr 249 | 250 | cdef setElem(self, G1[curve] *g): 251 | self.free() 252 | self._thisptr = g 253 | 254 | cdef G1[curve] *getElemRef(self): 255 | return self._thisptr 256 | 257 | cdef G1Py createElem(self, G1[curve] *g): 258 | cdef G1Py g1 = G1Py(init=False) 259 | g1.setElem(g) 260 | return g1 261 | 262 | cpdef G1Py mul(self, BigNum bgpy): 263 | cdef G1[curve] *newptr 264 | 265 | cdef Fr[curve] bg = bgpy.getElemRef()[0] 266 | cdef G1Py elem 267 | if self.g1_table != NULL: 268 | newptr = new G1[curve](g1_mul(self.g1_window_size, self.g1_table, bg)) 269 | else: 270 | newptr = new G1[curve](bg * self.getElemRef()[0]) 271 | 272 | return self.createElem(newptr) 273 | 274 | 275 | cpdef G1Py add(self, G1Py other): 276 | cdef G1[curve] *newptr 277 | newptr = new G1[curve](self.getElemRef()[0] + other.getElemRef()[0]) 278 | return self.createElem(newptr) 279 | 280 | cpdef G1Py sub(self, G1Py other): 281 | cdef G1[curve] *newptr 282 | newptr = new G1[curve](self.getElemRef()[0] - other.getElemRef()[0]) 283 | return self.createElem(newptr) 284 | 285 | cpdef eq(self, G1Py other): 286 | return self.getElemRef()[0] == other.getElemRef()[0] 287 | 288 | def __mul__(x, y): 289 | cdef G1Py g1 290 | cdef BigNum bg 291 | cdef Fr[curve] *fr 292 | 293 | if not (isinstance(x, G1Py) or isinstance(y, G1Py)): 294 | return NotImplemented 295 | 296 | if isinstance(x, G1Py): 297 | g1 = x 298 | if isinstance(y, BigNum): 299 | bg = y 300 | elif isinstance(y, int) or isinstance(y, long): 301 | bg = BigNum(y) 302 | else: 303 | return NotImplemented 304 | else: 305 | g1 = y 306 | if isinstance(x, BigNum): 307 | bg = x 308 | elif isinstance(x, int) or isinstance(x, long): 309 | bg = BigNum(x) 310 | else: 311 | return NotImplemented 312 | 313 | return g1.mul(bg) 314 | 315 | def __hash__(self): 316 | cdef G1[curve] *elem = new G1[curve](self.getElemRef()[0]) 317 | 318 | elem[0].to_affine_coordinates() 319 | 320 | cdef string mystr = elem[0].coord[0].toString(10) + \ 321 | elem[0].coord[1].toString(10) + \ 322 | elem[0].coord[2].toString(10) 323 | 324 | return hash(mystr) 325 | 326 | def __add__(x, y): 327 | cdef G1Py left, right 328 | 329 | if not (isinstance(x, G1Py) and isinstance(y, G1Py)): 330 | return NotImplemented 331 | 332 | left = x 333 | right = y 334 | 335 | return left.add(right) 336 | 337 | def __sub__(x, y): 338 | cdef G1Py left, right 339 | 340 | if not (isinstance(x, G1Py) and isinstance(y, G1Py)): 341 | return NotImplemented 342 | 343 | left = x 344 | right = y 345 | 346 | return left.sub(right) 347 | 348 | def __richcmp__(x, y, int op): 349 | cdef G1Py left, right 350 | 351 | if op != 2: 352 | # not == 353 | return NotImplemented 354 | 355 | if not (isinstance(x, G1Py) and isinstance(y, G1Py)): 356 | return NotImplemented 357 | 358 | left = x 359 | right = y 360 | 361 | return left.eq(right) 362 | 363 | cpdef pyprint(self): 364 | self.getElemRef()[0].cprint() 365 | 366 | 367 | cdef class G2Py: 368 | cdef G2[curve] *_thisptr 369 | cdef size_t g2_exp_count 370 | cdef size_t g2_window_size 371 | cdef window_table[G2[curve]] *g2_table 372 | 373 | def __cinit__(self, init=True): 374 | if init: 375 | self._thisptr = new G2[curve](get_g2_gen()) 376 | 377 | def __dealloc__(self): 378 | self.free() 379 | if self.g2_table != NULL: 380 | del self.g2_table 381 | 382 | def initWindowTable(self, int n): 383 | self.g2_exp_count = n + 6 384 | self.g2_window_size = get_g2_exp_window_size(self.g2_exp_count) 385 | self.g2_table = new window_table[G2[curve]](get_g2_window_table(self.g2_window_size, self.getElemRef()[0])) 386 | 387 | @staticmethod 388 | def inf(): 389 | cdef G2[curve] *newptr 390 | cdef G2Py g = G2Py(init=False) 391 | newptr = new G2[curve](get_g2_zero()) 392 | g.setElem(newptr) 393 | return g 394 | 395 | def free(self): 396 | if self._thisptr != NULL: 397 | del self._thisptr 398 | 399 | cdef setElem(self, G2[curve] *g): 400 | self.free() 401 | self._thisptr = g 402 | 403 | cdef G2[curve] *getElemRef(self): 404 | return self._thisptr 405 | 406 | cdef createElem(self, G2[curve] *g): 407 | cdef G2Py g2 = G2Py(init=False) 408 | g2.setElem(g) 409 | return g2 410 | 411 | cpdef G2Py mul(self, BigNum bgpy): 412 | cdef G2[curve] *newptr 413 | cdef Fr[curve] bg = bgpy.getElemRef()[0] 414 | 415 | if self.g2_table != NULL: 416 | newptr = new G2[curve](g2_mul(self.g2_window_size, self.g2_table, bg)) 417 | else: 418 | newptr = new G2[curve](bg * self.getElemRef()[0]) 419 | 420 | return self.createElem(newptr) 421 | 422 | cpdef G2Py add(self, G2Py other): 423 | cdef G2[curve] *newptr 424 | newptr = new G2[curve](self.getElemRef()[0] + other.getElemRef()[0]) 425 | return self.createElem(newptr) 426 | 427 | cpdef G2Py sub(self, G2Py other): 428 | cdef G2[curve] *newptr 429 | newptr = new G2[curve](self.getElemRef()[0] - other.getElemRef()[0]) 430 | return self.createElem(newptr) 431 | 432 | cpdef eq(self, G2Py other): 433 | return self.getElemRef()[0] == other.getElemRef()[0] 434 | 435 | def __mul__(x, y): 436 | cdef G2Py g2 437 | cdef BigNum bg 438 | cdef Fr[curve] *fr 439 | 440 | if not (isinstance(x, G2Py) or isinstance(y, G2Py)): 441 | return NotImplemented 442 | 443 | if isinstance(x, G2Py): 444 | if isinstance(y, BigNum): 445 | bg = y 446 | elif isinstance(y, int): 447 | fr = new Fr[curve](y) 448 | bg = BigNum(init=False) 449 | bg.setElem(fr) 450 | else: 451 | return NotImplemented 452 | g2 = x 453 | elif isinstance(x, BigNum): 454 | g2 = y 455 | bg = x 456 | elif isinstance(x, int): 457 | g2 = y 458 | fr = new Fr[curve](x) 459 | bg = BigNum(init=False) 460 | bg.setElem(fr) 461 | else: 462 | return NotImplemented 463 | 464 | return g2.mul(bg) 465 | 466 | def __hash__(self): 467 | cdef G2[curve] *elem = new G2[curve](self.getElemRef()[0]) 468 | 469 | elem[0].to_affine_coordinates() 470 | 471 | cdef string mystr = elem[0].coord[0].toString(10) + \ 472 | elem[0].coord[1].toString(10) + \ 473 | elem[0].coord[2].toString(10) 474 | 475 | return hash(mystr) 476 | 477 | def __add__(x, y): 478 | cdef G2Py left, right 479 | 480 | if not (isinstance(x, G2Py) and isinstance(y, G2Py)): 481 | return NotImplemented 482 | 483 | left = x 484 | right = y 485 | 486 | return left.add(right) 487 | 488 | def __sub__(x, y): 489 | cdef G2Py left, right 490 | 491 | if not (isinstance(x, G2Py) and isinstance(y, G2Py)): 492 | return NotImplemented 493 | 494 | left = x 495 | right = y 496 | 497 | return left.sub(right) 498 | 499 | def __richcmp__(x, y, op): 500 | cdef G2Py left, right 501 | 502 | if op != 2: 503 | # not == 504 | return NotImplemented 505 | 506 | if not (isinstance(x, G2Py) and isinstance(y, G2Py)): 507 | return NotImplemented 508 | 509 | left = x 510 | right = y 511 | 512 | return left.eq(right) 513 | 514 | cpdef pyprint(self): 515 | self.getElemRef()[0].cprint() 516 | 517 | 518 | cdef class GTPy: 519 | cdef GT[curve] *_thisptr 520 | 521 | def __cinit__(self, init=True): 522 | if init: 523 | self._thisptr = new GT[curve]() 524 | 525 | def __dealloc__(self): 526 | self.free() 527 | 528 | def free(self): 529 | if self._thisptr != NULL: 530 | del self._thisptr 531 | 532 | def __mul__(x, y): 533 | cdef GTPy left, right 534 | 535 | if not (isinstance(x, GTPy) and isinstance(y, GTPy)): 536 | return NotImplemented 537 | 538 | left = x 539 | right = y 540 | 541 | return left.mul(right) 542 | 543 | def __pow__(x, y, z): 544 | cdef GTPy gt 545 | cdef BigNum bg 546 | 547 | if not (isinstance(x, GTPy) and isinstance(y, BigNum)): 548 | return NotImplemented 549 | 550 | gt = x 551 | bg = y 552 | 553 | return gt.pow(bg) 554 | 555 | def __richcmp__(x, y, op): 556 | cdef GTPy left, right 557 | if op != 2 or not(isinstance(x, GTPy) and isinstance(y, GTPy)): 558 | return NotImplemented 559 | 560 | left = x 561 | right = y 562 | 563 | return left.eq(right) 564 | 565 | cpdef GTPy inv(self): 566 | cdef GT[curve] *newptr 567 | newptr = new GT[curve](self.getElemRef()[0].unitary_inverse()) 568 | return self.createElem(newptr) 569 | 570 | cdef GT[curve]* getElemRef(self): 571 | return self._thisptr 572 | 573 | cdef setElem(self, GT[curve] *g): 574 | self.free() 575 | self._thisptr = g 576 | 577 | cdef GTPy createElem(self, GT[curve] *g): 578 | cdef GTPy gt = GTPy(init=False) 579 | gt.setElem(g) 580 | return gt 581 | 582 | cpdef GTPy mul(self, GTPy other): 583 | cdef GT[curve] *newptr 584 | newptr = new GT[curve](self.getElemRef()[0] * other.getElemRef()[0]) 585 | return self.createElem(newptr) 586 | 587 | cpdef GTPy pow(self, BigNum bg): 588 | cdef GT[curve] *newptr 589 | cdef Fr[curve] fr = bg.getElemRef()[0] 590 | newptr = new GT[curve](self.getElemRef()[0] ^ fr) 591 | return self.createElem(newptr) 592 | 593 | cpdef bool eq(self, GTPy other): 594 | return self.getElemRef()[0] == other.getElemRef()[0] 595 | 596 | @staticmethod 597 | def one(): 598 | cdef GTPy gt = GTPy(init=False) 599 | cdef GT[curve] *newptr 600 | newptr = new GT[curve](get_gt_one()) 601 | gt.setElem(newptr) 602 | return gt 603 | 604 | @staticmethod 605 | def pair(G1Py g1, G2Py g2): 606 | cdef GTPy gt = GTPy(init=False) 607 | cdef GT[curve] *newptr 608 | newptr = new GT[curve](reduced_pairing(g1.getElemRef()[0], g2.getElemRef()[0])) 609 | gt.setElem(newptr) 610 | return gt 611 | 612 | cpdef pyprint(self): 613 | self.getElemRef()[0].cprint() 614 | 615 | 616 | cdef class LibffPy: 617 | cdef G1Py g1 618 | cdef G2Py g2 619 | 620 | def __init__(self, int n): 621 | init_public_params() 622 | self.g1 = G1Py() 623 | self.g2 = G2Py() 624 | 625 | self.g1.initWindowTable(n) 626 | self.g2.initWindowTable(n) 627 | 628 | def order(self): 629 | return BigNum.getOrder() 630 | 631 | def gen1(self): 632 | return self.g1 633 | 634 | def gen2(self): 635 | return self.g2 636 | 637 | def pair(self, G1Py g1, G2Py g2): 638 | gt = GTPy.pair(g1, g2) 639 | return gt 640 | -------------------------------------------------------------------------------- /libffpy/setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from distutils.core import setup 3 | from distutils.extension import Extension 4 | from Cython.Build import cythonize 5 | 6 | from Cython.Distutils import build_ext 7 | 8 | 9 | os.environ["CC"] = "g++" 10 | os.environ["CXX"] = "g++" 11 | 12 | setup( 13 | name='libffpy', 14 | ext_modules=cythonize( 15 | Extension( 16 | "libffpy", 17 | sources=["libffpy.pyx", "libff_wrapper.cpp"], 18 | language="c++", 19 | include_dirs=["/usr/local/include/libff"], 20 | library_dirs = ["/usr/local/lib"], 21 | extra_compile_args = ["-std=c++11", "-fPIC", "-shared", "-w", "-static"], 22 | extra_link_args = ["-lgmp", "-lff", "-lsnark", "-lcrypto", "-fopenmp", "-g"] 23 | ) 24 | ), 25 | cmdclass = {'build_ext': build_ext} 26 | ) 27 | -------------------------------------------------------------------------------- /libffpy/tests/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for the libff wrapper 3 | """ 4 | 5 | -------------------------------------------------------------------------------- /libffpy/tests/test_bignum.py: -------------------------------------------------------------------------------- 1 | from libffpy import LibffPy, BigNum 2 | 3 | import unittest 4 | 5 | MAX = 100 6 | 7 | class BigNumTest(unittest.TestCase): 8 | def setUp(self): 9 | l = LibffPy(MAX) 10 | 11 | def test_get_order(self): 12 | order = BigNum(num=0) 13 | self.assertEqual(BigNum.getOrder(), order) 14 | 15 | def test_add(self): 16 | first = 100 17 | second = 337 18 | bg1 = BigNum(first) 19 | bg2 = BigNum(second) 20 | 21 | self.assertEqual(bg1 + bg2, BigNum(first + second)) 22 | 23 | def test_add_int(self): 24 | first = 100 25 | second = 337 26 | 27 | bg1 = BigNum(first) 28 | self.assertEqual(bg1 + second, BigNum(first + second)) 29 | 30 | def test_sub(self): 31 | first = 100 32 | second = 337 33 | bg1 = BigNum(first) 34 | bg2 = BigNum(second) 35 | 36 | self.assertEqual(bg1 - bg2, BigNum(first - second)) 37 | self.assertEqual(bg2 - bg1, BigNum(second - first)) 38 | 39 | def test_sub_int(self): 40 | first = 100 41 | second = 337 42 | bg1 = BigNum(first) 43 | 44 | self.assertEqual(bg1 - second, BigNum(first - second)) 45 | self.assertEqual(second - bg1, BigNum(second - first)) 46 | 47 | def test_eq(self): 48 | first = 100 49 | second = 337 50 | bg1 = BigNum(first) 51 | bg2 = BigNum(second) 52 | 53 | self.assertEqual(bg1, BigNum(first)) 54 | self.assertNotEqual(bg1, bg2) 55 | 56 | def test_pow(self): 57 | num = 2 58 | p = 2 59 | bg = BigNum(num) ** p 60 | 61 | self.assertEqual(bg, BigNum(num ** p)) 62 | 63 | def test_mod_inverse(self): 64 | bg = BigNum() 65 | 66 | self.assertEqual(bg * bg.mod_inverse(), BigNum(1)) 67 | 68 | def test_mul(self): 69 | first = 10 70 | second = 20 71 | 72 | bg1 = BigNum(first) 73 | bg2 = BigNum(second) 74 | 75 | self.assertEqual(bg1 * bg2, BigNum(first * second)) 76 | 77 | def test_mul_int(self): 78 | first = 10 79 | second = 20 80 | 81 | bg = BigNum(first) 82 | 83 | self.assertEqual(bg * second, BigNum(first * second)) 84 | 85 | def test_neg(self): 86 | num = 10 87 | 88 | bg = BigNum(num) 89 | 90 | self.assertEqual(-bg, BigNum(-num)) 91 | 92 | 93 | if __name__ == '__main__': 94 | unittest.main() 95 | -------------------------------------------------------------------------------- /libffpy/tests/test_g1.py: -------------------------------------------------------------------------------- 1 | from libffpy import LibffPy, G1Py, BigNum 2 | 3 | import unittest 4 | 5 | MAX = 100 6 | class G1Test(unittest.TestCase): 7 | def setUp(self): 8 | LibffPy(MAX) 9 | 10 | def test_inf(self): 11 | inf = G1Py.inf() 12 | elem = G1Py() 13 | elem2 = elem * 10 14 | 15 | self.assertEqual(inf + elem, elem) 16 | self.assertEqual(inf + elem2, elem2) 17 | 18 | def mul_test(self, g1): 19 | # create N - 1 BigNum 20 | bg = [BigNum() for _ in xrange(MAX - 1)] 21 | # get the sum of the BigNums 22 | s = reduce((lambda x, y: x + y), bg) 23 | # Nth element of bg is order + 1 - s, so sum(bg) = order + 1 24 | # so g1 * bg[0] + g1 * bg[1] + ... + g1 * bg[N] == g1 * sum(bg) == 25 | # == g1 * (order + 1) == g1 26 | bg.append(bg[0].getOrder() + 1 - s) 27 | 28 | res = [g1 * e for e in bg] 29 | s = reduce((lambda x, y: x + y), res) 30 | 31 | self.assertEqual(s, g1) 32 | 33 | def test_mul_without_window_table(self): 34 | # get generator 35 | g1 = G1Py() 36 | 37 | self.mul_test(g1) 38 | 39 | def test_mul_with_window_table(self): 40 | g1 = G1Py() 41 | g1.initWindowTable(MAX) 42 | 43 | self.mul_test(g1) 44 | 45 | def test_mul_with_int(self): 46 | g1 = G1Py() 47 | g2 = G1Py() 48 | 49 | self.assertEqual(g1 * 2, g2 * 2) 50 | 51 | def test_addition(self): 52 | g1 = G1Py() 53 | g2 = G1Py() 54 | 55 | self.assertEqual(g1 + g1, g2 + g2) 56 | 57 | self.assertNotEqual(g1, g2 + g2) 58 | 59 | def test_sub(self): 60 | g1 = G1Py() 61 | g2 = G1Py() 62 | g3 = g1 * 2 # == g2 * 2 63 | 64 | self.assertEqual(g3 - g1, g3 - g2) 65 | self.assertEqual(g1 - g3, g2 - g3) 66 | self.assertNotEqual(g3 - g1, g2) 67 | 68 | def test_hash(self): 69 | g1 = G1Py() 70 | g2 = G1Py() 71 | g3 = g1 * 2 72 | 73 | self.assertEqual(hash(g1), hash(g2)) 74 | 75 | self.assertNotEqual(hash(g1), hash(g3)) 76 | 77 | 78 | if __name__ == '__main__': 79 | unittest.main() 80 | -------------------------------------------------------------------------------- /libffpy/tests/test_g2.py: -------------------------------------------------------------------------------- 1 | from libffpy import LibffPy, G2Py, BigNum 2 | 3 | import unittest 4 | 5 | MAX = 100 6 | 7 | class G1Test(unittest.TestCase): 8 | def setUp(self): 9 | LibffPy(MAX) 10 | 11 | def test_inf(self): 12 | inf = G2Py.inf() 13 | elem = G2Py() 14 | elem2 = elem * 10 15 | 16 | self.assertEqual(inf + elem, elem) 17 | self.assertEqual(inf + elem2, elem2) 18 | 19 | def mul_test(self, g1): 20 | # create N - 1 BigNum 21 | bg = [BigNum() for _ in xrange(MAX - 1)] 22 | # get the sum of the BigNums 23 | s = reduce((lambda x, y: x + y), bg) 24 | # Nth element of bg is order + 1 - s, so sum(bg) = order + 1 25 | # so g1 * bg[0] + g1 * bg[1] + ... + g1 * bg[N] == g1 * sum(bg) == 26 | # == g1 * (order + 1) == g1 27 | bg.append(bg[0].getOrder() + 1 - s) 28 | 29 | res = [g1 * e for e in bg] 30 | s = reduce((lambda x, y: x + y), res) 31 | 32 | self.assertEqual(s, g1) 33 | 34 | def test_mul_without_window_table(self): 35 | # get generator 36 | g1 = G2Py() 37 | 38 | self.mul_test(g1) 39 | 40 | def test_mul_with_window_table(self): 41 | g1 = G2Py() 42 | g1.initWindowTable(MAX) 43 | 44 | self.mul_test(g1) 45 | 46 | def test_mul_with_int(self): 47 | g1 = G2Py() 48 | g2 = G2Py() 49 | 50 | self.assertEqual(g1 * 2, g2 * 2) 51 | 52 | self.assertNotEqual(g1 * 2, g2 * 3) 53 | 54 | def test_addition(self): 55 | g1 = G2Py() 56 | g2 = G2Py() 57 | 58 | self.assertEqual(g1 + g1, g2 + g2) 59 | 60 | self.assertNotEqual(g1, g2 + g2) 61 | 62 | def test_sub(self): 63 | g1 = G2Py() 64 | g2 = G2Py() 65 | g3 = g1 * 2 # == g2 * 2 66 | 67 | self.assertEqual(g3 - g1, g3 - g2) 68 | self.assertEqual(g1 - g3, g2 - g3) 69 | self.assertNotEqual(g3 - g1, g2) 70 | 71 | def test_hash(self): 72 | g1 = G2Py() 73 | g2 = G2Py() 74 | g3 = g1 * 3 75 | 76 | self.assertEqual(hash(g1), hash(g2)) 77 | 78 | self.assertNotEqual(hash(g1), hash(g3)) 79 | 80 | 81 | if __name__ == '__main__': 82 | unittest.main() 83 | -------------------------------------------------------------------------------- /libffpy/tests/test_gt.py: -------------------------------------------------------------------------------- 1 | from libffpy import LibffPy, BigNum, GTPy 2 | 3 | import unittest 4 | 5 | MAX = 100 6 | 7 | class BigNumTest(unittest.TestCase): 8 | def setUp(self): 9 | self.libff = LibffPy(MAX) 10 | self.g1 = self.libff.gen1() 11 | self.g2 = self.libff.gen2() 12 | 13 | def test_pair(self): 14 | gt1 = self.libff.pair(self.g1, self.g2) 15 | gt2= self.libff.pair(self.g1, self.g2) 16 | gt3= self.libff.pair(self.g1, self.g2 * 2) 17 | 18 | self.assertEqual(gt1, gt2) 19 | self.assertNotEqual(gt1, gt3) 20 | 21 | def test_pow(self): 22 | gt = self.libff.pair(self.g1, self.g2) 23 | bg = BigNum(3) 24 | 25 | self.assertEqual(gt ** bg, gt * gt * gt) 26 | 27 | 28 | if __name__ == '__main__': 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from setuptools import setup, find_packages 4 | from distutils.extension import Extension 5 | 6 | from subprocess import call 7 | 8 | def get_long_desc(): 9 | with open("README.md", "r") as readme: 10 | desc = readme.read() 11 | 12 | return desc 13 | 14 | 15 | def setup_package(): 16 | setup( 17 | name='flz16', 18 | version='0.0.1', 19 | description='An implementation of a re-encryption mix-net', 20 | long_description=get_long_desc(), 21 | url='https://github.com/eellak/gsoc17module-zeus', 22 | license='AGPL-3.0', 23 | packages = find_packages(exclude=["*.libffpy", "*.libffpy.*", "libffpy.*", "libffpy"]), 24 | install_requires=[] 25 | ) 26 | 27 | if __name__ == '__main__': 28 | setup_package() 29 | --------------------------------------------------------------------------------