├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── cli ├── .gitignore └── cli.go ├── go.mod ├── go.sum ├── parsers ├── parsers.go └── parsers_test.go ├── prover ├── arithmetic.go ├── arithmetic_test.go ├── gextra.go ├── gextra_test.go ├── ifft.go ├── prover.go ├── prover_test.go └── tables.md ├── testdata ├── .gitignore ├── circuit10k │ ├── circuit.circom │ └── inputs.json ├── circuit1k │ ├── circuit.circom │ └── inputs.json ├── circuit20k │ ├── circuit.circom │ └── inputs.json ├── circuit5k │ ├── circuit.circom │ └── inputs.json ├── clean-gereated-files.sh ├── compile-circuits.sh ├── package-lock.json └── package.json ├── types └── types.go └── verifier ├── verifier.go └── verifier_test.go /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Test 3 | on: [push, pull_request] 4 | jobs: 5 | test: 6 | # matrix strategy from: https://github.com/mvdan/github-actions-golang/blob/master/.github/workflows/test.yml 7 | strategy: 8 | matrix: 9 | go-version: [1.13.x, 1.14.x] 10 | platform: [ubuntu-latest] 11 | runs-on: ${{ matrix.platform }} 12 | steps: 13 | - name: Install Go 14 | uses: actions/setup-go@v1 15 | with: 16 | go-version: ${{ matrix.go-version }} 17 | - name: Install Nodejs 18 | uses: actions/setup-node@v1 19 | with: 20 | node-version: '10.x' 21 | - name: Checkout code 22 | uses: actions/checkout@v2 23 | - name: Compile circuits and execute Go tests 24 | run: | 25 | cd testdata && sh ./compile-circuits.sh && cd .. 26 | go run cli/cli.go -prove -pk=testdata/circuit1k/proving_key.json -witness=testdata/circuit1k/witness.json -proof=testdata/circuit1k/proof.json -public=testdata/circuit1k/public.json 27 | go run cli/cli.go -prove -pk=testdata/circuit5k/proving_key.json -witness=testdata/circuit5k/witness.json -proof=testdata/circuit5k/proof.json -public=testdata/circuit5k/public.json 28 | go test ./... 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | testdata/*/*.json 2 | testdata/*/*.wasm 3 | testdata/*/*.cpp 4 | testdata/*/*.sym 5 | testdata/*/*.r1cs 6 | testdata/*/*.sol 7 | testdata/*/*.bin 8 | !testdata/*/inputs.json 9 | cli/*.json 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-circom-prover-verifier [![GoDoc](https://godoc.org/github.com/iden3/go-circom-prover-verifier?status.svg)](https://godoc.org/github.com/iden3/go-circom-prover-verifier) [![Go Report Card](https://goreportcard.com/badge/github.com/iden3/go-circom-prover-verifier)](https://goreportcard.com/report/github.com/iden3/go-circom-prover-verifier) [![Test](https://github.com/iden3/go-circom-prover-verifier/workflows/Test/badge.svg)](https://github.com/iden3/go-circom-prover-verifier/actions?query=workflow%3ATest) 2 | 3 | Go implementation of the [Groth16 protocol](https://eprint.iacr.org/2016/260.pdf) zkSNARK prover & verifier compatible with [circom](https://github.com/iden3/circom). 4 | 5 | 6 | Using [bn256](https://github.com/ethereum/go-ethereum/tree/master/crypto/bn256/cloudflare) (used by [go-ethereum](https://github.com/ethereum/go-ethereum)) for the Pairing curve operations. 7 | 8 | ### Example 9 | 10 | - Generate Proof 11 | ```go 12 | import ( 13 | "github.com/iden3/go-circom-prover-verifier/parsers" 14 | "github.com/iden3/go-circom-prover-verifier/prover" 15 | "github.com/iden3/go-circom-prover-verifier/verifier" 16 | ) 17 | 18 | [...] 19 | 20 | // read ProvingKey & Witness files 21 | provingKeyJson, _ := ioutil.ReadFile("../testdata/small/proving_key.json") 22 | witnessJson, _ := ioutil.ReadFile("../testdata/small/witness.json") 23 | 24 | // parse Proving Key 25 | pk, _ := parsers.ParsePk(provingKeyJson) 26 | 27 | // parse Witness 28 | w, _ := parsers.ParseWitness(witnessJson) 29 | 30 | // generate the proof 31 | proof, pubSignals, _ := prover.GenerateProof(pk, w) 32 | 33 | // print proof & publicSignals 34 | proofStr, _ := parsers.ProofToJson(proof) 35 | publicStr, _ := json.Marshal(parsers.ArrayBigIntToString(pubSignals)) 36 | fmt.Println(proofStr) 37 | fmt.Println(publicStr) 38 | ``` 39 | 40 | - Verify Proof 41 | ```go 42 | // read proof & verificationKey & publicSignals 43 | proofJson, _ := ioutil.ReadFile("../testdata/big/proof.json") 44 | vkJson, _ := ioutil.ReadFile("../testdata/big/verification_key.json") 45 | publicJson, _ := ioutil.ReadFile("../testdata/big/public.json") 46 | 47 | // parse proof & verificationKey & publicSignals 48 | public, _ := parsers.ParsePublicSignals(publicJson) 49 | proof, _ := parsers.ParseProof(proofJson) 50 | vk, _ := parsers.ParseVk(vkJson) 51 | 52 | // verify the proof with the given verificationKey & publicSignals 53 | v := verifier.Verify(vk, proof, public) 54 | fmt.Println(v) 55 | ``` 56 | 57 | ## CLI 58 | 59 | From the `cli` directory: 60 | 61 | - Show options 62 | ``` 63 | > go run cli.go -help 64 | go-circom-prover-verifier 65 | v0.0.1 66 | Usage of /tmp/go-build620318239/b001/exe/cli: 67 | -proof string 68 | proof path (default "proof.json") 69 | -prove 70 | prover mode 71 | -provingkey string 72 | provingKey path (default "proving_key.json") 73 | -public string 74 | public signals path (default "public.json") 75 | -verificationkey string 76 | verificationKey path (default "verification_key.json") 77 | -verify 78 | verifier mode 79 | -witness string 80 | witness path (default "witness.json") 81 | ``` 82 | 83 | - Prove 84 | ``` 85 | > go run cli.go -prove -provingkey=../testdata/circuit5k/proving_key.json -witness=../testdata/circuit5k/witness.json 86 | ``` 87 | - Verify 88 | ``` 89 | > go run cli.go -verify -verificationkey=../testdata/circuit5k/verification_key.json 90 | ``` 91 | -------------------------------------------------------------------------------- /cli/.gitignore: -------------------------------------------------------------------------------- 1 | cli 2 | -------------------------------------------------------------------------------- /cli/cli.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "time" 10 | 11 | "github.com/iden3/go-circom-prover-verifier/parsers" 12 | "github.com/iden3/go-circom-prover-verifier/prover" 13 | "github.com/iden3/go-circom-prover-verifier/verifier" 14 | ) 15 | 16 | const version = "v0.0.1" 17 | 18 | func main() { 19 | fmt.Println("go-circom-prover-verifier") 20 | fmt.Println(" ", version) 21 | 22 | prove := flag.Bool("prove", false, "prover mode") 23 | verify := flag.Bool("verify", false, "verifier mode") 24 | convert := flag.Bool("convert", false, "convert mode, to convert between proving_key.json to proving_key.go.bin") 25 | 26 | provingKeyPath := flag.String("pk", "proving_key.json", "provingKey path") 27 | witnessPath := flag.String("witness", "witness.json", "witness path") 28 | proofPath := flag.String("proof", "proof.json", "proof path") 29 | verificationKeyPath := flag.String("vk", "verification_key.json", "verificationKey path") 30 | publicPath := flag.String("public", "public.json", "public signals path") 31 | provingKeyBinPath := flag.String("pkbin", "proving_key.go.bin", "provingKey Bin path") 32 | 33 | flag.Parse() 34 | 35 | if *prove { 36 | err := cmdProve(*provingKeyPath, *witnessPath, *proofPath, *publicPath) 37 | if err != nil { 38 | fmt.Println("Error:", err) 39 | } 40 | os.Exit(0) 41 | } else if *verify { 42 | err := cmdVerify(*proofPath, *verificationKeyPath, *publicPath) 43 | if err != nil { 44 | fmt.Println("Error:", err) 45 | } 46 | os.Exit(0) 47 | } else if *convert { 48 | err := cmdConvert(*provingKeyPath, *provingKeyBinPath) 49 | if err != nil { 50 | fmt.Println("Error:", err) 51 | } 52 | os.Exit(0) 53 | } 54 | flag.PrintDefaults() 55 | } 56 | 57 | func cmdProve(provingKeyPath, witnessPath, proofPath, publicPath string) error { 58 | fmt.Println("zkSNARK Groth16 prover") 59 | 60 | fmt.Println("Reading proving key file:", provingKeyPath) 61 | provingKeyJson, err := ioutil.ReadFile(provingKeyPath) 62 | if err != nil { 63 | return err 64 | } 65 | pk, err := parsers.ParsePk(provingKeyJson) 66 | if err != nil { 67 | return err 68 | } 69 | 70 | fmt.Println("Reading witness file:", witnessPath) 71 | witnessJson, err := ioutil.ReadFile(witnessPath) 72 | if err != nil { 73 | return err 74 | } 75 | w, err := parsers.ParseWitness(witnessJson) 76 | if err != nil { 77 | return err 78 | } 79 | 80 | fmt.Println("Generating the proof") 81 | beforeT := time.Now() 82 | proof, pubSignals, err := prover.GenerateProof(pk, w) 83 | if err != nil { 84 | return err 85 | } 86 | fmt.Println("proof generation time elapsed:", time.Since(beforeT)) 87 | 88 | proofStr, err := parsers.ProofToJson(proof) 89 | if err != nil { 90 | return err 91 | } 92 | 93 | // write output 94 | err = ioutil.WriteFile(proofPath, proofStr, 0644) 95 | if err != nil { 96 | return err 97 | } 98 | publicStr, err := json.Marshal(parsers.ArrayBigIntToString(pubSignals)) 99 | if err != nil { 100 | return err 101 | } 102 | err = ioutil.WriteFile(publicPath, publicStr, 0644) 103 | if err != nil { 104 | return err 105 | } 106 | fmt.Println("Proof stored at:", proofPath) 107 | fmt.Println("PublicSignals stored at:", publicPath) 108 | return nil 109 | } 110 | 111 | func cmdVerify(proofPath, verificationKeyPath, publicPath string) error { 112 | fmt.Println("zkSNARK Groth16 verifier") 113 | 114 | proofJson, err := ioutil.ReadFile(proofPath) 115 | if err != nil { 116 | return err 117 | } 118 | vkJson, err := ioutil.ReadFile(verificationKeyPath) 119 | if err != nil { 120 | return err 121 | } 122 | publicJson, err := ioutil.ReadFile(publicPath) 123 | if err != nil { 124 | return err 125 | } 126 | 127 | public, err := parsers.ParsePublicSignals(publicJson) 128 | if err != nil { 129 | return err 130 | } 131 | proof, err := parsers.ParseProof(proofJson) 132 | if err != nil { 133 | return err 134 | } 135 | vk, err := parsers.ParseVk(vkJson) 136 | if err != nil { 137 | return err 138 | } 139 | 140 | v := verifier.Verify(vk, proof, public) 141 | fmt.Println("verification:", v) 142 | return nil 143 | } 144 | 145 | func cmdConvert(provingKeyPath, provingKeyBinPath string) error { 146 | fmt.Println("Convertion tool") 147 | 148 | provingKeyJson, err := ioutil.ReadFile(provingKeyPath) 149 | if err != nil { 150 | return err 151 | } 152 | pk, err := parsers.ParsePk(provingKeyJson) 153 | if err != nil { 154 | return err 155 | } 156 | 157 | fmt.Printf("Converting proving key json (%s)\nto go proving key binary (%s)\n", provingKeyPath, provingKeyBinPath) 158 | pkGBin, err := parsers.PkToGoBin(pk) 159 | if err != nil { 160 | return err 161 | } 162 | if err = ioutil.WriteFile(provingKeyBinPath, pkGBin, 0644); err != nil { 163 | return err 164 | } 165 | 166 | return nil 167 | } 168 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/iden3/go-circom-prover-verifier 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/ethereum/go-ethereum v1.9.13 7 | github.com/iden3/go-iden3-crypto v0.0.5 8 | github.com/stretchr/testify v1.4.0 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/Azure/azure-pipeline-go v0.2.1/go.mod h1:UGSo8XybXnIGZ3epmeBw7Jdz+HiUVpqIlpz/HKHylF4= 2 | github.com/Azure/azure-pipeline-go v0.2.2/go.mod h1:4rQ/NZncSvGqNkkOsNpOU1tgoNuIlp9AfUH5G1tvCHc= 3 | github.com/Azure/azure-storage-blob-go v0.7.0/go.mod h1:f9YQKtsG1nMisotuTPpO0tjNuEjKRYAcJU8/ydDI++4= 4 | github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= 5 | github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= 6 | github.com/Azure/go-autorest/autorest/adal v0.8.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= 7 | github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= 8 | github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= 9 | github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= 10 | github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= 11 | github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM= 12 | github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= 13 | github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= 14 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 15 | github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= 16 | github.com/OneOfOne/xxhash v1.2.5/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q= 17 | github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= 18 | github.com/VictoriaMetrics/fastcache v1.5.3/go.mod h1:+jv9Ckb+za/P1ZRg/sulP5Ni1v49daAVERr0H3CuscE= 19 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 20 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 21 | github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= 22 | github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847/go.mod h1:D/tb0zPVXnP7fmsLZjtdUhSsumbK/ij54UXjjVgMGxQ= 23 | github.com/aws/aws-sdk-go v1.25.48/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= 24 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 25 | github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6/go.mod h1:Dmm/EzmjnCiweXmzRIAiUWCInVmPgjkzgv5k4tVyXiQ= 26 | github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= 27 | github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= 28 | github.com/cespare/xxhash/v2 v2.0.1-0.20190104013014-3767db7a7e18/go.mod h1:HD5P3vAIAh+Y2GAxg0PrPN1P8WkepXGpjbUPDHJqqKM= 29 | github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 30 | github.com/cloudflare/cloudflare-go v0.10.2-0.20190916151808-a80f83b9add9/go.mod h1:1MxXX1Ux4x6mqPmjkUgTP1CdXIBXKX7T+Jk9Gxrmx+U= 31 | github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= 32 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 33 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 34 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 35 | github.com/dchest/blake512 v1.0.0/go.mod h1:FV1x7xPPLWukZlpDpWQ88rF/SFwZ5qbskrzhLMB92JI= 36 | github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ= 37 | github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= 38 | github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= 39 | github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= 40 | github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= 41 | github.com/dop251/goja v0.0.0-20200219165308-d1232e640a87/go.mod h1:Mw6PkjjMXWbTj+nnj4s3QPXq1jaT0s5pC0iFD4+BOAA= 42 | github.com/edsrzf/mmap-go v0.0.0-20160512033002-935e0e8a636c/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= 43 | github.com/elastic/gosigar v0.8.1-0.20180330100440-37f05ff46ffa/go.mod h1:cdorVVzy1fhmEqmtgqkoE3bYtCfSCkVyjTyCIo22xvs= 44 | github.com/ethereum/go-ethereum v1.8.27/go.mod h1:PwpWDrCLZrV+tfrhqqF6kPknbISMHaJv9Ln3kPCZLwY= 45 | github.com/ethereum/go-ethereum v1.9.12/go.mod h1:PvsVkQmhZFx92Y+h2ylythYlheEDt/uBgFbl61Js/jo= 46 | github.com/ethereum/go-ethereum v1.9.13 h1:rOPqjSngvs1VSYH2H+PMPiWt4VEulvNRbFgqiGqJM3E= 47 | github.com/ethereum/go-ethereum v1.9.13/go.mod h1:qwN9d1GLyDh0N7Ab8bMGd0H9knaji2jOBm2RrMGjXls= 48 | github.com/fatih/color v1.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= 49 | github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= 50 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 51 | github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= 52 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 53 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 54 | github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= 55 | github.com/go-sourcemap/sourcemap v2.1.2+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= 56 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 57 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 58 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 59 | github.com/golang/protobuf v1.3.2-0.20190517061210-b285ee9cfc6c/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 60 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 61 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 62 | github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= 63 | github.com/graph-gophers/graphql-go v0.0.0-20191115155744-f33e81362277/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= 64 | github.com/hashicorp/golang-lru v0.0.0-20160813221303-0a025b7e63ad/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= 65 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 66 | github.com/huin/goupnp v0.0.0-20161224104101-679507af18f3/go.mod h1:MZ2ZmwcBpvOoJ22IJsc7va19ZwoheaBk43rKg12SKag= 67 | github.com/iden3/go-iden3-crypto v0.0.4 h1:rGQEFBvX6d4fDxqkQTizVq5UefB+xdZAg8j5FQ6uv6g= 68 | github.com/iden3/go-iden3-crypto v0.0.4/go.mod h1:LLcgB7DLWAUs+8eBSKne+ZHy5z7xtAmlYlEz0M9M8gE= 69 | github.com/iden3/go-iden3-crypto v0.0.5-0.20200421133134-14c3144613d4 h1:C+WGAJM9G5MxU62cAVrcwivFLk1muyENjGD5DGADk5o= 70 | github.com/iden3/go-iden3-crypto v0.0.5-0.20200421133134-14c3144613d4/go.mod h1:XKw1oDwYn2CIxKOtr7m/mL5jMn4mLOxAxtZBRxQBev8= 71 | github.com/iden3/go-iden3-crypto v0.0.5 h1:inCSm5a+ry+nbpVTL/9+m6UcIwSv6nhUm0tnIxEbcps= 72 | github.com/iden3/go-iden3-crypto v0.0.5/go.mod h1:XKw1oDwYn2CIxKOtr7m/mL5jMn4mLOxAxtZBRxQBev8= 73 | github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= 74 | github.com/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= 75 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= 76 | github.com/julienschmidt/httprouter v1.1.1-0.20170430222011-975b5c4c7c21/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 77 | github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= 78 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 79 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 80 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 81 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 82 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 83 | github.com/mattn/go-colorable v0.1.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= 84 | github.com/mattn/go-ieproxy v0.0.0-20190610004146-91bb50d98149/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= 85 | github.com/mattn/go-ieproxy v0.0.0-20190702010315-6dee0af9227d/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= 86 | github.com/mattn/go-isatty v0.0.5-0.20180830101745-3fb116b82035/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= 87 | github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= 88 | github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= 89 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 90 | github.com/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0= 91 | github.com/naoina/toml v0.1.2-0.20170918210437-9fafd6967416/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E= 92 | github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= 93 | github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= 94 | github.com/olekukonko/tablewriter v0.0.2-0.20190409134802-7e037d187b0c/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= 95 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 96 | github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 97 | github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 98 | github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= 99 | github.com/pborman/uuid v0.0.0-20170112150404-1b00554d8222/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34= 100 | github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= 101 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 102 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 103 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 104 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 105 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 106 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 107 | github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 108 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 109 | github.com/prometheus/tsdb v0.6.2-0.20190402121629-4f204dcbc150/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= 110 | github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= 111 | github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= 112 | github.com/rs/xhandler v0.0.0-20160618193221-ed27b6fd6521/go.mod h1:RvLn4FgxWubrpZHtQLnOf6EwhN2hEMusxZOhcW9H3UQ= 113 | github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 114 | github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= 115 | github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= 116 | github.com/spaolacci/murmur3 v1.0.1-0.20190317074736-539464a789e9/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= 117 | github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4/go.mod h1:RZLeN1LMWmRsyYjvAu+I6Dm9QmlDaIIt+Y+4Kd7Tp+Q= 118 | github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw= 119 | github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU= 120 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 121 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 122 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 123 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 124 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 125 | github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= 126 | github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= 127 | github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= 128 | github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208/go.mod h1:IotVbo4F+mw0EzQ08zFqg7pK3FebNXpaMsRy2RT+Ees= 129 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 130 | golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 131 | golang.org/x/crypto v0.0.0-20200311171314-f7b00557c8c4/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 132 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 133 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 134 | golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 135 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 136 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 137 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 138 | golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 139 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 140 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 141 | golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So= 142 | golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 143 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 144 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 145 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 146 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 147 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 148 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 149 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 150 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 151 | gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= 152 | gopkg.in/olebedev/go-duktape.v3 v3.0.0-20190213234257-ec84240a7772/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= 153 | gopkg.in/olebedev/go-duktape.v3 v3.0.0-20200316214253-d7b0ff38cac9/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= 154 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 155 | gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0= 156 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 157 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 158 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 159 | gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= 160 | -------------------------------------------------------------------------------- /parsers/parsers.go: -------------------------------------------------------------------------------- 1 | package parsers 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/binary" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "io" 11 | "math/big" 12 | "os" 13 | "sort" 14 | "strconv" 15 | "strings" 16 | 17 | bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare" 18 | "github.com/iden3/go-circom-prover-verifier/types" 19 | ) 20 | 21 | // PkString is the equivalent to the Pk struct in string representation, containing the ProvingKey 22 | type PkString struct { 23 | A [][]string `json:"A"` 24 | B2 [][][]string `json:"B2"` 25 | B1 [][]string `json:"B1"` 26 | C [][]string `json:"C"` 27 | NVars int `json:"nVars"` 28 | NPublic int `json:"nPublic"` 29 | VkAlpha1 []string `json:"vk_alfa_1"` 30 | VkDelta1 []string `json:"vk_delta_1"` 31 | VkBeta1 []string `json:"vk_beta_1"` 32 | VkBeta2 [][]string `json:"vk_beta_2"` 33 | VkDelta2 [][]string `json:"vk_delta_2"` 34 | HExps [][]string `json:"hExps"` 35 | DomainSize int `json:"domainSize"` 36 | PolsA []map[string]string `json:"polsA"` 37 | PolsB []map[string]string `json:"polsB"` 38 | } 39 | 40 | // WitnessString contains the Witness in string representation 41 | type WitnessString []string 42 | 43 | // ProofString is the equivalent to the Proof struct in string representation 44 | type ProofString struct { 45 | A []string `json:"pi_a"` 46 | B [][]string `json:"pi_b"` 47 | C []string `json:"pi_c"` 48 | Protocol string `json:"protocol"` 49 | } 50 | 51 | // VkString is the Verification Key data structure in string format (from json) 52 | type VkString struct { 53 | Alpha []string `json:"vk_alfa_1"` 54 | Beta [][]string `json:"vk_beta_2"` 55 | Gamma [][]string `json:"vk_gamma_2"` 56 | Delta [][]string `json:"vk_delta_2"` 57 | IC [][]string `json:"IC"` 58 | } 59 | 60 | // ParseWitness parses the json []byte data into the Witness struct 61 | func ParseWitness(wJson []byte) (types.Witness, error) { 62 | var ws WitnessString 63 | err := json.Unmarshal(wJson, &ws) 64 | if err != nil { 65 | return nil, err 66 | } 67 | 68 | var w types.Witness 69 | for i := 0; i < len(ws); i++ { 70 | bi, err := stringToBigInt(ws[i]) 71 | if err != nil { 72 | return nil, err 73 | } 74 | w = append(w, bi) 75 | } 76 | return w, nil 77 | } 78 | 79 | // ParsePk parses the json []byte data into the Pk struct 80 | func ParsePk(pkJson []byte) (*types.Pk, error) { 81 | var pkStr PkString 82 | err := json.Unmarshal(pkJson, &pkStr) 83 | if err != nil { 84 | return nil, err 85 | } 86 | pk, err := pkStringToPk(pkStr) 87 | return pk, err 88 | } 89 | 90 | func pkStringToPk(ps PkString) (*types.Pk, error) { 91 | var p types.Pk 92 | var err error 93 | 94 | p.A, err = arrayStringToG1(ps.A) 95 | if err != nil { 96 | return nil, err 97 | } 98 | p.B2, err = arrayStringToG2(ps.B2) 99 | if err != nil { 100 | return nil, err 101 | } 102 | p.B1, err = arrayStringToG1(ps.B1) 103 | if err != nil { 104 | return nil, err 105 | } 106 | p.C, err = arrayStringToG1(ps.C) 107 | if err != nil { 108 | return nil, err 109 | } 110 | 111 | p.NVars = ps.NVars 112 | p.NPublic = ps.NPublic 113 | 114 | p.VkAlpha1, err = stringToG1(ps.VkAlpha1) 115 | if err != nil { 116 | return nil, err 117 | } 118 | 119 | p.VkDelta1, err = stringToG1(ps.VkDelta1) 120 | if err != nil { 121 | return nil, err 122 | } 123 | 124 | p.VkBeta1, err = stringToG1(ps.VkBeta1) 125 | if err != nil { 126 | return nil, err 127 | } 128 | p.VkBeta2, err = stringToG2(ps.VkBeta2) 129 | if err != nil { 130 | return nil, err 131 | } 132 | p.VkDelta2, err = stringToG2(ps.VkDelta2) 133 | if err != nil { 134 | return nil, err 135 | } 136 | 137 | p.HExps, err = arrayStringToG1(ps.HExps) 138 | if err != nil { 139 | return nil, err 140 | } 141 | 142 | p.DomainSize = ps.DomainSize 143 | 144 | p.PolsA, err = polsStringToBigInt(ps.PolsA) 145 | if err != nil { 146 | return nil, err 147 | } 148 | p.PolsB, err = polsStringToBigInt(ps.PolsB) 149 | if err != nil { 150 | return nil, err 151 | } 152 | 153 | return &p, nil 154 | } 155 | 156 | func proofStringToProof(pr ProofString) (*types.Proof, error) { 157 | var p types.Proof 158 | var err error 159 | p.A, err = stringToG1(pr.A) 160 | if err != nil { 161 | return nil, err 162 | } 163 | 164 | p.B, err = stringToG2(pr.B) 165 | if err != nil { 166 | return nil, err 167 | } 168 | 169 | p.C, err = stringToG1(pr.C) 170 | if err != nil { 171 | return nil, err 172 | } 173 | 174 | return &p, nil 175 | } 176 | 177 | // ParseProof takes a json []byte and outputs the *Proof struct 178 | func ParseProof(pj []byte) (*types.Proof, error) { 179 | var pr ProofString 180 | err := json.Unmarshal(pj, &pr) 181 | if err != nil { 182 | return nil, err 183 | } 184 | p, err := proofStringToProof(pr) 185 | return p, err 186 | } 187 | 188 | // ParsePublicSignals takes a json []byte and outputs the []*big.Int struct 189 | func ParsePublicSignals(pj []byte) ([]*big.Int, error) { 190 | var pr []string 191 | err := json.Unmarshal(pj, &pr) 192 | if err != nil { 193 | return nil, err 194 | } 195 | var public []*big.Int 196 | for _, s := range pr { 197 | sb, err := stringToBigInt(s) 198 | if err != nil { 199 | return nil, err 200 | } 201 | public = append(public, sb) 202 | } 203 | return public, nil 204 | } 205 | 206 | // ParseVk takes a json []byte and outputs the *Vk struct 207 | func ParseVk(vj []byte) (*types.Vk, error) { 208 | var vr VkString 209 | err := json.Unmarshal(vj, &vr) 210 | if err != nil { 211 | return nil, err 212 | } 213 | v, err := vkStringToVk(vr) 214 | return v, err 215 | } 216 | 217 | func vkStringToVk(vr VkString) (*types.Vk, error) { 218 | var v types.Vk 219 | var err error 220 | v.Alpha, err = stringToG1(vr.Alpha) 221 | if err != nil { 222 | return nil, err 223 | } 224 | 225 | v.Beta, err = stringToG2(vr.Beta) 226 | if err != nil { 227 | return nil, err 228 | } 229 | 230 | v.Gamma, err = stringToG2(vr.Gamma) 231 | if err != nil { 232 | return nil, err 233 | } 234 | 235 | v.Delta, err = stringToG2(vr.Delta) 236 | if err != nil { 237 | return nil, err 238 | } 239 | 240 | for i := 0; i < len(vr.IC); i++ { 241 | p, err := stringToG1(vr.IC[i]) 242 | if err != nil { 243 | return nil, err 244 | } 245 | v.IC = append(v.IC, p) 246 | } 247 | 248 | return &v, nil 249 | } 250 | 251 | // polsStringToBigInt is for taking string polynomials and converting it to *big.Int polynomials 252 | func polsStringToBigInt(s []map[string]string) ([]map[int]*big.Int, error) { 253 | var o []map[int]*big.Int 254 | for i := 0; i < len(s); i++ { 255 | // var oi map[int]*big.Int 256 | oi := make(map[int]*big.Int) 257 | for j, v := range s[i] { 258 | si, err := stringToBigInt(v) 259 | if err != nil { 260 | return o, err 261 | } 262 | // oi = append(oi, si) 263 | jInt, err := strconv.Atoi(j) 264 | if err != nil { 265 | return o, err 266 | } 267 | oi[jInt] = si 268 | } 269 | o = append(o, oi) 270 | } 271 | return o, nil 272 | } 273 | 274 | // ArrayBigIntToString converts an []*big.Int into []string, used to output the Public Signals 275 | func ArrayBigIntToString(bi []*big.Int) []string { 276 | var s []string 277 | for i := 0; i < len(bi); i++ { 278 | s = append(s, bi[i].String()) 279 | } 280 | return s 281 | } 282 | 283 | func arrayStringToBigInt(s []string) ([]*big.Int, error) { 284 | var o []*big.Int 285 | for i := 0; i < len(s); i++ { 286 | si, err := stringToBigInt(s[i]) 287 | if err != nil { 288 | return o, nil 289 | } 290 | o = append(o, si) 291 | } 292 | return o, nil 293 | } 294 | 295 | func stringToBigInt(s string) (*big.Int, error) { 296 | base := 10 297 | if bytes.HasPrefix([]byte(s), []byte("0x")) { 298 | base = 16 299 | s = strings.TrimPrefix(s, "0x") 300 | } 301 | n, ok := new(big.Int).SetString(s, base) 302 | if !ok { 303 | return nil, fmt.Errorf("Can not parse string to *big.Int: %s", s) 304 | } 305 | return n, nil 306 | } 307 | 308 | func addPadding32(b []byte) []byte { 309 | if len(b) != 32 { 310 | b = addZPadding(b) 311 | } 312 | return b 313 | } 314 | 315 | func addZPadding(b []byte) []byte { 316 | var z [32]byte 317 | var r []byte 318 | r = append(r, z[len(b):]...) // add padding on the left 319 | r = append(r, b...) 320 | return r[:32] 321 | } 322 | 323 | func stringToBytes(s string) ([]byte, error) { 324 | if s == "1" { 325 | s = "0" 326 | } 327 | bi, ok := new(big.Int).SetString(s, 10) 328 | if !ok { 329 | return nil, fmt.Errorf("error parsing bigint stringToBytes") 330 | } 331 | b := bi.Bytes() 332 | if len(b) != 32 { 333 | b = addZPadding(b) 334 | } 335 | return b, nil 336 | 337 | } 338 | 339 | func arrayStringToG1(h [][]string) ([]*bn256.G1, error) { 340 | var o []*bn256.G1 341 | for i := 0; i < len(h); i++ { 342 | hi, err := stringToG1(h[i]) 343 | if err != nil { 344 | return o, err 345 | } 346 | o = append(o, hi) 347 | } 348 | return o, nil 349 | } 350 | 351 | func arrayStringToG2(h [][][]string) ([]*bn256.G2, error) { 352 | var o []*bn256.G2 353 | for i := 0; i < len(h); i++ { 354 | hi, err := stringToG2(h[i]) 355 | if err != nil { 356 | return o, err 357 | } 358 | o = append(o, hi) 359 | } 360 | return o, nil 361 | } 362 | 363 | func stringToG1(h []string) (*bn256.G1, error) { 364 | if len(h) <= 2 { 365 | return nil, fmt.Errorf("not enought data for stringToG1") 366 | } 367 | h = h[:2] 368 | hexa := false 369 | if len(h[0]) > 1 { 370 | if "0x" == h[0][:2] { 371 | hexa = true 372 | } 373 | } 374 | in := "" 375 | 376 | var b []byte 377 | var err error 378 | if hexa { 379 | for i := range h { 380 | in += strings.TrimPrefix(h[i], "0x") 381 | } 382 | b, err = hex.DecodeString(in) 383 | if err != nil { 384 | return nil, err 385 | } 386 | } else { 387 | // TODO TMP 388 | // TODO use stringToBytes() 389 | if h[0] == "1" { 390 | h[0] = "0" 391 | } 392 | if h[1] == "1" { 393 | h[1] = "0" 394 | } 395 | bi0, ok := new(big.Int).SetString(h[0], 10) 396 | if !ok { 397 | return nil, fmt.Errorf("error parsing stringToG1") 398 | } 399 | bi1, ok := new(big.Int).SetString(h[1], 10) 400 | if !ok { 401 | return nil, fmt.Errorf("error parsing stringToG1") 402 | } 403 | b0 := bi0.Bytes() 404 | b1 := bi1.Bytes() 405 | if len(b0) != 32 { 406 | b0 = addZPadding(b0) 407 | } 408 | if len(b1) != 32 { 409 | b1 = addZPadding(b1) 410 | } 411 | 412 | b = append(b, b0...) 413 | b = append(b, b1...) 414 | } 415 | p := new(bn256.G1) 416 | _, err = p.Unmarshal(b) 417 | 418 | return p, err 419 | } 420 | 421 | func stringToG2(h [][]string) (*bn256.G2, error) { 422 | if len(h) <= 2 { 423 | return nil, fmt.Errorf("not enought data for stringToG2") 424 | } 425 | h = h[:2] 426 | hexa := false 427 | if len(h[0][0]) > 1 { 428 | if "0x" == h[0][0][:2] { 429 | hexa = true 430 | } 431 | } 432 | in := "" 433 | var b []byte 434 | var err error 435 | if hexa { 436 | for i := 0; i < len(h); i++ { 437 | for j := 0; j < len(h[i]); j++ { 438 | in += strings.TrimPrefix(h[i][j], "0x") 439 | } 440 | } 441 | b, err = hex.DecodeString(in) 442 | if err != nil { 443 | return nil, err 444 | } 445 | } else { 446 | // TODO TMP 447 | bH, err := stringToBytes(h[0][1]) 448 | if err != nil { 449 | return nil, err 450 | } 451 | b = append(b, bH...) 452 | bH, err = stringToBytes(h[0][0]) 453 | if err != nil { 454 | return nil, err 455 | } 456 | b = append(b, bH...) 457 | bH, err = stringToBytes(h[1][1]) 458 | if err != nil { 459 | return nil, err 460 | } 461 | b = append(b, bH...) 462 | bH, err = stringToBytes(h[1][0]) 463 | if err != nil { 464 | return nil, err 465 | } 466 | b = append(b, bH...) 467 | } 468 | 469 | p := new(bn256.G2) 470 | _, err = p.Unmarshal(b) 471 | return p, err 472 | } 473 | 474 | // ProofStringToSmartContractFormat converts the ProofString to a ProofString in the SmartContract format in a ProofString structure 475 | func ProofStringToSmartContractFormat(s ProofString) ProofString { 476 | var rs ProofString 477 | rs.A = make([]string, 2) 478 | rs.B = make([][]string, 2) 479 | rs.B[0] = make([]string, 2) 480 | rs.B[1] = make([]string, 2) 481 | rs.C = make([]string, 2) 482 | 483 | rs.A[0] = s.A[0] 484 | rs.A[1] = s.A[1] 485 | rs.B[0][0] = s.B[0][1] 486 | rs.B[0][1] = s.B[0][0] 487 | rs.B[1][0] = s.B[1][1] 488 | rs.B[1][1] = s.B[1][0] 489 | rs.C[0] = s.C[0] 490 | rs.C[1] = s.C[1] 491 | rs.Protocol = s.Protocol 492 | return rs 493 | } 494 | 495 | // ProofToSmartContractFormat converts the *types.Proof to a ProofString in the SmartContract format in a ProofString structure 496 | func ProofToSmartContractFormat(p *types.Proof) ProofString { 497 | s := ProofToString(p) 498 | return ProofStringToSmartContractFormat(s) 499 | } 500 | 501 | // ProofToString converts the Proof to ProofString 502 | func ProofToString(p *types.Proof) ProofString { 503 | var ps ProofString 504 | ps.A = make([]string, 3) 505 | ps.B = make([][]string, 3) 506 | ps.B[0] = make([]string, 2) 507 | ps.B[1] = make([]string, 2) 508 | ps.B[2] = make([]string, 2) 509 | ps.C = make([]string, 3) 510 | 511 | a := p.A.Marshal() 512 | ps.A[0] = new(big.Int).SetBytes(a[:32]).String() 513 | ps.A[1] = new(big.Int).SetBytes(a[32:64]).String() 514 | ps.A[2] = "1" 515 | 516 | b := p.B.Marshal() 517 | ps.B[0][1] = new(big.Int).SetBytes(b[:32]).String() 518 | ps.B[0][0] = new(big.Int).SetBytes(b[32:64]).String() 519 | ps.B[1][1] = new(big.Int).SetBytes(b[64:96]).String() 520 | ps.B[1][0] = new(big.Int).SetBytes(b[96:128]).String() 521 | ps.B[2][0] = "1" 522 | ps.B[2][1] = "0" 523 | 524 | c := p.C.Marshal() 525 | ps.C[0] = new(big.Int).SetBytes(c[:32]).String() 526 | ps.C[1] = new(big.Int).SetBytes(c[32:64]).String() 527 | ps.C[2] = "1" 528 | 529 | ps.Protocol = "groth" 530 | 531 | return ps 532 | } 533 | 534 | // ProofToJson outputs the Proof i Json format 535 | func ProofToJson(p *types.Proof) ([]byte, error) { 536 | ps := ProofToString(p) 537 | return json.Marshal(ps) 538 | } 539 | 540 | // ProofToHex converts the Proof to ProofString with hexadecimal strings 541 | func ProofToHex(p *types.Proof) ProofString { 542 | var ps ProofString 543 | ps.A = make([]string, 3) 544 | ps.B = make([][]string, 3) 545 | ps.B[0] = make([]string, 2) 546 | ps.B[1] = make([]string, 2) 547 | ps.B[2] = make([]string, 2) 548 | ps.C = make([]string, 3) 549 | 550 | a := p.A.Marshal() 551 | ps.A[0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(a[:32]).Bytes()) 552 | ps.A[1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(a[32:64]).Bytes()) 553 | ps.A[2] = "1" 554 | 555 | b := p.B.Marshal() 556 | ps.B[0][1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[:32]).Bytes()) 557 | ps.B[0][0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[32:64]).Bytes()) 558 | ps.B[1][1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[64:96]).Bytes()) 559 | ps.B[1][0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(b[96:128]).Bytes()) 560 | ps.B[2][0] = "1" 561 | ps.B[2][1] = "0" 562 | 563 | c := p.C.Marshal() 564 | ps.C[0] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(c[:32]).Bytes()) 565 | ps.C[1] = "0x" + hex.EncodeToString(new(big.Int).SetBytes(c[32:64]).Bytes()) 566 | ps.C[2] = "1" 567 | 568 | ps.Protocol = "groth" 569 | 570 | return ps 571 | } 572 | 573 | // ProofToJsonHex outputs the Proof i Json format with hexadecimal strings 574 | func ProofToJsonHex(p *types.Proof) ([]byte, error) { 575 | ps := ProofToHex(p) 576 | return json.Marshal(ps) 577 | } 578 | 579 | // ParseWitnessBin parses binary file representation of the Witness into the Witness struct 580 | func ParseWitnessBin(f *os.File) (types.Witness, error) { 581 | var w types.Witness 582 | r := bufio.NewReader(f) 583 | for { 584 | b := make([]byte, 32) 585 | n, err := r.Read(b) 586 | if err == io.EOF { 587 | return w, nil 588 | } else if err != nil { 589 | return nil, err 590 | } 591 | if n != 32 { 592 | return nil, fmt.Errorf("error on value format, expected 32 bytes, got %v", n) 593 | } 594 | w = append(w, new(big.Int).SetBytes(swapEndianness(b[0:32]))) 595 | } 596 | } 597 | 598 | // swapEndianness swaps the order of the bytes in the slice. 599 | func swapEndianness(b []byte) []byte { 600 | o := make([]byte, len(b)) 601 | for i := range b { 602 | o[len(b)-1-i] = b[i] 603 | } 604 | return o 605 | } 606 | 607 | func readNBytes(r io.Reader, n int) ([]byte, error) { 608 | b := make([]byte, n) 609 | _, err := io.ReadFull(r, b) 610 | if err != nil { 611 | return b, err 612 | } 613 | return b, nil 614 | } 615 | 616 | // ParsePkBin parses binary file representation of the ProvingKey into the ProvingKey struct 617 | func ParsePkBin(f *os.File) (*types.Pk, error) { 618 | o := 0 619 | var pk types.Pk 620 | r := bufio.NewReader(f) 621 | 622 | b, err := readNBytes(r, 12) 623 | if err != nil { 624 | return nil, err 625 | } 626 | pk.NVars = int(binary.LittleEndian.Uint32(b[:4])) 627 | pk.NPublic = int(binary.LittleEndian.Uint32(b[4:8])) 628 | pk.DomainSize = int(binary.LittleEndian.Uint32(b[8:12])) 629 | o += 12 630 | 631 | b, err = readNBytes(r, 8) 632 | if err != nil { 633 | return nil, err 634 | } 635 | pPolsA := int(binary.LittleEndian.Uint32(b[:4])) 636 | pPolsB := int(binary.LittleEndian.Uint32(b[4:8])) 637 | o += 8 638 | 639 | b, err = readNBytes(r, 20) 640 | if err != nil { 641 | return nil, err 642 | } 643 | pPointsA := int(binary.LittleEndian.Uint32(b[:4])) 644 | pPointsB1 := int(binary.LittleEndian.Uint32(b[4:8])) 645 | pPointsB2 := int(binary.LittleEndian.Uint32(b[8:12])) 646 | pPointsC := int(binary.LittleEndian.Uint32(b[12:16])) 647 | pPointsHExps := int(binary.LittleEndian.Uint32(b[16:20])) 648 | o += 20 649 | 650 | b, err = readNBytes(r, 64) 651 | if err != nil { 652 | return nil, err 653 | } 654 | pk.VkAlpha1 = new(bn256.G1) 655 | _, err = pk.VkAlpha1.Unmarshal(fromMont1Q(b)) 656 | if err != nil { 657 | return nil, err 658 | } 659 | 660 | b, err = readNBytes(r, 64) 661 | if err != nil { 662 | return nil, err 663 | } 664 | pk.VkBeta1 = new(bn256.G1) 665 | _, err = pk.VkBeta1.Unmarshal(fromMont1Q(b)) 666 | if err != nil { 667 | return nil, err 668 | } 669 | 670 | b, err = readNBytes(r, 64) 671 | if err != nil { 672 | return nil, err 673 | } 674 | pk.VkDelta1 = new(bn256.G1) 675 | _, err = pk.VkDelta1.Unmarshal(fromMont1Q(b)) 676 | if err != nil { 677 | return nil, err 678 | } 679 | b, err = readNBytes(r, 128) 680 | if err != nil { 681 | return nil, err 682 | } 683 | pk.VkBeta2 = new(bn256.G2) 684 | _, err = pk.VkBeta2.Unmarshal(fromMont2Q(b)) 685 | if err != nil { 686 | return nil, err 687 | } 688 | b, err = readNBytes(r, 128) 689 | if err != nil { 690 | return nil, err 691 | } 692 | pk.VkDelta2 = new(bn256.G2) 693 | _, err = pk.VkDelta2.Unmarshal(fromMont2Q(b)) 694 | if err != nil { 695 | return nil, err 696 | } 697 | o += 448 698 | if o != pPolsA { 699 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsA, o) 700 | } 701 | 702 | // PolsA 703 | for i := 0; i < pk.NVars; i++ { 704 | b, err = readNBytes(r, 4) 705 | if err != nil { 706 | return nil, err 707 | } 708 | keysLength := int(binary.LittleEndian.Uint32(b[:4])) 709 | o += 4 710 | polsMap := make(map[int]*big.Int) 711 | for j := 0; j < keysLength; j++ { 712 | bK, err := readNBytes(r, 4) 713 | if err != nil { 714 | return nil, err 715 | } 716 | key := int(binary.LittleEndian.Uint32(bK[:4])) 717 | o += 4 718 | 719 | b, err := readNBytes(r, 32) 720 | if err != nil { 721 | return nil, err 722 | } 723 | polsMap[key] = new(big.Int).SetBytes(fromMont1R(b[:32])) 724 | o += 32 725 | } 726 | pk.PolsA = append(pk.PolsA, polsMap) 727 | } 728 | if o != pPolsB { 729 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsB, o) 730 | } 731 | // PolsB 732 | for i := 0; i < pk.NVars; i++ { 733 | b, err = readNBytes(r, 4) 734 | if err != nil { 735 | return nil, err 736 | } 737 | keysLength := int(binary.LittleEndian.Uint32(b[:4])) 738 | o += 4 739 | polsMap := make(map[int]*big.Int) 740 | for j := 0; j < keysLength; j++ { 741 | bK, err := readNBytes(r, 4) 742 | if err != nil { 743 | return nil, err 744 | } 745 | key := int(binary.LittleEndian.Uint32(bK[:4])) 746 | o += 4 747 | 748 | b, err := readNBytes(r, 32) 749 | if err != nil { 750 | return nil, err 751 | } 752 | polsMap[key] = new(big.Int).SetBytes(fromMont1R(b[:32])) 753 | o += 32 754 | } 755 | pk.PolsB = append(pk.PolsB, polsMap) 756 | } 757 | if o != pPointsA { 758 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsA, o) 759 | } 760 | // A 761 | for i := 0; i < pk.NVars; i++ { 762 | b, err = readNBytes(r, 64) 763 | if err != nil { 764 | return nil, err 765 | } 766 | p1 := new(bn256.G1) 767 | _, err = p1.Unmarshal(fromMont1Q(b)) 768 | if err != nil { 769 | return nil, err 770 | } 771 | pk.A = append(pk.A, p1) 772 | o += 64 773 | } 774 | if o != pPointsB1 { 775 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB1, o) 776 | } 777 | // B1 778 | for i := 0; i < pk.NVars; i++ { 779 | b, err = readNBytes(r, 64) 780 | if err != nil { 781 | return nil, err 782 | } 783 | p1 := new(bn256.G1) 784 | _, err = p1.Unmarshal(fromMont1Q(b)) 785 | if err != nil { 786 | return nil, err 787 | } 788 | pk.B1 = append(pk.B1, p1) 789 | o += 64 790 | } 791 | if o != pPointsB2 { 792 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB2, o) 793 | } 794 | // B2 795 | for i := 0; i < pk.NVars; i++ { 796 | b, err = readNBytes(r, 128) 797 | if err != nil { 798 | return nil, err 799 | } 800 | p2 := new(bn256.G2) 801 | _, err = p2.Unmarshal(fromMont2Q(b)) 802 | if err != nil { 803 | return nil, err 804 | } 805 | pk.B2 = append(pk.B2, p2) 806 | o += 128 807 | } 808 | if o != pPointsC { 809 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsC, o) 810 | } 811 | // C 812 | zb := make([]byte, 64) 813 | z := new(bn256.G1) 814 | _, err = z.Unmarshal(zb) 815 | if err != nil { 816 | return nil, err 817 | } 818 | for i := 0; i < pk.NPublic+1; i++ { 819 | pk.C = append(pk.C, z) 820 | } 821 | for i := pk.NPublic + 1; i < pk.NVars; i++ { 822 | b, err = readNBytes(r, 64) 823 | if err != nil { 824 | return nil, err 825 | } 826 | p1 := new(bn256.G1) 827 | _, err = p1.Unmarshal(fromMont1Q(b)) 828 | if err != nil { 829 | return nil, err 830 | } 831 | pk.C = append(pk.C, p1) 832 | o += 64 833 | } 834 | if o != pPointsHExps { 835 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsHExps, o) 836 | } 837 | // HExps 838 | for i := 0; i < pk.DomainSize; i++ { 839 | b, err = readNBytes(r, 64) 840 | if err != nil { 841 | return nil, err 842 | } 843 | p1 := new(bn256.G1) 844 | _, err = p1.Unmarshal(fromMont1Q(b)) 845 | if err != nil { 846 | return nil, err 847 | } 848 | pk.HExps = append(pk.HExps, p1) 849 | } 850 | return &pk, nil 851 | } 852 | 853 | func fromMont1Q(m []byte) []byte { 854 | a := new(big.Int).SetBytes(swapEndianness(m[:32])) 855 | b := new(big.Int).SetBytes(swapEndianness(m[32:64])) 856 | 857 | x := coordFromMont(a, types.Q) 858 | y := coordFromMont(b, types.Q) 859 | if bytes.Equal(x.Bytes(), big.NewInt(1).Bytes()) { 860 | x = big.NewInt(0) 861 | } 862 | if bytes.Equal(y.Bytes(), big.NewInt(1).Bytes()) { 863 | y = big.NewInt(0) 864 | } 865 | 866 | xBytes := x.Bytes() 867 | yBytes := y.Bytes() 868 | if len(xBytes) != 32 { 869 | xBytes = addZPadding(xBytes) 870 | } 871 | if len(yBytes) != 32 { 872 | yBytes = addZPadding(yBytes) 873 | } 874 | 875 | var p []byte 876 | p = append(p, xBytes...) 877 | p = append(p, yBytes...) 878 | 879 | return p 880 | } 881 | 882 | func fromMont2Q(m []byte) []byte { 883 | a := new(big.Int).SetBytes(swapEndianness(m[:32])) 884 | b := new(big.Int).SetBytes(swapEndianness(m[32:64])) 885 | c := new(big.Int).SetBytes(swapEndianness(m[64:96])) 886 | d := new(big.Int).SetBytes(swapEndianness(m[96:128])) 887 | 888 | x := coordFromMont(a, types.Q) 889 | y := coordFromMont(b, types.Q) 890 | z := coordFromMont(c, types.Q) 891 | t := coordFromMont(d, types.Q) 892 | 893 | if bytes.Equal(x.Bytes(), big.NewInt(1).Bytes()) { 894 | x = big.NewInt(0) 895 | } 896 | if bytes.Equal(y.Bytes(), big.NewInt(1).Bytes()) { 897 | y = big.NewInt(0) 898 | } 899 | if bytes.Equal(z.Bytes(), big.NewInt(1).Bytes()) { 900 | z = big.NewInt(0) 901 | } 902 | if bytes.Equal(t.Bytes(), big.NewInt(1).Bytes()) { 903 | t = big.NewInt(0) 904 | } 905 | 906 | xBytes := x.Bytes() 907 | yBytes := y.Bytes() 908 | zBytes := z.Bytes() 909 | tBytes := t.Bytes() 910 | if len(xBytes) != 32 { 911 | xBytes = addZPadding(xBytes) 912 | } 913 | if len(yBytes) != 32 { 914 | yBytes = addZPadding(yBytes) 915 | } 916 | if len(zBytes) != 32 { 917 | zBytes = addZPadding(zBytes) 918 | } 919 | if len(tBytes) != 32 { 920 | tBytes = addZPadding(tBytes) 921 | } 922 | 923 | var p []byte 924 | p = append(p, yBytes...) // swap 925 | p = append(p, xBytes...) 926 | p = append(p, tBytes...) 927 | p = append(p, zBytes...) 928 | 929 | return p 930 | } 931 | 932 | func fromMont1R(m []byte) []byte { 933 | a := new(big.Int).SetBytes(swapEndianness(m[:32])) 934 | 935 | x := coordFromMont(a, types.R) 936 | 937 | return x.Bytes() 938 | } 939 | 940 | func fromMont2R(m []byte) []byte { 941 | a := new(big.Int).SetBytes(swapEndianness(m[:32])) 942 | b := new(big.Int).SetBytes(swapEndianness(m[32:64])) 943 | c := new(big.Int).SetBytes(swapEndianness(m[64:96])) 944 | d := new(big.Int).SetBytes(swapEndianness(m[96:128])) 945 | 946 | x := coordFromMont(a, types.R) 947 | y := coordFromMont(b, types.R) 948 | z := coordFromMont(c, types.R) 949 | t := coordFromMont(d, types.R) 950 | 951 | var p []byte 952 | p = append(p, y.Bytes()...) // swap 953 | p = append(p, x.Bytes()...) 954 | p = append(p, t.Bytes()...) 955 | p = append(p, z.Bytes()...) 956 | 957 | return p 958 | } 959 | 960 | func coordFromMont(u, q *big.Int) *big.Int { 961 | return new(big.Int).Mod( 962 | new(big.Int).Mul( 963 | u, 964 | new(big.Int).ModInverse( 965 | new(big.Int).Lsh(big.NewInt(1), 256), 966 | q, 967 | ), 968 | ), 969 | q, 970 | ) 971 | } 972 | 973 | func sortedKeys(m map[int]*big.Int) []int { 974 | keys := make([]int, 0, len(m)) 975 | for k, _ := range m { 976 | keys = append(keys, k) 977 | } 978 | sort.Ints(keys) 979 | return keys 980 | } 981 | 982 | // PkToGoBin converts the ProvingKey (*types.Pk) into binary format defined by 983 | // go-circom-prover-verifier. PkGoBin is a own go-circom-prover-verifier 984 | // binary format that allows to go faster when parsing. 985 | func PkToGoBin(pk *types.Pk) ([]byte, error) { 986 | var r []byte 987 | o := 0 988 | var b [4]byte 989 | binary.LittleEndian.PutUint32(b[:], uint32(pk.NVars)) 990 | r = append(r, b[:]...) 991 | 992 | binary.LittleEndian.PutUint32(b[:], uint32(pk.NPublic)) 993 | r = append(r, b[:]...) 994 | 995 | binary.LittleEndian.PutUint32(b[:], uint32(pk.DomainSize)) 996 | r = append(r, b[:]...) 997 | o += 12 998 | 999 | // reserve space for pols (A, B) pos 1000 | b = [4]byte{} 1001 | r = append(r, b[:]...) // 12:16 1002 | r = append(r, b[:]...) // 16:20 1003 | o += 8 1004 | // reserve space for points (A, B1, B2, C, HExps) pos 1005 | r = append(r, b[:]...) // 20:24 1006 | r = append(r, b[:]...) // 24 1007 | r = append(r, b[:]...) // 28 1008 | r = append(r, b[:]...) // 32 1009 | r = append(r, b[:]...) // 36:40 1010 | o += 20 1011 | 1012 | pb1 := pk.VkAlpha1.Marshal() 1013 | r = append(r, pb1[:]...) 1014 | pb1 = pk.VkBeta1.Marshal() 1015 | r = append(r, pb1[:]...) 1016 | pb1 = pk.VkDelta1.Marshal() 1017 | r = append(r, pb1[:]...) 1018 | pb2 := pk.VkBeta2.Marshal() 1019 | r = append(r, pb2[:]...) 1020 | pb2 = pk.VkDelta2.Marshal() 1021 | r = append(r, pb2[:]...) 1022 | o += 448 1023 | 1024 | // polsA 1025 | binary.LittleEndian.PutUint32(r[12:16], uint32(o)) 1026 | for i := 0; i < pk.NVars; i++ { 1027 | binary.LittleEndian.PutUint32(b[:], uint32(len(pk.PolsA[i]))) 1028 | r = append(r, b[:]...) 1029 | o += 4 1030 | for _, j := range sortedKeys(pk.PolsA[i]) { 1031 | v := pk.PolsA[i][j] 1032 | binary.LittleEndian.PutUint32(b[:], uint32(j)) 1033 | r = append(r, b[:]...) 1034 | r = append(r, addPadding32(v.Bytes())...) 1035 | o += 32 + 4 1036 | } 1037 | } 1038 | // polsB 1039 | binary.LittleEndian.PutUint32(r[16:20], uint32(o)) 1040 | for i := 0; i < pk.NVars; i++ { 1041 | binary.LittleEndian.PutUint32(b[:], uint32(len(pk.PolsB[i]))) 1042 | r = append(r, b[:]...) 1043 | o += 4 1044 | for _, j := range sortedKeys(pk.PolsB[i]) { 1045 | v := pk.PolsB[i][j] 1046 | binary.LittleEndian.PutUint32(b[:], uint32(j)) 1047 | r = append(r, b[:]...) 1048 | r = append(r, addPadding32(v.Bytes())...) 1049 | o += 32 + 4 1050 | } 1051 | } 1052 | // A 1053 | binary.LittleEndian.PutUint32(r[20:24], uint32(o)) 1054 | for i := 0; i < pk.NVars; i++ { 1055 | pb1 = pk.A[i].Marshal() 1056 | r = append(r, pb1[:]...) 1057 | o += 64 1058 | } 1059 | // B1 1060 | binary.LittleEndian.PutUint32(r[24:28], uint32(o)) 1061 | for i := 0; i < pk.NVars; i++ { 1062 | pb1 = pk.B1[i].Marshal() 1063 | r = append(r, pb1[:]...) 1064 | o += 64 1065 | } 1066 | // B2 1067 | binary.LittleEndian.PutUint32(r[28:32], uint32(o)) 1068 | for i := 0; i < pk.NVars; i++ { 1069 | pb2 = pk.B2[i].Marshal() 1070 | r = append(r, pb2[:]...) 1071 | o += 128 1072 | } 1073 | // C 1074 | binary.LittleEndian.PutUint32(r[32:36], uint32(o)) 1075 | for i := pk.NPublic + 1; i < pk.NVars; i++ { 1076 | pb1 = pk.C[i].Marshal() 1077 | r = append(r, pb1[:]...) 1078 | o += 64 1079 | } 1080 | // HExps 1081 | binary.LittleEndian.PutUint32(r[36:40], uint32(o)) 1082 | for i := 0; i < pk.DomainSize+1; i++ { 1083 | pb1 = pk.HExps[i].Marshal() 1084 | r = append(r, pb1[:]...) 1085 | o += 64 1086 | } 1087 | 1088 | return r[:], nil 1089 | } 1090 | 1091 | // ParsePkGoBin parses go-circom-prover-verifier binary file representation of 1092 | // the ProvingKey into ProvingKey struct (*types.Pk). PkGoBin is a own 1093 | // go-circom-prover-verifier binary format that allows to go faster when 1094 | // parsing. 1095 | func ParsePkGoBin(f *os.File) (*types.Pk, error) { 1096 | o := 0 1097 | var pk types.Pk 1098 | r := bufio.NewReader(f) 1099 | 1100 | b, err := readNBytes(r, 12) 1101 | if err != nil { 1102 | return nil, err 1103 | } 1104 | pk.NVars = int(binary.LittleEndian.Uint32(b[:4])) 1105 | pk.NPublic = int(binary.LittleEndian.Uint32(b[4:8])) 1106 | pk.DomainSize = int(binary.LittleEndian.Uint32(b[8:12])) 1107 | o += 12 1108 | 1109 | b, err = readNBytes(r, 8) 1110 | if err != nil { 1111 | return nil, err 1112 | } 1113 | pPolsA := int(binary.LittleEndian.Uint32(b[:4])) 1114 | pPolsB := int(binary.LittleEndian.Uint32(b[4:8])) 1115 | o += 8 1116 | 1117 | b, err = readNBytes(r, 20) 1118 | if err != nil { 1119 | return nil, err 1120 | } 1121 | pPointsA := int(binary.LittleEndian.Uint32(b[:4])) 1122 | pPointsB1 := int(binary.LittleEndian.Uint32(b[4:8])) 1123 | pPointsB2 := int(binary.LittleEndian.Uint32(b[8:12])) 1124 | pPointsC := int(binary.LittleEndian.Uint32(b[12:16])) 1125 | pPointsHExps := int(binary.LittleEndian.Uint32(b[16:20])) 1126 | o += 20 1127 | 1128 | b, err = readNBytes(r, 64) 1129 | if err != nil { 1130 | return nil, err 1131 | } 1132 | pk.VkAlpha1 = new(bn256.G1) 1133 | _, err = pk.VkAlpha1.Unmarshal(b) 1134 | if err != nil { 1135 | return &pk, err 1136 | } 1137 | b, err = readNBytes(r, 64) 1138 | if err != nil { 1139 | return nil, err 1140 | } 1141 | pk.VkBeta1 = new(bn256.G1) 1142 | _, err = pk.VkBeta1.Unmarshal(b) 1143 | if err != nil { 1144 | return &pk, err 1145 | } 1146 | b, err = readNBytes(r, 64) 1147 | if err != nil { 1148 | return nil, err 1149 | } 1150 | pk.VkDelta1 = new(bn256.G1) 1151 | _, err = pk.VkDelta1.Unmarshal(b) 1152 | if err != nil { 1153 | return &pk, err 1154 | } 1155 | b, err = readNBytes(r, 128) 1156 | if err != nil { 1157 | return nil, err 1158 | } 1159 | pk.VkBeta2 = new(bn256.G2) 1160 | _, err = pk.VkBeta2.Unmarshal(b) 1161 | if err != nil { 1162 | return &pk, err 1163 | } 1164 | b, err = readNBytes(r, 128) 1165 | if err != nil { 1166 | return nil, err 1167 | } 1168 | pk.VkDelta2 = new(bn256.G2) 1169 | _, err = pk.VkDelta2.Unmarshal(b) 1170 | if err != nil { 1171 | return &pk, err 1172 | } 1173 | o += 448 1174 | if o != pPolsA { 1175 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsA, o) 1176 | } 1177 | 1178 | // PolsA 1179 | for i := 0; i < pk.NVars; i++ { 1180 | b, err = readNBytes(r, 4) 1181 | if err != nil { 1182 | return nil, err 1183 | } 1184 | keysLength := int(binary.LittleEndian.Uint32(b[:4])) 1185 | o += 4 1186 | polsMap := make(map[int]*big.Int) 1187 | for j := 0; j < keysLength; j++ { 1188 | bK, err := readNBytes(r, 4) 1189 | if err != nil { 1190 | return nil, err 1191 | } 1192 | key := int(binary.LittleEndian.Uint32(bK[:4])) 1193 | o += 4 1194 | 1195 | b, err := readNBytes(r, 32) 1196 | if err != nil { 1197 | return nil, err 1198 | } 1199 | polsMap[key] = new(big.Int).SetBytes(b[:32]) 1200 | o += 32 1201 | } 1202 | pk.PolsA = append(pk.PolsA, polsMap) 1203 | } 1204 | if o != pPolsB { 1205 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPolsB, o) 1206 | } 1207 | // PolsB 1208 | for i := 0; i < pk.NVars; i++ { 1209 | b, err = readNBytes(r, 4) 1210 | if err != nil { 1211 | return nil, err 1212 | } 1213 | keysLength := int(binary.LittleEndian.Uint32(b[:4])) 1214 | o += 4 1215 | polsMap := make(map[int]*big.Int) 1216 | for j := 0; j < keysLength; j++ { 1217 | bK, err := readNBytes(r, 4) 1218 | if err != nil { 1219 | return nil, err 1220 | } 1221 | key := int(binary.LittleEndian.Uint32(bK[:4])) 1222 | o += 4 1223 | 1224 | b, err := readNBytes(r, 32) 1225 | if err != nil { 1226 | return nil, err 1227 | } 1228 | polsMap[key] = new(big.Int).SetBytes(b[:32]) 1229 | o += 32 1230 | } 1231 | pk.PolsB = append(pk.PolsB, polsMap) 1232 | } 1233 | if o != pPointsA { 1234 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsA, o) 1235 | } 1236 | // A 1237 | for i := 0; i < pk.NVars; i++ { 1238 | b, err = readNBytes(r, 64) 1239 | if err != nil { 1240 | return nil, err 1241 | } 1242 | p1 := new(bn256.G1) 1243 | _, err = p1.Unmarshal(b) 1244 | if err != nil { 1245 | return nil, err 1246 | } 1247 | pk.A = append(pk.A, p1) 1248 | o += 64 1249 | } 1250 | if o != pPointsB1 { 1251 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB1, o) 1252 | } 1253 | // B1 1254 | for i := 0; i < pk.NVars; i++ { 1255 | b, err = readNBytes(r, 64) 1256 | if err != nil { 1257 | return nil, err 1258 | } 1259 | p1 := new(bn256.G1) 1260 | _, err = p1.Unmarshal(b) 1261 | if err != nil { 1262 | return nil, err 1263 | } 1264 | pk.B1 = append(pk.B1, p1) 1265 | o += 64 1266 | } 1267 | if o != pPointsB2 { 1268 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsB2, o) 1269 | } 1270 | // B2 1271 | for i := 0; i < pk.NVars; i++ { 1272 | b, err = readNBytes(r, 128) 1273 | if err != nil { 1274 | return nil, err 1275 | } 1276 | p2 := new(bn256.G2) 1277 | _, err = p2.Unmarshal(b) 1278 | if err != nil { 1279 | return nil, err 1280 | } 1281 | pk.B2 = append(pk.B2, p2) 1282 | o += 128 1283 | } 1284 | if o != pPointsC { 1285 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsC, o) 1286 | } 1287 | // C 1288 | zb := make([]byte, 64) 1289 | z := new(bn256.G1) 1290 | _, err = z.Unmarshal(zb) 1291 | if err != nil { 1292 | return nil, err 1293 | } 1294 | for i := 0; i < pk.NPublic+1; i++ { 1295 | pk.C = append(pk.C, z) 1296 | } 1297 | for i := pk.NPublic + 1; i < pk.NVars; i++ { 1298 | b, err = readNBytes(r, 64) 1299 | if err != nil { 1300 | return nil, err 1301 | } 1302 | p1 := new(bn256.G1) 1303 | _, err = p1.Unmarshal(b) 1304 | if err != nil { 1305 | return nil, err 1306 | } 1307 | pk.C = append(pk.C, p1) 1308 | o += 64 1309 | } 1310 | if o != pPointsHExps { 1311 | return nil, fmt.Errorf("Unexpected offset, expected: %v, actual: %v", pPointsHExps, o) 1312 | } 1313 | // HExps 1314 | for i := 0; i < pk.DomainSize+1; i++ { 1315 | b, err = readNBytes(r, 64) 1316 | if err != nil { 1317 | return nil, err 1318 | } 1319 | p1 := new(bn256.G1) 1320 | _, err = p1.Unmarshal(b) 1321 | if err != nil { 1322 | return nil, err 1323 | } 1324 | pk.HExps = append(pk.HExps, p1) 1325 | } 1326 | 1327 | return &pk, nil 1328 | } 1329 | -------------------------------------------------------------------------------- /parsers/parsers_test.go: -------------------------------------------------------------------------------- 1 | package parsers 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os" 7 | "testing" 8 | 9 | "github.com/iden3/go-circom-prover-verifier/types" 10 | "github.com/stretchr/testify/assert" 11 | "github.com/stretchr/testify/require" 12 | ) 13 | 14 | func TestParseArrayG1(t *testing.T) { 15 | aS := [][]string{ 16 | { 17 | "16145916318196730299582072104388453231952213805668281741813587224450782397538", 18 | "4434505318477484327659527264104806919103674231447634885054368605283938696207", 19 | "1", 20 | }, 21 | { 22 | "10618406967550056457559358662746625591602641004174976323307214433994084907915", 23 | "1843236360452735081347085412539192450068665510574800388201121698908391533923", 24 | "1", 25 | }, 26 | { 27 | "1208972877970123411566574123860641832032384890981476033353526096830198333194", 28 | "777503551507025252294438107100944741641946695980350712141258191590862204805", 29 | "1", 30 | }, 31 | { 32 | "0", 33 | "1", 34 | "0", 35 | }, 36 | } 37 | 38 | a, err := arrayStringToG1(aS) 39 | assert.Nil(t, err) 40 | assert.Equal(t, "bn256.G1(23b243c928ce40c4cc2dad366e9f61723aef65866e1c66f42a08697f2f030462, 09cdd7500688fb487ec9f27b5a732d68fa0f3ddca5c2c790e330fdfb03b77c0f)", a[0].String()) 41 | assert.Equal(t, "bn256.G1(1779ce2c586b5fc523e72e755d969a63473052aaad7c11eb5bf0ecdcfdfefb8b, 04133c1c74206dace57cd3d76ce59be381bbf08f51a5b3edc2b0c183d43eed63)", a[1].String()) 42 | assert.Equal(t, "bn256.G1(02ac4120598d2f2bb81bc09b8df596403360577b0c5ff52485d1ef2200f23f0a, 01b80d298de75f867d6484c55c3da02c042bb4eb9a1734d3386786aaa669af85)", a[2].String()) 43 | assert.Equal(t, "bn256.G1(0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000001)", a[3].String()) 44 | } 45 | 46 | func TestParseG2(t *testing.T) { 47 | aS := [][]string{ 48 | { 49 | "9283666785342556550467669770956850930982548182701254051508520248901282197973", 50 | "11369378229277445316894458966429873744779877313900506577160370623273013178252", 51 | }, 52 | { 53 | "10625777544326349817513295021482494426101347915428005055375725845993157551870", 54 | "21401790227434807639472120486932615400751346915707967674912972446672152512583", 55 | }, 56 | { 57 | "1", 58 | "0", 59 | }, 60 | } 61 | 62 | a, err := stringToG2(aS) 63 | assert.Nil(t, err) 64 | assert.Equal(t, "bn256.G2((1922d70c934543aa655ec3277f7fa10a25ec973a4f001a7c54ce4954b4916f8c, 14865e836947c42cf35b47d30e06535fff9dab319c4296e28afde368960671d5), (2f50fbe77925b0a9d718c9ab38638bafa7c65f43f0d09035e518df97ad294847, 177dfa1a3b8627faf0425d9511bcb4c6ca986ea05e3803b5c643c35b94a7e6fe))", a.String()) 65 | 66 | aS = [][]string{ 67 | { 68 | "13973091636763944887728510851169742544309374663995476311690518173988838518856", 69 | "12903946180439304546475897520537621821375470264150438270817301786763517825250", 70 | }, 71 | { 72 | "370374369234123593044872519351942112043402224488849374153134091815693350697", 73 | "17423079115073430837335625309232513526393852743032331213038909731579295753224", 74 | }, 75 | { 76 | "1", 77 | "0", 78 | }, 79 | } 80 | a, err = stringToG2(aS) 81 | assert.Nil(t, err) 82 | assert.Equal(t, "bn256.G2((1c875fed67fff3b35f115b03706ec45f281b5f6cc71a99107240e09fce4910e2, 1ee47d566e9a099626b9860bcd96f6d4a1ed65f115d3efa8e05e5f42cc793048), (26851d022ce9961df65a430811824aaf3118710ac03b0614a50c05ee27d8e408, 00d19fdce25b0d78fb317a5f1789823b7ed76274b0d1be9c685792c73b347729))", a.String()) 83 | } 84 | 85 | func TestParseArrayG2(t *testing.T) { 86 | aS := [][][]string{ 87 | { 88 | { 89 | "0", 90 | "0", 91 | }, 92 | { 93 | "1", 94 | "0", 95 | }, 96 | { 97 | "0", 98 | "0", 99 | }, 100 | }, 101 | { 102 | { 103 | "0", 104 | "0", 105 | }, 106 | { 107 | "1", 108 | "0", 109 | }, 110 | { 111 | "0", 112 | "0", 113 | }, 114 | }, 115 | { 116 | { 117 | "0", 118 | "0", 119 | }, 120 | { 121 | "1", 122 | "0", 123 | }, 124 | { 125 | "0", 126 | "0", 127 | }, 128 | }, 129 | { 130 | { 131 | "9283666785342556550467669770956850930982548182701254051508520248901282197973", 132 | "11369378229277445316894458966429873744779877313900506577160370623273013178252", 133 | }, 134 | { 135 | "10625777544326349817513295021482494426101347915428005055375725845993157551870", 136 | "21401790227434807639472120486932615400751346915707967674912972446672152512583", 137 | }, 138 | { 139 | "1", 140 | "0", 141 | }, 142 | }, 143 | } 144 | 145 | a, err := arrayStringToG2(aS) 146 | assert.Nil(t, err) 147 | assert.Equal(t, "bn256.G2((0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000), (0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000001))", a[0].String()) 148 | assert.Equal(t, "bn256.G2((1922d70c934543aa655ec3277f7fa10a25ec973a4f001a7c54ce4954b4916f8c, 14865e836947c42cf35b47d30e06535fff9dab319c4296e28afde368960671d5), (2f50fbe77925b0a9d718c9ab38638bafa7c65f43f0d09035e518df97ad294847, 177dfa1a3b8627faf0425d9511bcb4c6ca986ea05e3803b5c643c35b94a7e6fe))", a[3].String()) 149 | 150 | } 151 | 152 | func testCircuitParseWitnessBin(t *testing.T, circuit string) { 153 | witnessBinFile, err := os.Open("../testdata/" + circuit + "/witness.bin") 154 | require.Nil(t, err) 155 | defer witnessBinFile.Close() 156 | witness, err := ParseWitnessBin(witnessBinFile) 157 | require.Nil(t, err) 158 | 159 | witnessJson, err := ioutil.ReadFile("../testdata/" + circuit + "/witness.json") 160 | require.Nil(t, err) 161 | w, err := ParseWitness(witnessJson) 162 | require.Nil(t, err) 163 | 164 | assert.Equal(t, len(w), len(witness)) 165 | assert.Equal(t, w[0], witness[0]) 166 | assert.Equal(t, w[1], witness[1]) 167 | assert.Equal(t, w[10], witness[10]) 168 | assert.Equal(t, w[len(w)-3], witness[len(w)-3]) 169 | assert.Equal(t, w[len(w)-2], witness[len(w)-2]) 170 | assert.Equal(t, w[len(w)-1], witness[len(w)-1]) 171 | } 172 | 173 | func TestParseWitnessBin(t *testing.T) { 174 | testCircuitParseWitnessBin(t, "circuit1k") 175 | testCircuitParseWitnessBin(t, "circuit5k") 176 | } 177 | 178 | func TestProofSmartContractFormat(t *testing.T) { 179 | proofJson, err := ioutil.ReadFile("../testdata/circuit1k/proof.json") 180 | require.Nil(t, err) 181 | proof, err := ParseProof(proofJson) 182 | require.Nil(t, err) 183 | pS := ProofToString(proof) 184 | 185 | pSC := ProofToSmartContractFormat(proof) 186 | assert.Nil(t, err) 187 | assert.Equal(t, pS.A[0], pSC.A[0]) 188 | assert.Equal(t, pS.A[1], pSC.A[1]) 189 | assert.Equal(t, pS.B[0][0], pSC.B[0][1]) 190 | assert.Equal(t, pS.B[0][1], pSC.B[0][0]) 191 | assert.Equal(t, pS.B[1][0], pSC.B[1][1]) 192 | assert.Equal(t, pS.B[1][1], pSC.B[1][0]) 193 | assert.Equal(t, pS.C[0], pSC.C[0]) 194 | assert.Equal(t, pS.C[1], pSC.C[1]) 195 | assert.Equal(t, pS.Protocol, pSC.Protocol) 196 | 197 | pSC2 := ProofStringToSmartContractFormat(pS) 198 | assert.Equal(t, pSC, pSC2) 199 | } 200 | 201 | func TestProofJSON(t *testing.T) { 202 | proofJson, err := ioutil.ReadFile("../testdata/circuit1k/proof.json") 203 | require.Nil(t, err) 204 | proof, err := ParseProof(proofJson) 205 | require.Nil(t, err) 206 | 207 | proof1JSON, err := json.Marshal(proof) 208 | require.Nil(t, err) 209 | var proof1 types.Proof 210 | err = json.Unmarshal(proof1JSON, &proof1) 211 | require.Nil(t, err) 212 | require.Equal(t, *proof, proof1) 213 | } 214 | 215 | func testCircuitParsePkBin(t *testing.T, circuit string) { 216 | pkBinFile, err := os.Open("../testdata/" + circuit + "/proving_key.bin") 217 | require.Nil(t, err) 218 | defer pkBinFile.Close() 219 | pk, err := ParsePkBin(pkBinFile) 220 | require.Nil(t, err) 221 | 222 | pkJson, err := ioutil.ReadFile("../testdata/" + circuit + "/proving_key.json") 223 | require.Nil(t, err) 224 | pkJ, err := ParsePk(pkJson) 225 | require.Nil(t, err) 226 | 227 | assert.Equal(t, pkJ.NVars, pk.NVars) 228 | assert.Equal(t, pkJ.NPublic, pk.NPublic) 229 | assert.Equal(t, pkJ.DomainSize, pk.DomainSize) 230 | assert.Equal(t, pkJ.VkAlpha1, pk.VkAlpha1) 231 | assert.Equal(t, pkJ.VkBeta1, pk.VkBeta1) 232 | assert.Equal(t, pkJ.VkDelta1, pk.VkDelta1) 233 | assert.Equal(t, pkJ.VkDelta2, pk.VkDelta2) 234 | assert.Equal(t, pkJ.PolsA, pk.PolsA) 235 | assert.Equal(t, pkJ.PolsB, pk.PolsB) 236 | assert.Equal(t, pkJ.A, pk.A) 237 | assert.Equal(t, pkJ.B1, pk.B1) 238 | assert.Equal(t, pkJ.B2, pk.B2) 239 | assert.Equal(t, pkJ.C, pk.C) 240 | assert.Equal(t, pkJ.HExps[:pkJ.DomainSize], pk.HExps[:pk.DomainSize]) // circom behaviour 241 | 242 | assert.Equal(t, pkJ.NVars, pk.NVars) 243 | assert.Equal(t, pkJ.NPublic, pk.NPublic) 244 | assert.Equal(t, pkJ.DomainSize, pk.DomainSize) 245 | } 246 | 247 | func TestParsePkBin(t *testing.T) { 248 | testCircuitParsePkBin(t, "circuit1k") 249 | testCircuitParsePkBin(t, "circuit5k") 250 | } 251 | 252 | func testGoCircomPkFormat(t *testing.T, circuit string) { 253 | pkJson, err := ioutil.ReadFile("../testdata/" + circuit + "/proving_key.json") 254 | require.Nil(t, err) 255 | pk, err := ParsePk(pkJson) 256 | require.Nil(t, err) 257 | 258 | pkGBin, err := PkToGoBin(pk) 259 | require.Nil(t, err) 260 | err = ioutil.WriteFile("../testdata/"+circuit+"/proving_key.go.bin", pkGBin, 0644) 261 | assert.Nil(t, err) 262 | 263 | // parse ProvingKeyGo 264 | pkGoBinFile, err := os.Open("../testdata/" + circuit + "/proving_key.go.bin") 265 | require.Nil(t, err) 266 | defer pkGoBinFile.Close() 267 | pkG, err := ParsePkGoBin(pkGoBinFile) 268 | require.Nil(t, err) 269 | assert.Equal(t, pk.VkAlpha1, pkG.VkAlpha1) 270 | assert.Equal(t, pk.VkBeta1, pkG.VkBeta1) 271 | assert.Equal(t, pk.VkDelta1, pkG.VkDelta1) 272 | assert.Equal(t, pk.VkBeta2, pkG.VkBeta2) 273 | assert.Equal(t, pk.VkDelta2, pkG.VkDelta2) 274 | assert.Equal(t, pk.A, pkG.A) 275 | assert.Equal(t, pk.B1, pkG.B1) 276 | assert.Equal(t, pk.B2, pkG.B2) 277 | assert.Equal(t, pk.C, pkG.C) 278 | assert.Equal(t, pk.HExps, pkG.HExps) 279 | assert.Equal(t, pk.PolsA, pkG.PolsA) 280 | assert.Equal(t, pk.PolsB, pkG.PolsB) 281 | 282 | assert.Equal(t, pk.NVars, pkG.NVars) 283 | assert.Equal(t, pk.NPublic, pkG.NPublic) 284 | assert.Equal(t, pk.DomainSize, pkG.DomainSize) 285 | } 286 | 287 | func TestGoCircomPkFormat(t *testing.T) { 288 | testGoCircomPkFormat(t, "circuit1k") 289 | testGoCircomPkFormat(t, "circuit5k") 290 | // testGoCircomPkFormat(t, "circuit10k") 291 | // testGoCircomPkFormat(t, "circuit20k") 292 | } 293 | 294 | func benchmarkParsePk(b *testing.B, circuit string) { 295 | pkJson, err := ioutil.ReadFile("../testdata/" + circuit + "/proving_key.json") 296 | require.Nil(b, err) 297 | 298 | pkBinFile, err := os.Open("../testdata/" + circuit + "/proving_key.bin") 299 | require.Nil(b, err) 300 | defer pkBinFile.Close() 301 | 302 | pkGoBinFile, err := os.Open("../testdata/" + circuit + "/proving_key.go.bin") 303 | require.Nil(b, err) 304 | defer pkGoBinFile.Close() 305 | 306 | b.Run("ParsePkJson "+circuit, func(b *testing.B) { 307 | for i := 0; i < b.N; i++ { 308 | _, err = ParsePk(pkJson) 309 | require.Nil(b, err) 310 | } 311 | }) 312 | b.Run("ParsePkBin "+circuit, func(b *testing.B) { 313 | for i := 0; i < b.N; i++ { 314 | pkBinFile.Seek(0, 0) 315 | _, err = ParsePkBin(pkBinFile) 316 | require.Nil(b, err) 317 | } 318 | }) 319 | b.Run("ParsePkGoBin "+circuit, func(b *testing.B) { 320 | for i := 0; i < b.N; i++ { 321 | pkGoBinFile.Seek(0, 0) 322 | _, err = ParsePkGoBin(pkGoBinFile) 323 | require.Nil(b, err) 324 | } 325 | }) 326 | } 327 | 328 | func BenchmarkParsePk(b *testing.B) { 329 | benchmarkParsePk(b, "circuit1k") 330 | benchmarkParsePk(b, "circuit5k") 331 | // benchmarkParsePk(b, "circuit10k") 332 | // benchmarkParsePk(b, "circuit20k") 333 | } 334 | -------------------------------------------------------------------------------- /prover/arithmetic.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "bytes" 5 | "math/big" 6 | 7 | bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare" 8 | "github.com/iden3/go-circom-prover-verifier/types" 9 | "github.com/iden3/go-iden3-crypto/ff" 10 | ) 11 | 12 | func arrayOfZeroes(n int) []*big.Int { 13 | r := make([]*big.Int, n) 14 | for i := 0; i < n; i++ { 15 | r[i] = new(big.Int).SetInt64(0) 16 | } 17 | return r[:] 18 | } 19 | 20 | func arrayOfZeroesE(n int) []*ff.Element { 21 | r := make([]*ff.Element, n) 22 | for i := 0; i < n; i++ { 23 | r[i] = ff.NewElement() 24 | } 25 | return r[:] 26 | } 27 | 28 | func arrayOfZeroesG1(n int) []*bn256.G1 { 29 | r := make([]*bn256.G1, n) 30 | for i := 0; i < n; i++ { 31 | r[i] = new(bn256.G1).ScalarBaseMult(big.NewInt(0)) 32 | } 33 | return r[:] 34 | } 35 | 36 | func arrayOfZeroesG2(n int) []*bn256.G2 { 37 | r := make([]*bn256.G2, n) 38 | for i := 0; i < n; i++ { 39 | r[i] = new(bn256.G2).ScalarBaseMult(big.NewInt(0)) 40 | } 41 | return r[:] 42 | } 43 | 44 | func fAdd(a, b *big.Int) *big.Int { 45 | ab := new(big.Int).Add(a, b) 46 | return ab.Mod(ab, types.R) 47 | } 48 | 49 | func fSub(a, b *big.Int) *big.Int { 50 | ab := new(big.Int).Sub(a, b) 51 | return new(big.Int).Mod(ab, types.R) 52 | } 53 | 54 | func fMul(a, b *big.Int) *big.Int { 55 | ab := new(big.Int).Mul(a, b) 56 | return ab.Mod(ab, types.R) 57 | } 58 | 59 | func fDiv(a, b *big.Int) *big.Int { 60 | ab := new(big.Int).Mul(a, new(big.Int).ModInverse(b, types.R)) 61 | return new(big.Int).Mod(ab, types.R) 62 | } 63 | 64 | func fNeg(a *big.Int) *big.Int { 65 | return new(big.Int).Mod(new(big.Int).Neg(a), types.R) 66 | } 67 | 68 | func fInv(a *big.Int) *big.Int { 69 | return new(big.Int).ModInverse(a, types.R) 70 | } 71 | 72 | func fExp(base *big.Int, e *big.Int) *big.Int { 73 | res := big.NewInt(1) 74 | rem := new(big.Int).Set(e) 75 | exp := base 76 | 77 | for !bytes.Equal(rem.Bytes(), big.NewInt(int64(0)).Bytes()) { 78 | // if BigIsOdd(rem) { 79 | if rem.Bit(0) == 1 { // .Bit(0) returns 1 when is odd 80 | res = fMul(res, exp) 81 | } 82 | exp = fMul(exp, exp) 83 | rem.Rsh(rem, 1) 84 | } 85 | return res 86 | } 87 | 88 | func max(a, b int) int { 89 | if a > b { 90 | return a 91 | } 92 | return b 93 | } 94 | 95 | func polynomialSub(a, b []*big.Int) []*big.Int { 96 | r := arrayOfZeroes(max(len(a), len(b))) 97 | for i := 0; i < len(a); i++ { 98 | r[i] = fAdd(r[i], a[i]) 99 | } 100 | for i := 0; i < len(b); i++ { 101 | r[i] = fSub(r[i], b[i]) 102 | } 103 | return r 104 | } 105 | 106 | func polynomialSubE(a, b []*ff.Element) []*ff.Element { 107 | r := arrayOfZeroesE(max(len(a), len(b))) 108 | for i := 0; i < len(a); i++ { 109 | r[i].Add(r[i], a[i]) 110 | } 111 | for i := 0; i < len(b); i++ { 112 | r[i].Sub(r[i], b[i]) 113 | } 114 | return r 115 | } 116 | 117 | func polynomialMul(a, b []*big.Int) []*big.Int { 118 | r := arrayOfZeroes(len(a) + len(b) - 1) 119 | for i := 0; i < len(a); i++ { 120 | for j := 0; j < len(b); j++ { 121 | r[i+j] = fAdd(r[i+j], fMul(a[i], b[j])) 122 | } 123 | } 124 | return r 125 | } 126 | 127 | func polynomialMulE(a, b []*ff.Element) []*ff.Element { 128 | r := arrayOfZeroesE(len(a) + len(b) - 1) 129 | for i := 0; i < len(a); i++ { 130 | for j := 0; j < len(b); j++ { 131 | r[i+j].Add(r[i+j], ff.NewElement().Mul(a[i], b[j])) 132 | } 133 | } 134 | return r 135 | } 136 | 137 | func polynomialDiv(a, b []*big.Int) ([]*big.Int, []*big.Int) { 138 | // https://en.wikipedia.org/wiki/Division_algorithm 139 | r := arrayOfZeroes(len(a) - len(b) + 1) 140 | rem := a 141 | for len(rem) >= len(b) { 142 | l := fDiv(rem[len(rem)-1], b[len(b)-1]) 143 | pos := len(rem) - len(b) 144 | r[pos] = l 145 | aux := arrayOfZeroes(pos) 146 | aux1 := append(aux, l) 147 | aux2 := polynomialSub(rem, polynomialMul(b, aux1)) 148 | rem = aux2[:len(aux2)-1] 149 | } 150 | return r, rem 151 | } 152 | 153 | func polynomialDivE(a, b []*ff.Element) ([]*ff.Element, []*ff.Element) { 154 | // https://en.wikipedia.org/wiki/Division_algorithm 155 | r := arrayOfZeroesE(len(a) - len(b) + 1) 156 | rem := a 157 | for len(rem) >= len(b) { 158 | l := ff.NewElement().Div(rem[len(rem)-1], b[len(b)-1]) 159 | pos := len(rem) - len(b) 160 | r[pos] = l 161 | aux := arrayOfZeroesE(pos) 162 | aux1 := append(aux, l) 163 | aux2 := polynomialSubE(rem, polynomialMulE(b, aux1)) 164 | rem = aux2[:len(aux2)-1] 165 | } 166 | return r, rem 167 | } 168 | -------------------------------------------------------------------------------- /prover/arithmetic_test.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "crypto/rand" 5 | "math/big" 6 | "testing" 7 | 8 | cryptoConstants "github.com/iden3/go-iden3-crypto/constants" 9 | "github.com/iden3/go-iden3-crypto/utils" 10 | ) 11 | 12 | func randBI() *big.Int { 13 | maxbits := 256 14 | b := make([]byte, (maxbits/8)-1) 15 | _, err := rand.Read(b) 16 | if err != nil { 17 | panic(err) 18 | } 19 | r := new(big.Int).SetBytes(b) 20 | return new(big.Int).Mod(r, cryptoConstants.Q) 21 | } 22 | 23 | func BenchmarkArithmetic(b *testing.B) { 24 | // generate arrays with bigint 25 | var p, q []*big.Int 26 | for i := 0; i < 1000; i++ { 27 | pi := randBI() 28 | p = append(p, pi) 29 | } 30 | for i := 1000 - 1; i >= 0; i-- { 31 | q = append(q, p[i]) 32 | } 33 | pe := utils.BigIntArrayToElementArray(p) 34 | qe := utils.BigIntArrayToElementArray(q) 35 | 36 | b.Run("polynomialSub", func(b *testing.B) { 37 | for i := 0; i < b.N; i++ { 38 | polynomialSub(p, q) 39 | } 40 | }) 41 | b.Run("polynomialSubE", func(b *testing.B) { 42 | for i := 0; i < b.N; i++ { 43 | polynomialSubE(pe, qe) 44 | } 45 | }) 46 | b.Run("polynomialMul", func(b *testing.B) { 47 | for i := 0; i < b.N; i++ { 48 | polynomialMul(p, q) 49 | } 50 | }) 51 | b.Run("polynomialMulE", func(b *testing.B) { 52 | for i := 0; i < b.N; i++ { 53 | polynomialMulE(pe, qe) 54 | } 55 | }) 56 | b.Run("polynomialDiv", func(b *testing.B) { 57 | for i := 0; i < b.N; i++ { 58 | polynomialDiv(p, q) 59 | } 60 | }) 61 | b.Run("polynomialDivE", func(b *testing.B) { 62 | for i := 0; i < b.N; i++ { 63 | polynomialDivE(pe, qe) 64 | } 65 | }) 66 | } 67 | -------------------------------------------------------------------------------- /prover/gextra.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "math/big" 5 | 6 | bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare" 7 | cryptoConstants "github.com/iden3/go-iden3-crypto/constants" 8 | ) 9 | 10 | type tableG1 struct { 11 | data []*bn256.G1 12 | } 13 | 14 | func (t tableG1) getData() []*bn256.G1 { 15 | return t.data 16 | } 17 | 18 | // Compute table of gsize elements as :: 19 | // Table[0] = Inf 20 | // Table[1] = a[0] 21 | // Table[2] = a[1] 22 | // Table[3] = a[0]+a[1] 23 | // ..... 24 | // Table[(1<= 0; i-- { 88 | // TODO. bn256 doesn't export double operation. We will need to fork repo and export it 89 | Q = new(bn256.G1).Add(Q, Q) 90 | b := getBit(kExt, i) 91 | if b != 0 { 92 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 93 | Q.Add(Q, t.data[b]) 94 | } 95 | } 96 | if qPrev != nil { 97 | return Q.Add(Q, qPrev) 98 | } 99 | return Q 100 | } 101 | 102 | // Multiply scalar by precomputed table of G1 elements without intermediate doubling 103 | func mulTableNoDoubleG1(t []tableG1, k []*big.Int, qPrev *bn256.G1, gsize int) *bn256.G1 { 104 | // We need at least gsize elements. If not enough, fill with 0 105 | minNElems := len(t) * gsize 106 | kExt := make([]*big.Int, 0) 107 | kExt = append(kExt, k...) 108 | for i := len(k); i < minNElems; i++ { 109 | kExt = append(kExt, new(big.Int).SetUint64(0)) 110 | } 111 | // Init Adders 112 | nbitsQ := cryptoConstants.Q.BitLen() 113 | Q := make([]*bn256.G1, nbitsQ) 114 | 115 | for i := 0; i < nbitsQ; i++ { 116 | Q[i] = new(bn256.G1).ScalarBaseMult(big.NewInt(0)) 117 | } 118 | 119 | // Perform bitwise addition 120 | for j := 0; j < len(t); j++ { 121 | msb := getMsb(kExt[j*gsize : (j+1)*gsize]) 122 | 123 | for i := msb - 1; i >= 0; i-- { 124 | b := getBit(kExt[j*gsize:(j+1)*gsize], i) 125 | if b != 0 { 126 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 127 | Q[i].Add(Q[i], t[j].data[b]) 128 | } 129 | } 130 | } 131 | 132 | // Consolidate Addition 133 | R := new(bn256.G1).Set(Q[nbitsQ-1]) 134 | for i := nbitsQ - 1; i > 0; i-- { 135 | // TODO. bn256 doesn't export double operation. We will need to fork repo and export it 136 | R = new(bn256.G1).Add(R, R) 137 | R.Add(R, Q[i-1]) 138 | } 139 | 140 | if qPrev != nil { 141 | return R.Add(R, qPrev) 142 | } 143 | return R 144 | } 145 | 146 | // Compute tables within function. This solution should still be faster than std multiplication 147 | // for gsize = 7 148 | func scalarMultG1(a []*bn256.G1, k []*big.Int, qPrev *bn256.G1, gsize int) *bn256.G1 { 149 | ntables := int((len(a) + gsize - 1) / gsize) 150 | table := tableG1{} 151 | Q := new(bn256.G1).ScalarBaseMult(new(big.Int)) 152 | 153 | for i := 0; i < ntables-1; i++ { 154 | table.newTableG1(a[i*gsize:(i+1)*gsize], gsize, false) 155 | Q = table.mulTableG1(k[i*gsize:(i+1)*gsize], Q, gsize) 156 | } 157 | table.newTableG1(a[(ntables-1)*gsize:], gsize, false) 158 | Q = table.mulTableG1(k[(ntables-1)*gsize:], Q, gsize) 159 | 160 | if qPrev != nil { 161 | return Q.Add(Q, qPrev) 162 | } 163 | return Q 164 | } 165 | 166 | // Multiply scalar by precomputed table of G1 elements without intermediate doubling 167 | func scalarMultNoDoubleG1(a []*bn256.G1, k []*big.Int, qPrev *bn256.G1, gsize int) *bn256.G1 { 168 | ntables := int((len(a) + gsize - 1) / gsize) 169 | table := tableG1{} 170 | 171 | // We need at least gsize elements. If not enough, fill with 0 172 | minNElems := ntables * gsize 173 | kExt := make([]*big.Int, 0) 174 | kExt = append(kExt, k...) 175 | for i := len(k); i < minNElems; i++ { 176 | kExt = append(kExt, new(big.Int).SetUint64(0)) 177 | } 178 | // Init Adders 179 | nbitsQ := cryptoConstants.Q.BitLen() 180 | Q := make([]*bn256.G1, nbitsQ) 181 | 182 | for i := 0; i < nbitsQ; i++ { 183 | Q[i] = new(bn256.G1).ScalarBaseMult(big.NewInt(0)) 184 | } 185 | 186 | // Perform bitwise addition 187 | for j := 0; j < ntables-1; j++ { 188 | table.newTableG1(a[j*gsize:(j+1)*gsize], gsize, false) 189 | msb := getMsb(kExt[j*gsize : (j+1)*gsize]) 190 | 191 | for i := msb - 1; i >= 0; i-- { 192 | b := getBit(kExt[j*gsize:(j+1)*gsize], i) 193 | if b != 0 { 194 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 195 | Q[i].Add(Q[i], table.data[b]) 196 | } 197 | } 198 | } 199 | table.newTableG1(a[(ntables-1)*gsize:], gsize, false) 200 | msb := getMsb(kExt[(ntables-1)*gsize:]) 201 | 202 | for i := msb - 1; i >= 0; i-- { 203 | b := getBit(kExt[(ntables-1)*gsize:], i) 204 | if b != 0 { 205 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 206 | Q[i].Add(Q[i], table.data[b]) 207 | } 208 | } 209 | 210 | // Consolidate Addition 211 | R := new(bn256.G1).Set(Q[nbitsQ-1]) 212 | for i := nbitsQ - 1; i > 0; i-- { 213 | // TODO. bn256 doesn't export double operation. We will need to fork repo and export it 214 | R = new(bn256.G1).Add(R, R) 215 | R.Add(R, Q[i-1]) 216 | } 217 | if qPrev != nil { 218 | return R.Add(R, qPrev) 219 | } 220 | return R 221 | } 222 | 223 | ///// 224 | 225 | // TODO - How can avoid replicating code in G2? 226 | //G2 227 | 228 | type tableG2 struct { 229 | data []*bn256.G2 230 | } 231 | 232 | func (t tableG2) getData() []*bn256.G2 { 233 | return t.data 234 | } 235 | 236 | // Compute table of gsize elements as :: 237 | // Table[0] = Inf 238 | // Table[1] = a[0] 239 | // Table[2] = a[1] 240 | // Table[3] = a[0]+a[1] 241 | // ..... 242 | // Table[(1< toaffine = True doesnt work. Problem with Marshal/Unmarshal 244 | func (t *tableG2) newTableG2(a []*bn256.G2, gsize int, toaffine bool) { 245 | // EC table 246 | table := make([]*bn256.G2, 0) 247 | 248 | // We need at least gsize elements. If not enough, fill with 0 249 | aExt := make([]*bn256.G2, 0) 250 | aExt = append(aExt, a...) 251 | 252 | for i := len(a); i < gsize; i++ { 253 | aExt = append(aExt, new(bn256.G2).ScalarBaseMult(big.NewInt(0))) 254 | } 255 | 256 | elG2 := new(bn256.G2).ScalarBaseMult(big.NewInt(0)) 257 | table = append(table, elG2) 258 | lastPow2 := 1 259 | nelems := 0 260 | for i := 1; i < 1<= 0; i-- { 307 | // TODO. bn256 doesn't export double operation. We will need to fork repo and export it 308 | Q = new(bn256.G2).Add(Q, Q) 309 | b := getBit(kExt, i) 310 | if b != 0 { 311 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 312 | Q.Add(Q, t.data[b]) 313 | } 314 | } 315 | if qPrev != nil { 316 | return Q.Add(Q, qPrev) 317 | } 318 | return Q 319 | } 320 | 321 | // Multiply scalar by precomputed table of G2 elements without intermediate doubling 322 | func mulTableNoDoubleG2(t []tableG2, k []*big.Int, qPrev *bn256.G2, gsize int) *bn256.G2 { 323 | // We need at least gsize elements. If not enough, fill with 0 324 | minNElems := len(t) * gsize 325 | kExt := make([]*big.Int, 0) 326 | kExt = append(kExt, k...) 327 | for i := len(k); i < minNElems; i++ { 328 | kExt = append(kExt, new(big.Int).SetUint64(0)) 329 | } 330 | // Init Adders 331 | nbitsQ := cryptoConstants.Q.BitLen() 332 | Q := make([]*bn256.G2, nbitsQ) 333 | 334 | for i := 0; i < nbitsQ; i++ { 335 | Q[i] = new(bn256.G2).ScalarBaseMult(big.NewInt(0)) 336 | } 337 | 338 | // Perform bitwise addition 339 | for j := 0; j < len(t); j++ { 340 | msb := getMsb(kExt[j*gsize : (j+1)*gsize]) 341 | 342 | for i := msb - 1; i >= 0; i-- { 343 | b := getBit(kExt[j*gsize:(j+1)*gsize], i) 344 | if b != 0 { 345 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 346 | Q[i].Add(Q[i], t[j].data[b]) 347 | } 348 | } 349 | } 350 | 351 | // Consolidate Addition 352 | R := new(bn256.G2).Set(Q[nbitsQ-1]) 353 | for i := nbitsQ - 1; i > 0; i-- { 354 | // TODO. bn256 doesn't export double operation. We will need to fork repo and export it 355 | R = new(bn256.G2).Add(R, R) 356 | R.Add(R, Q[i-1]) 357 | } 358 | if qPrev != nil { 359 | return R.Add(R, qPrev) 360 | } 361 | return R 362 | } 363 | 364 | // Compute tables within function. This solution should still be faster than std multiplication 365 | // for gsize = 7 366 | func scalarMultG2(a []*bn256.G2, k []*big.Int, qPrev *bn256.G2, gsize int) *bn256.G2 { 367 | ntables := int((len(a) + gsize - 1) / gsize) 368 | table := tableG2{} 369 | Q := new(bn256.G2).ScalarBaseMult(new(big.Int)) 370 | 371 | for i := 0; i < ntables-1; i++ { 372 | table.newTableG2(a[i*gsize:(i+1)*gsize], gsize, false) 373 | Q = table.mulTableG2(k[i*gsize:(i+1)*gsize], Q, gsize) 374 | } 375 | table.newTableG2(a[(ntables-1)*gsize:], gsize, false) 376 | Q = table.mulTableG2(k[(ntables-1)*gsize:], Q, gsize) 377 | 378 | if qPrev != nil { 379 | return Q.Add(Q, qPrev) 380 | } 381 | return Q 382 | } 383 | 384 | // Multiply scalar by precomputed table of G2 elements without intermediate doubling 385 | func scalarMultNoDoubleG2(a []*bn256.G2, k []*big.Int, qPrev *bn256.G2, gsize int) *bn256.G2 { 386 | ntables := int((len(a) + gsize - 1) / gsize) 387 | table := tableG2{} 388 | 389 | // We need at least gsize elements. If not enough, fill with 0 390 | minNElems := ntables * gsize 391 | kExt := make([]*big.Int, 0) 392 | kExt = append(kExt, k...) 393 | for i := len(k); i < minNElems; i++ { 394 | kExt = append(kExt, new(big.Int).SetUint64(0)) 395 | } 396 | // Init Adders 397 | nbitsQ := cryptoConstants.Q.BitLen() 398 | Q := make([]*bn256.G2, nbitsQ) 399 | 400 | for i := 0; i < nbitsQ; i++ { 401 | Q[i] = new(bn256.G2).ScalarBaseMult(big.NewInt(0)) 402 | } 403 | 404 | // Perform bitwise addition 405 | for j := 0; j < ntables-1; j++ { 406 | table.newTableG2(a[j*gsize:(j+1)*gsize], gsize, false) 407 | msb := getMsb(kExt[j*gsize : (j+1)*gsize]) 408 | 409 | for i := msb - 1; i >= 0; i-- { 410 | b := getBit(kExt[j*gsize:(j+1)*gsize], i) 411 | if b != 0 { 412 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 413 | Q[i].Add(Q[i], table.data[b]) 414 | } 415 | } 416 | } 417 | table.newTableG2(a[(ntables-1)*gsize:], gsize, false) 418 | msb := getMsb(kExt[(ntables-1)*gsize:]) 419 | 420 | for i := msb - 1; i >= 0; i-- { 421 | b := getBit(kExt[(ntables-1)*gsize:], i) 422 | if b != 0 { 423 | // TODO. bn256 doesn't export mixed addition (Jacobian + Affine), which is more efficient. 424 | Q[i].Add(Q[i], table.data[b]) 425 | } 426 | } 427 | 428 | // Consolidate Addition 429 | R := new(bn256.G2).Set(Q[nbitsQ-1]) 430 | for i := nbitsQ - 1; i > 0; i-- { 431 | // TODO. bn256 doesn't export double operation. We will need to fork repo and export it 432 | R = new(bn256.G2).Add(R, R) 433 | R.Add(R, Q[i-1]) 434 | } 435 | if qPrev != nil { 436 | return R.Add(R, qPrev) 437 | } 438 | return R 439 | } 440 | 441 | // Return most significant bit position in a group of Big Integers 442 | func getMsb(k []*big.Int) int { 443 | msb := 0 444 | 445 | for _, el := range k { 446 | tmpMsb := el.BitLen() 447 | if tmpMsb > msb { 448 | msb = tmpMsb 449 | } 450 | } 451 | return msb 452 | } 453 | 454 | // Return ith bit in group of Big Integers 455 | func getBit(k []*big.Int, i int) uint { 456 | tableIdx := uint(0) 457 | 458 | for idx, el := range k { 459 | b := el.Bit(i) 460 | tableIdx += (b << idx) 461 | } 462 | return tableIdx 463 | } 464 | -------------------------------------------------------------------------------- /prover/gextra_test.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "fmt" 7 | "math/big" 8 | "testing" 9 | "time" 10 | 11 | bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare" 12 | ) 13 | 14 | const ( 15 | N1 = 5000 16 | N2 = 5000 17 | ) 18 | 19 | func randomBigIntArray(n int) []*big.Int { 20 | var p []*big.Int 21 | for i := 0; i < n; i++ { 22 | pi := randBI() 23 | p = append(p, pi) 24 | } 25 | 26 | return p 27 | } 28 | 29 | func randomG1Array(n int) []*bn256.G1 { 30 | arrayG1 := make([]*bn256.G1, n) 31 | 32 | for i := 0; i < n; i++ { 33 | _, arrayG1[i], _ = bn256.RandomG1(rand.Reader) 34 | } 35 | return arrayG1 36 | } 37 | 38 | func randomG2Array(n int) []*bn256.G2 { 39 | arrayG2 := make([]*bn256.G2, n) 40 | 41 | for i := 0; i < n; i++ { 42 | _, arrayG2[i], _ = bn256.RandomG2(rand.Reader) 43 | } 44 | return arrayG2 45 | } 46 | 47 | func TestTableG1(t *testing.T) { 48 | n := N1 49 | 50 | // init scalar 51 | var arrayW = randomBigIntArray(n) 52 | // init G1 array 53 | var arrayG1 = randomG1Array(n) 54 | 55 | beforeT := time.Now() 56 | Q1 := new(bn256.G1).ScalarBaseMult(new(big.Int)) 57 | for i := 0; i < n; i++ { 58 | Q1.Add(Q1, new(bn256.G1).ScalarMult(arrayG1[i], arrayW[i])) 59 | } 60 | fmt.Println("Std. Mult. time elapsed:", time.Since(beforeT)) 61 | 62 | for gsize := 2; gsize < 10; gsize++ { 63 | ntables := int((n + gsize - 1) / gsize) 64 | table := make([]tableG1, ntables) 65 | 66 | for i := 0; i < ntables-1; i++ { 67 | table[i].newTableG1(arrayG1[i*gsize:(i+1)*gsize], gsize, true) 68 | } 69 | table[ntables-1].newTableG1(arrayG1[(ntables-1)*gsize:], gsize, true) 70 | 71 | beforeT = time.Now() 72 | Q2 := new(bn256.G1).ScalarBaseMult(new(big.Int)) 73 | for i := 0; i < ntables-1; i++ { 74 | Q2 = table[i].mulTableG1(arrayW[i*gsize:(i+1)*gsize], Q2, gsize) 75 | } 76 | Q2 = table[ntables-1].mulTableG1(arrayW[(ntables-1)*gsize:], Q2, gsize) 77 | fmt.Printf("Gsize : %d, TMult time elapsed: %s\n", gsize, time.Since(beforeT)) 78 | 79 | beforeT = time.Now() 80 | Q3 := scalarMultG1(arrayG1, arrayW, nil, gsize) 81 | fmt.Printf("Gsize : %d, TMult time elapsed (inc table comp): %s\n", gsize, time.Since(beforeT)) 82 | 83 | beforeT = time.Now() 84 | Q4 := mulTableNoDoubleG1(table, arrayW, nil, gsize) 85 | fmt.Printf("Gsize : %d, TMultNoDouble time elapsed: %s\n", gsize, time.Since(beforeT)) 86 | 87 | beforeT = time.Now() 88 | Q5 := scalarMultNoDoubleG1(arrayG1, arrayW, nil, gsize) 89 | fmt.Printf("Gsize : %d, TMultNoDouble time elapsed (inc table comp): %s\n", gsize, time.Since(beforeT)) 90 | 91 | if bytes.Compare(Q1.Marshal(), Q2.Marshal()) != 0 { 92 | t.Error("Error in TMult") 93 | } 94 | if bytes.Compare(Q1.Marshal(), Q3.Marshal()) != 0 { 95 | t.Error("Error in TMult with table comp") 96 | } 97 | if bytes.Compare(Q1.Marshal(), Q4.Marshal()) != 0 { 98 | t.Error("Error in TMultNoDouble") 99 | } 100 | if bytes.Compare(Q1.Marshal(), Q5.Marshal()) != 0 { 101 | t.Error("Error in TMultNoDoublee with table comp") 102 | } 103 | } 104 | } 105 | 106 | func TestTableG2(t *testing.T) { 107 | n := N2 108 | 109 | // init scalar 110 | var arrayW = randomBigIntArray(n) 111 | // init G2 array 112 | var arrayG2 = randomG2Array(n) 113 | 114 | beforeT := time.Now() 115 | Q1 := new(bn256.G2).ScalarBaseMult(new(big.Int)) 116 | for i := 0; i < n; i++ { 117 | Q1.Add(Q1, new(bn256.G2).ScalarMult(arrayG2[i], arrayW[i])) 118 | } 119 | fmt.Println("Std. Mult. time elapsed:", time.Since(beforeT)) 120 | 121 | for gsize := 2; gsize < 10; gsize++ { 122 | ntables := int((n + gsize - 1) / gsize) 123 | table := make([]tableG2, ntables) 124 | 125 | for i := 0; i < ntables-1; i++ { 126 | table[i].newTableG2(arrayG2[i*gsize:(i+1)*gsize], gsize, false) 127 | } 128 | table[ntables-1].newTableG2(arrayG2[(ntables-1)*gsize:], gsize, false) 129 | 130 | beforeT = time.Now() 131 | Q2 := new(bn256.G2).ScalarBaseMult(new(big.Int)) 132 | for i := 0; i < ntables-1; i++ { 133 | Q2 = table[i].mulTableG2(arrayW[i*gsize:(i+1)*gsize], Q2, gsize) 134 | } 135 | Q2 = table[ntables-1].mulTableG2(arrayW[(ntables-1)*gsize:], Q2, gsize) 136 | fmt.Printf("Gsize : %d, TMult time elapsed: %s\n", gsize, time.Since(beforeT)) 137 | 138 | beforeT = time.Now() 139 | Q3 := scalarMultG2(arrayG2, arrayW, nil, gsize) 140 | fmt.Printf("Gsize : %d, TMult time elapsed (inc table comp): %s\n", gsize, time.Since(beforeT)) 141 | 142 | beforeT = time.Now() 143 | Q4 := mulTableNoDoubleG2(table, arrayW, nil, gsize) 144 | fmt.Printf("Gsize : %d, TMultNoDouble time elapsed: %s\n", gsize, time.Since(beforeT)) 145 | 146 | beforeT = time.Now() 147 | Q5 := scalarMultNoDoubleG2(arrayG2, arrayW, nil, gsize) 148 | fmt.Printf("Gsize : %d, TMultNoDouble time elapsed (inc table comp): %s\n", gsize, time.Since(beforeT)) 149 | 150 | if bytes.Compare(Q1.Marshal(), Q2.Marshal()) != 0 { 151 | t.Error("Error in TMult") 152 | } 153 | if bytes.Compare(Q1.Marshal(), Q3.Marshal()) != 0 { 154 | t.Error("Error in TMult with table comp") 155 | } 156 | if bytes.Compare(Q1.Marshal(), Q4.Marshal()) != 0 { 157 | t.Error("Error in TMultNoDouble") 158 | } 159 | if bytes.Compare(Q1.Marshal(), Q5.Marshal()) != 0 { 160 | t.Error("Error in TMultNoDoublee with table comp") 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /prover/ifft.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "math" 5 | "math/big" 6 | 7 | "github.com/iden3/go-circom-prover-verifier/types" 8 | "github.com/iden3/go-iden3-crypto/ff" 9 | ) 10 | 11 | type rootsT struct { 12 | roots [][]*ff.Element 13 | w []*ff.Element 14 | } 15 | 16 | func newRootsT() rootsT { 17 | var roots rootsT 18 | 19 | rem := new(big.Int).Sub(types.R, big.NewInt(1)) 20 | s := 0 21 | for rem.Bit(0) == 0 { // rem.Bit==0 when even 22 | s++ 23 | rem = new(big.Int).Rsh(rem, 1) 24 | } 25 | roots.w = make([]*ff.Element, s+1) 26 | roots.w[s] = ff.NewElement().SetBigInt(fExp(big.NewInt(5), rem)) 27 | 28 | n := s - 1 29 | for n >= 0 { 30 | roots.w[n] = ff.NewElement().Mul(roots.w[n+1], roots.w[n+1]) 31 | n-- 32 | } 33 | roots.roots = make([][]*ff.Element, 50) // TODO WIP 34 | 35 | roots.setRoots(15) 36 | return roots 37 | } 38 | 39 | func (roots rootsT) setRoots(n int) { 40 | for i := n; i >= 0 && nil == roots.roots[i]; i-- { // TODO tmp i<=len(r) 41 | r := ff.NewElement().SetBigInt(big.NewInt(1)) 42 | nroots := 1 << i 43 | var rootsi []*ff.Element 44 | for j := 0; j < nroots; j++ { 45 | rootsi = append(rootsi, r) 46 | r = ff.NewElement().Mul(r, roots.w[i]) 47 | } 48 | roots.roots[i] = rootsi 49 | } 50 | } 51 | 52 | func fftroots(roots rootsT, pall []*ff.Element, bits, offset, step int) []*ff.Element { 53 | n := 1 << bits 54 | if n == 1 { 55 | return []*ff.Element{pall[offset]} 56 | } else if n == 2 { 57 | return []*ff.Element{ 58 | ff.NewElement().Add(pall[offset], pall[offset+step]), // TODO tmp 59 | ff.NewElement().Sub(pall[offset], pall[offset+step]), 60 | } 61 | } 62 | 63 | ndiv2 := n >> 1 64 | p1 := fftroots(roots, pall, bits-1, offset, step*2) 65 | p2 := fftroots(roots, pall, bits-1, offset+step, step*2) 66 | 67 | out := make([]*ff.Element, n) 68 | for i := 0; i < ndiv2; i++ { 69 | out[i] = ff.NewElement().Add(p1[i], ff.NewElement().Mul(roots.roots[bits][i], p2[i])) 70 | out[i+ndiv2] = ff.NewElement().Sub(p1[i], ff.NewElement().Mul(roots.roots[bits][i], p2[i])) 71 | } 72 | return out 73 | } 74 | 75 | func fft(p []*ff.Element) []*ff.Element { 76 | if len(p) <= 1 { 77 | return p 78 | } 79 | bits := math.Log2(float64(len(p)-1)) + 1 80 | roots := newRootsT() 81 | roots.setRoots(int(bits)) 82 | m := 1 << int(bits) 83 | ep := extend(p, m) 84 | res := fftroots(roots, ep, int(bits), 0, 1) 85 | return res 86 | } 87 | 88 | func ifft(p []*ff.Element) []*ff.Element { 89 | res := fft(p) 90 | bits := math.Log2(float64(len(p)-1)) + 1 91 | m := 1 << int(bits) 92 | 93 | twoinvm := ff.NewElement().SetBigInt(fInv(fMul(big.NewInt(1), big.NewInt(int64(m))))) 94 | 95 | var resn []*ff.Element 96 | for i := 0; i < m; i++ { 97 | resn = append(resn, ff.NewElement().Mul(res[(m-i)%m], twoinvm)) 98 | } 99 | 100 | return resn 101 | } 102 | 103 | func extend(p []*ff.Element, e int) []*ff.Element { 104 | if e == len(p) { 105 | return p 106 | } 107 | z := arrayOfZeroesE(e - len(p)) 108 | return append(p, z...) 109 | } 110 | -------------------------------------------------------------------------------- /prover/prover.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "crypto/rand" 5 | "math" 6 | "math/big" 7 | "runtime" 8 | "sync" 9 | 10 | bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare" 11 | "github.com/iden3/go-circom-prover-verifier/types" 12 | "github.com/iden3/go-iden3-crypto/utils" 13 | //"fmt" 14 | ) 15 | 16 | // Group Size 17 | const ( 18 | GSIZE = 6 19 | ) 20 | 21 | func randBigInt() (*big.Int, error) { 22 | maxbits := types.R.BitLen() 23 | b := make([]byte, (maxbits/8)-1) 24 | _, err := rand.Read(b) 25 | if err != nil { 26 | return nil, err 27 | } 28 | r := new(big.Int).SetBytes(b) 29 | rq := new(big.Int).Mod(r, types.R) 30 | 31 | return rq, nil 32 | } 33 | 34 | // GenerateProof generates the Groth16 zkSNARK proof 35 | func GenerateProof(pk *types.Pk, w types.Witness) (*types.Proof, []*big.Int, error) { 36 | var proof types.Proof 37 | 38 | r, err := randBigInt() 39 | if err != nil { 40 | return nil, nil, err 41 | } 42 | s, err := randBigInt() 43 | if err != nil { 44 | return nil, nil, err 45 | } 46 | 47 | // BEGIN PAR 48 | numcpu := runtime.NumCPU() 49 | 50 | proofA := arrayOfZeroesG1(numcpu) 51 | proofB := arrayOfZeroesG2(numcpu) 52 | proofC := arrayOfZeroesG1(numcpu) 53 | proofBG1 := arrayOfZeroesG1(numcpu) 54 | gsize := GSIZE 55 | var wg1 sync.WaitGroup 56 | wg1.Add(numcpu) 57 | for _cpu, _ranges := range ranges(pk.NVars, numcpu) { 58 | // split 1 59 | go func(cpu int, ranges [2]int) { 60 | proofA[cpu] = scalarMultNoDoubleG1(pk.A[ranges[0]:ranges[1]], 61 | w[ranges[0]:ranges[1]], 62 | proofA[cpu], 63 | gsize) 64 | proofB[cpu] = scalarMultNoDoubleG2(pk.B2[ranges[0]:ranges[1]], 65 | w[ranges[0]:ranges[1]], 66 | proofB[cpu], 67 | gsize) 68 | proofBG1[cpu] = scalarMultNoDoubleG1(pk.B1[ranges[0]:ranges[1]], 69 | w[ranges[0]:ranges[1]], 70 | proofBG1[cpu], 71 | gsize) 72 | minLim := pk.NPublic + 1 73 | if ranges[0] > pk.NPublic+1 { 74 | minLim = ranges[0] 75 | } 76 | if ranges[1] > pk.NPublic+1 { 77 | proofC[cpu] = scalarMultNoDoubleG1(pk.C[minLim:ranges[1]], 78 | w[minLim:ranges[1]], 79 | proofC[cpu], 80 | gsize) 81 | } 82 | wg1.Done() 83 | }(_cpu, _ranges) 84 | } 85 | wg1.Wait() 86 | // join 1 87 | for cpu := 1; cpu < numcpu; cpu++ { 88 | proofA[0].Add(proofA[0], proofA[cpu]) 89 | proofB[0].Add(proofB[0], proofB[cpu]) 90 | proofC[0].Add(proofC[0], proofC[cpu]) 91 | proofBG1[0].Add(proofBG1[0], proofBG1[cpu]) 92 | } 93 | proof.A = proofA[0] 94 | proof.B = proofB[0] 95 | proof.C = proofC[0] 96 | // END PAR 97 | 98 | h := calculateH(pk, w) 99 | 100 | proof.A.Add(proof.A, pk.VkAlpha1) 101 | proof.A.Add(proof.A, new(bn256.G1).ScalarMult(pk.VkDelta1, r)) 102 | 103 | proof.B.Add(proof.B, pk.VkBeta2) 104 | proof.B.Add(proof.B, new(bn256.G2).ScalarMult(pk.VkDelta2, s)) 105 | 106 | proofBG1[0].Add(proofBG1[0], pk.VkBeta1) 107 | proofBG1[0].Add(proofBG1[0], new(bn256.G1).ScalarMult(pk.VkDelta1, s)) 108 | 109 | proofC = arrayOfZeroesG1(numcpu) 110 | var wg2 sync.WaitGroup 111 | wg2.Add(numcpu) 112 | for _cpu, _ranges := range ranges(len(h), numcpu) { 113 | // split 2 114 | go func(cpu int, ranges [2]int) { 115 | proofC[cpu] = scalarMultNoDoubleG1(pk.HExps[ranges[0]:ranges[1]], 116 | h[ranges[0]:ranges[1]], 117 | proofC[cpu], 118 | gsize) 119 | wg2.Done() 120 | }(_cpu, _ranges) 121 | } 122 | wg2.Wait() 123 | // join 2 124 | for cpu := 1; cpu < numcpu; cpu++ { 125 | proofC[0].Add(proofC[0], proofC[cpu]) 126 | } 127 | proof.C.Add(proof.C, proofC[0]) 128 | 129 | proof.C.Add(proof.C, new(bn256.G1).ScalarMult(proof.A, s)) 130 | proof.C.Add(proof.C, new(bn256.G1).ScalarMult(proofBG1[0], r)) 131 | rsneg := new(big.Int).Mod(new(big.Int).Neg(new(big.Int).Mul(r, s)), types.R) 132 | proof.C.Add(proof.C, new(bn256.G1).ScalarMult(pk.VkDelta1, rsneg)) 133 | 134 | pubSignals := w[1 : pk.NPublic+1] 135 | 136 | return &proof, pubSignals, nil 137 | } 138 | 139 | func calculateH(pk *types.Pk, w types.Witness) []*big.Int { 140 | m := pk.DomainSize 141 | polAT := arrayOfZeroes(m) 142 | polBT := arrayOfZeroes(m) 143 | 144 | numcpu := runtime.NumCPU() 145 | 146 | var wg1 sync.WaitGroup 147 | wg1.Add(2) 148 | go func() { 149 | for i := 0; i < pk.NVars; i++ { 150 | for j := range pk.PolsA[i] { 151 | polAT[j] = fAdd(polAT[j], fMul(w[i], pk.PolsA[i][j])) 152 | } 153 | } 154 | wg1.Done() 155 | }() 156 | go func() { 157 | for i := 0; i < pk.NVars; i++ { 158 | for j := range pk.PolsB[i] { 159 | polBT[j] = fAdd(polBT[j], fMul(w[i], pk.PolsB[i][j])) 160 | } 161 | } 162 | wg1.Done() 163 | }() 164 | wg1.Wait() 165 | polATe := utils.BigIntArrayToElementArray(polAT) 166 | polBTe := utils.BigIntArrayToElementArray(polBT) 167 | 168 | polASe := ifft(polATe) 169 | polBSe := ifft(polBTe) 170 | 171 | r := int(math.Log2(float64(m))) + 1 172 | roots := newRootsT() 173 | roots.setRoots(r) 174 | 175 | var wg2 sync.WaitGroup 176 | wg2.Add(numcpu) 177 | for _cpu, _ranges := range ranges(len(polASe), numcpu) { 178 | go func(cpu int, ranges [2]int) { 179 | for i := ranges[0]; i < ranges[1]; i++ { 180 | polASe[i].Mul(polASe[i], roots.roots[r][i]) 181 | polBSe[i].Mul(polBSe[i], roots.roots[r][i]) 182 | } 183 | wg2.Done() 184 | }(_cpu, _ranges) 185 | } 186 | wg2.Wait() 187 | 188 | polATodd := fft(polASe) 189 | polBTodd := fft(polBSe) 190 | 191 | polABT := arrayOfZeroesE(len(polASe) * 2) 192 | var wg3 sync.WaitGroup 193 | wg3.Add(numcpu) 194 | for _cpu, _ranges := range ranges(len(polASe), numcpu) { 195 | go func(cpu int, ranges [2]int) { 196 | for i := ranges[0]; i < ranges[1]; i++ { 197 | polABT[2*i].Mul(polATe[i], polBTe[i]) 198 | polABT[2*i+1].Mul(polATodd[i], polBTodd[i]) 199 | } 200 | wg3.Done() 201 | }(_cpu, _ranges) 202 | } 203 | wg3.Wait() 204 | 205 | hSeFull := ifft(polABT) 206 | 207 | hSe := hSeFull[m:] 208 | return utils.ElementArrayToBigIntArray(hSe) 209 | } 210 | 211 | func ranges(n, parts int) [][2]int { 212 | s := make([][2]int, parts) 213 | p := float64(n) / float64(parts) 214 | for i := 0; i < parts; i++ { 215 | a, b := int(float64(i)*p), int(float64(i+1)*p) 216 | s[i] = [2]int{a, b} 217 | } 218 | return s 219 | } 220 | -------------------------------------------------------------------------------- /prover/prover_test.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "testing" 9 | "time" 10 | 11 | "github.com/iden3/go-circom-prover-verifier/parsers" 12 | "github.com/iden3/go-circom-prover-verifier/verifier" 13 | "github.com/stretchr/testify/assert" 14 | "github.com/stretchr/testify/require" 15 | ) 16 | 17 | func TestCircuitsGenerateProof(t *testing.T) { 18 | testCircuitGenerateProof(t, "circuit1k") // 1000 constraints 19 | testCircuitGenerateProof(t, "circuit5k") // 5000 constraints 20 | // testCircuitGenerateProof(t, "circuit10k") // 10000 constraints 21 | // testCircuitGenerateProof(t, "circuit20k") // 20000 constraints 22 | } 23 | 24 | func testCircuitGenerateProof(t *testing.T, circuit string) { 25 | // Using json provingKey file: 26 | // provingKeyJson, err := ioutil.ReadFile("../testdata/" + circuit + "/proving_key.json") 27 | // require.Nil(t, err) 28 | // pk, err := parsers.ParsePk(provingKeyJson) 29 | // require.Nil(t, err) 30 | // witnessJson, err := ioutil.ReadFile("../testdata/" + circuit + "/witness.json") 31 | // require.Nil(t, err) 32 | // w, err := parsers.ParseWitness(witnessJson) 33 | // require.Nil(t, err) 34 | 35 | // Using bin provingKey file: 36 | // pkBinFile, err := os.Open("../testdata/" + circuit + "/proving_key.bin") 37 | // require.Nil(t, err) 38 | // defer pkBinFile.Close() 39 | // pk, err := parsers.ParsePkBin(pkBinFile) 40 | // require.Nil(t, err) 41 | 42 | // Using go bin provingKey file: 43 | pkGoBinFile, err := os.Open("../testdata/" + circuit + "/proving_key.go.bin") 44 | require.Nil(t, err) 45 | defer pkGoBinFile.Close() 46 | pk, err := parsers.ParsePkGoBin(pkGoBinFile) 47 | require.Nil(t, err) 48 | 49 | witnessBinFile, err := os.Open("../testdata/" + circuit + "/witness.bin") 50 | require.Nil(t, err) 51 | defer witnessBinFile.Close() 52 | w, err := parsers.ParseWitnessBin(witnessBinFile) 53 | require.Nil(t, err) 54 | 55 | beforeT := time.Now() 56 | proof, pubSignals, err := GenerateProof(pk, w) 57 | assert.Nil(t, err) 58 | fmt.Println("proof generation time for "+circuit+" elapsed:", time.Since(beforeT)) 59 | 60 | proofStr, err := parsers.ProofToJson(proof) 61 | assert.Nil(t, err) 62 | 63 | err = ioutil.WriteFile("../testdata/"+circuit+"/proof.json", proofStr, 0644) 64 | assert.Nil(t, err) 65 | publicStr, err := json.Marshal(parsers.ArrayBigIntToString(pubSignals)) 66 | assert.Nil(t, err) 67 | err = ioutil.WriteFile("../testdata/"+circuit+"/public.json", publicStr, 0644) 68 | assert.Nil(t, err) 69 | 70 | // verify the proof 71 | vkJson, err := ioutil.ReadFile("../testdata/" + circuit + "/verification_key.json") 72 | require.Nil(t, err) 73 | vk, err := parsers.ParseVk(vkJson) 74 | require.Nil(t, err) 75 | 76 | v := verifier.Verify(vk, proof, pubSignals) 77 | assert.True(t, v) 78 | 79 | // to verify the proof with snarkjs: 80 | // snarkjs verify --vk testdata/circuitX/verification_key.json -p testdata/circuitX/proof.json --pub testdata/circuitX/public.json 81 | } 82 | 83 | func BenchmarkGenerateProof(b *testing.B) { 84 | // benchmark with a circuit of 10000 constraints 85 | provingKeyJson, err := ioutil.ReadFile("../testdata/circuit5k/proving_key.json") 86 | require.Nil(b, err) 87 | pk, err := parsers.ParsePk(provingKeyJson) 88 | require.Nil(b, err) 89 | 90 | witnessJson, err := ioutil.ReadFile("../testdata/circuit5k/witness.json") 91 | require.Nil(b, err) 92 | w, err := parsers.ParseWitness(witnessJson) 93 | require.Nil(b, err) 94 | 95 | for i := 0; i < b.N; i++ { 96 | GenerateProof(pk, w) 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /prover/tables.md: -------------------------------------------------------------------------------- 1 | # Tables Pre-calculation 2 | The most time consuming part of a ZKSnark proof calculation is the scalar multiplication of elliptic curve points. Direct mechanism accumulates each multiplication. However, prover only needs the total accumulation. 3 | 4 | There are two potential improvements to the naive approach: 5 | 6 | 1. Apply Strauss-Shamir method (https://stackoverflow.com/questions/50993471/ec-scalar-multiplication-with-strauss-shamir-method). 7 | 2. Leave the doubling operation for the last step 8 | 9 | Both options can be combined. 10 | 11 | In the following table, we show the results of using the naive method, Srauss-Shamir and Strauss-Shamir + No doubling. These last two options are repeated for different table grouping order. 12 | 13 | There are 50000 G1 Elliptical Curve Points, and the scalars are 254 bits (BN256 curve). 14 | 15 | There may be some concern on the additional size of the tables since they need to be loaded into a smartphone during the proof, and the time required to load these tables may exceed the benefits. If this is a problem, another althernative is to compute the tables during the proof itself. Depending on the Group Size, timing may be better than the naive approach. 16 | 17 | 18 | | Algorithm (G1) | GS 2 | GS 3 | GS 4 | GS 5 | GS 6 | GS 7 | GS 8 | GS 9 | 19 | |---|---|---|--|---|---|---|---|---| 20 | | Naive | 6.63s | - | - | - | - | - | - | - | 21 | | Strauss | 13.16s | 9.03s | 6.95s | 5.61s | 4.91s | 4.26s | 3.88s | 3.54 s | 22 | | Strauss + Table Computation | 16.13s | 11.32s | 8.47s | 7.10s | 6.2s | 5.94s | 6.01s | 6.69s | 23 | | No Doubling | 3.74s | 3.00s | 2.38s | 1.96s | 1.79s | 1.54s | 1.50s | 1.44s| 24 | | No Doubling + Table Computation | 6.83s | 5.1s | 4.16s | 3.52s| 3.22s | 3.21s | 3.57s | 4.56s | 25 | 26 | There are 5000 G2 Elliptical Curve Points, and the scalars are 254 bits (BN256 curve). 27 | 28 | | Algorithm (G2) | GS 2 | GS 3 | GS 4 | GS 5 | GS 6 | GS 7 | GS 8 | GS 9 | 29 | |---|---|---|--|---|---|---|---|---| 30 | | Naive | 3.55s | | | | | | | | 31 | | Strauss | 3.55s | 2.54s | 1.96s | 1.58s | 1.38s | 1.20s | 1.03s | 937ms | 32 | | Strauss + Table Computation | 3.59s | 2.58s | 2.04s | 1.71s | 1.51s | 1.46s | 1.51s | 1.82s | 33 | | No Doubling | 1.49s | 1.16s | 952ms | 719ms | 661ms | 548ms | 506ms| 444ms | 34 | | No Doubling + Table Computation | 1.55s | 1.21s | 984ms | 841ms | 826ms | 847ms | 1.03s | 1.39s | 35 | 36 | | GS | Extra Disk Space per Constraint (G1)| 37 | |----|--------| 38 | | 2 | 64 B | 39 | | 3 | 106 B | 40 | | 4 | 192 B | 41 | | 5 | 346 B | 42 | | 6 | 618 B | 43 | | 7 | 1106 B | 44 | | 8 | 1984 B | 45 | | 9 | 3577 B | 46 | | N | 2^(N+6)/N - 64 B | 47 | 48 | Extra disk space per constraint in G2 is twice the requirements for G1 49 | 50 | -------------------------------------------------------------------------------- /testdata/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /testdata/circuit10k/circuit.circom: -------------------------------------------------------------------------------- 1 | template TestConstraints(n) { 2 | signal input in; 3 | signal output out; 4 | 5 | signal intermediate[n]; 6 | 7 | intermediate[0] <== in; 8 | for (var i=1; i