├── .gitattributes ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── artifacts ├── .gitkeep ├── artifacts_test.go ├── wasm_exec_go.js └── wasm_exec_tinygo.js ├── circuits └── zkcensus │ ├── zkcensus.go │ ├── zkcensus_inputs.go │ └── zkcensus_test.go ├── cmd ├── compiler │ ├── groth16.go │ ├── main.go │ └── plonk.go └── prover │ └── main.go ├── examples ├── go │ └── main.go ├── tinygowasi │ ├── .parcelrc │ ├── artifacts │ │ └── .gitkeep │ ├── index.html │ ├── package-lock.json │ ├── package.json │ ├── wasm_exec.js │ └── worker.js └── web │ ├── index_g16.html │ ├── index_plonk.html │ ├── main.go │ ├── wasm_exec.js │ ├── worker_g16.js │ └── worker_plonk.js ├── go.mod ├── go.sum ├── internal └── zkaddress │ ├── zkaddress.go │ └── zkaddress_test.go ├── prover ├── groth16.go ├── prover.go └── prover_test.go ├── std ├── hash │ └── poseidon │ │ ├── constants.go │ │ ├── poseidon.go │ │ └── poseidon_test.go ├── smt │ ├── utils.go │ ├── verifier.go │ └── verifier_test.go └── zkaddress │ ├── zkaddress.go │ └── zkaddress_test.go ├── wasi └── main.go └── wasm ├── g16 └── main.go └── plonk └── main.go /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pkey filter=lfs diff=lfs merge=lfs -text 2 | *.vkey filter=lfs diff=lfs merge=lfs -text 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | artifacts 2 | index.html 3 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | compile-prover-go-plonk: 2 | GOOS=js GOARCH=wasm go build -ldflags="-s -w" -o artifacts/plonk_prover.wasm wasm/plonk/main.go 3 | wasm-opt -O artifacts/plonk_prover.wasm -o artifacts/plonk_prover.wasm --enable-bulk-memory 4 | 5 | compile-prover-go-g16: 6 | GOOS=js GOARCH=wasm go build -ldflags="-s -w" -o artifacts/g16_prover.wasm wasm/g16/main.go 7 | wasm-opt -O artifacts/g16_prover.wasm -o artifacts/g16_prover.wasm --enable-bulk-memory 8 | 9 | compile-prover-tinygo-plonk: 10 | tinygo build -target=wasm -opt=1 -no-debug -scheduler=asyncify -o artifacts/plonk_prover.wasm wasm/plonk/main.go 11 | wasm-opt -O artifacts/plonk_prover.wasm -o artifacts/plonk_prover.wasm --enable-bulk-memory 12 | 13 | compile-prover-tinygo-g16: 14 | tinygo build -target=wasm -opt=1 -no-debug -scheduler=asyncify -o artifacts/g16_prover.wasm wasm/g16/main.go 15 | wasm-opt -O artifacts/g16_prover.wasm -o artifacts/g16_prover.wasm --enable-bulk-memory 16 | 17 | compile-prover-tinygo-g16-wasi: 18 | tinygo build -target=wasi -opt=1 -scheduler=asyncify -o artifacts/g16_prover.wasi wasi/main.go 19 | wasm-opt -O artifacts/g16_prover.wasi -o artifacts/g16_prover.wasi --enable-bulk-memory 20 | 21 | compile-circuit-plonk: 22 | @go run ./cmd/compiler --protocol=plonk 23 | 24 | compile-circuit-g16: 25 | @go run ./cmd/compiler --protocol=groth16 26 | 27 | run-go-example-plonk: 28 | @echo "compilling circuit and genering artifacts" 29 | @make compile-circuit-plonk 30 | @echo "copying artifacts" 31 | @go run ./cmd/prover/main.go --protocol=plonk -circuit=artifacts/zkcensus.ccs -pkey=artifacts/zkcensus.pkey -srs=artifacts/zkcensus.srs -witness=artifacts/zkcensus.witness 32 | 33 | run-go-example-g16: 34 | @echo "compilling circuit and genering artifacts" 35 | @make compile-circuit-g16 36 | @echo "copying artifacts" 37 | @go run ./cmd/prover/main.go --protocol=groth16 -circuit=artifacts/g16_zkcensus.ccs -pkey=artifacts/g16_zkcensus.pkey -witness=artifacts/zkcensus.witness 38 | 39 | run-go-web-example-plonk: 40 | @echo "compilling circuit and genering artifacts" 41 | @make compile-circuit-plonk 42 | @echo "copying artifacts" 43 | @cp ./artifacts/zkcensus.ccs ./wasm/plonk/zkcensus.ccs 44 | @cp ./artifacts/zkcensus.srs ./wasm/plonk/zkcensus.srs 45 | @cp ./artifacts/zkcensus.pkey ./wasm/plonk/zkcensus.pkey 46 | @echo "copying compatible wasm_exec.js" 47 | @cp ./artifacts/wasm_exec_go.js ./examples/web/wasm_exec.js 48 | @echo "compilling the prover for go-wasm" 49 | @make compile-prover-go-plonk 50 | @echo "removing copied artifacts" 51 | @rm ./wasm/plonk/zkcensus.ccs 52 | @rm ./wasm/plonk/zkcensus.srs 53 | @rm ./wasm/plonk/zkcensus.pkey 54 | @rm -f examples/web/index.html 55 | @ln -s index_plonk.html examples/web/index.html 56 | @go run examples/web/main.go 57 | 58 | run-tinygo-web-example-plonk: 59 | @echo "compilling circuit and genering artifacts" 60 | @make compile-circuit-plonk 61 | @echo "copying artifacts" 62 | @cp ./artifacts/zkcensus.ccs ./wasm/plonk/zkcensus.ccs 63 | @cp ./artifacts/zkcensus.srs ./wasm/plonk/zkcensus.srs 64 | @cp ./artifacts/zkcensus.pkey ./wasm/plonk/zkcensus.pkey 65 | @echo "compilling the prover for tinygo" 66 | @make compile-prover-tinygo-plonk 67 | @echo "removing copied artifacts" 68 | @rm ./wasm/plonk/zkcensus.ccs 69 | @rm ./wasm/plonk/zkcensus.srs 70 | @rm ./wasm/plonk/zkcensus.pkey 71 | @echo "copying compatible wasm_exec.js" 72 | @cp ./artifacts/wasm_exec_tinygo.js ./examples/web/wasm_exec.js 73 | @rm -f examples/web/index.html 74 | @ln -s index_plonk.html examples/web/index.html 75 | @go run examples/web/main.go 76 | 77 | run-tinygo-web-example-g16: 78 | @echo "compilling circuit and genering artifacts for groth16" 79 | @make compile-circuit-g16 80 | @echo "copying artifacts" 81 | @cp ./artifacts/g16_zkcensus.ccs ./wasm/g16/zkcensus.ccs 82 | @cp ./artifacts/g16_zkcensus.pkey ./wasm/g16/zkcensus.pkey 83 | @echo "compilling the prover for tinygo" 84 | @make compile-prover-tinygo-g16 85 | @echo "removing copied artifacts" 86 | @rm ./wasm/g16/zkcensus.ccs 87 | @rm ./wasm/g16/zkcensus.pkey 88 | @rm -f examples/web/index.html 89 | @echo "copying compatible wasm_exec.js" 90 | @cp ./artifacts/wasm_exec_tinygo.js ./examples/web/wasm_exec.js 91 | @ln -s index_g16.html examples/web/index.html 92 | @go run examples/web/main.go 93 | 94 | run-tinygo-web-example-g16-wasi: 95 | @echo "compilling circuit and genering artifacts for groth16" 96 | @make compile-circuit-g16 97 | @echo "copying artifacts" 98 | @cp ./artifacts/g16_zkcensus.ccs ./wasi/zkcensus.ccs 99 | @cp ./artifacts/g16_zkcensus.pkey ./wasi/zkcensus.pkey 100 | @echo "compilling the prover for tinygo and wasi" 101 | @make compile-prover-tinygo-g16-wasi 102 | @cp ./artifacts/zkcensus.witness ./examples/tinygowasi/artifacts/zkcensus.witness 103 | @cp ./artifacts/g16_prover.wasi ./examples/tinygowasi/artifacts/g16_prover.wasm 104 | @echo "removing copied artifacts" 105 | @rm ./wasi/zkcensus.ccs 106 | @rm ./wasi/zkcensus.pkey 107 | @cd ./examples/tinygowasi && npm i && npx parcel index.html 108 | 109 | run-wasi-web-example-plonk: 110 | @echo "compilling circuit and genering artifacts" 111 | @make compile-circuit-g16 112 | @echo "copying artifacts" 113 | @cp ./artifacts/zkcensus.ccs ./wasi/zkcensus.ccs 114 | @cp ./artifacts/zkcensus.srs ./wasi/zkcensus.srs 115 | @cp ./artifacts/zkcensus.pkey ./wasi/zkcensus.pkey 116 | @cp ./artifacts/zkcensus.witness ./examples/tinygowasi/artifacts/zkcensus.witness 117 | @echo "compilling the prover for tinygo (wasi)" 118 | @make compile-prover-tinygo-wasi 119 | @echo "removing copied artifacts" 120 | @rm ./wasi/zkcensus.ccs 121 | @rm ./wasi/zkcensus.srs 122 | @rm ./wasi/zkcensus.pkey 123 | @cd ./examples/tinygowasi && npm i && npx parcel index.html 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gnark prover using TinyGo 2 | 3 | > ⚠️🚧 This repository is currently a **proof of concept**. 🚧⚠️ 4 | 5 | This is an attempt to create an experimental zksnark prover/verifier for gnark circuits, compatible with [TinyGo](https://github.com/tinygo-org/tinygo), which means that it could be used on a bunch variety of targets (e.g. browsers). 6 | 7 | It implements the same use case as [this circuit](https://github.com/vocdoni/zk-franchise-proof-circuit), and it attempts to replace the [Circom](https://github.com/iden3/circom) + [SnarkJS](https://github.com/iden3/snarkjs) stack. 8 | 9 | ## Motivations 10 | - 🚀 [Gnark](https://github.com/ConsenSys/gnark) is very fast. 11 | - 💉 Supports unit testing and many modern backends and curves. 12 | - 🔗 [vocdoni-node](https://github.com/vocdoni/vocdoni-node) is currently writed enterily in Go, like Gnark, which will increase the maintainability of the source code. 13 | 14 | **Read** about the comprehensive insights, decisions made, benchmarks and conclusions drawn in our article here https://hackmd.io/@vocdoni/B1VPA99Z3 15 | 16 | 17 | ## Project structure 18 | ``` 19 | artifacts/ -> Includes generated artifacts for the implemented and compiled circuits. 20 | circuits/ -> Includes the available circuits definitions. 21 | zkcensus/ -> Port to gnark of https://github.com/vocdoni/zk-franchise-proof-circuit/blob/master/circuit/census.circom 22 | cmd/ 23 | compiler/ -> Simple command to compile available circuits. 24 | prover/ -> Simple command to test the prover with go. 25 | examples/ -> Example of proof generation in js using gnark into a go-wasm. 26 | internal/ 27 | zkaddress/ -> Alternative implementation of current vocdoni zkaddress (https://github.com/vocdoni/vocdoni-node/blob/master/crypto/zk/address.go) 28 | std/ -> Extended gnark std version with required ports. 29 | hash/poseidon/ -> Port to gnark of https://github.com/iden3/circomlib/blob/master/circuits/poseidon.circom 30 | smt/ -> Port to gnark of https://github.com/iden3/circomlib/blob/master/circuits/smt/smtverifier.circom 31 | zkaddress/ -> Implementation of the zkaddress using gnark 32 | wasm/ -> Wasm entrypoint and compiled version. 33 | ``` 34 | 35 | ## Tests decription and results 36 | 37 | ### Followed stepts 38 | 39 | 1. Ports from Gnark of required Circom circuits: 40 | - `Poseidon hash`: [Gnark](./std/hash/poseidon/poseidon.go) | [Circom](https://github.com/iden3/circomlib/blob/db0202410771a3e3fc07c64c5226b64f954b8b5a/circuits/poseidon.circom). 41 | - `SMTVerifier`: [Gnark](./std/smt/verifier.go) | [Circom](https://github.com/iden3/circomlib/blob/a8cdb6cd1ad652cca1a409da053ec98f19de6c9d/circuits/smt/smtverifier.circom). 42 | 2. `ZkCensus` Vocdoni circuit port to Gnark: [Gnark](./circuits/zkcensus/zkcensus.go) | [Circom](https://github.com/vocdoni/zk-franchise-proof-circuit/blob/c2ead7f8502cf0dd7495140aec32599fd0a53199/circuit/census.circom). 43 | 4. `ZkCensus` (Gnark version) compiler and artifacts enconder command implementation. 44 | - Some blocks found and solved [1](#problems-found). 45 | 3. Generic Gnark prover/verifier implementation. 46 | - Go WASM compiler as baseline. Found some incompatibilities with TinyGo[2](#problems-found). 47 | 48 | ### Requirements 49 | * Go (1.20.2) 50 | * TinyGo ([@vocdoni](https://github.com/vocdoni) fork): [vocdoni/tinygo](https://github.com/vocdoni/tinygo) 51 | 52 | 53 | ### Circuit 54 | The ZkCensus circuit anonymously proves that a voter is part of a census for a given election, without revealing its identity. 55 | 56 | The ZkCensus circuit proves the following assertions: 57 | 1. The combination of the computed ZkAddress (using the given PrivateKey as seed) and the provided factoryWeight is a valid census tree leaf. This is tested computing the merkle root with the candidate leaf and the provided siblings, and comparing the result with the provided census root. 58 | 2. The provided nullifier is valid. This is tested computing the nullifier with the electionID and the privateKey, and comparing the result with the provided nullifier. 59 | 3. The votingWeight is equal to or less than the factoryWeight. 60 | 61 | Term descriptions: 62 | * *ZkAddress*: the address of an anonymous voter in the Vochain, it is optimised for zk-snarks and helps to reduce the number of levels of the census merkle tree. It is based on the BN254 elliptic curve and it uses the voter private key as seed. Read more [here](https://github.com/vocdoni/vocdoni-node/blob/ca09fde59cef93f6b1de90c0c918adbff814e87e/crypto/zk/address.go). 63 | * *Nullifier*: the result of applying the Poseidon hash to the combination of the election ID and the voter private key. 64 | 65 | #### Schema 66 | ``` 67 | +----+ 68 | PUB_votingWeight+------>+ <= +------------------+--PRI_factoryWeight 69 | +----+ | 70 | | 71 | +-----------+ | 72 | | | | 73 | PUB_censusRoot+-------->+ |(value)<---+ 74 | | | 75 | | SMT | +-----------+ +-----------+ 76 | | Verifier | | | | | 77 | PRI_siblings+---------->+ |(key)<-----+ ZkAddress +<--+ pubKey +---+-+PRI_privateKey 78 | | | | | | | | 79 | +-----------+ +-----------+ +-----------+ | 80 | | 81 | +-----------+ | 82 | +----+ | +<------------------------------+ 83 | PUB_nullifier+--------->+ == +<-----+ Poseidon |<------------+PUB_processID_0 84 | +----+ | +<------------+PUB_processID_1 85 | +-----------+ 86 | PUB_voteHash 87 | ``` 88 | 89 | #### Inputs 90 | | Name | Private/Public | Description | 91 | |:---:|:---:|:---| 92 | | *votingHeight* | 🔐 `private` | The weight used to perform a vote. It must be equal to or lower than `factoryWeight`. | 93 | | *factoryHeight* | 📢 `public` | The weight assigned to the voter as Merkle Tree leaf value. | 94 | | *privateKey* | 🔐 `private` | The voter private key. Seed of the ZkAddress. | 95 | | *censusRoot* | 📢 `public` | The Merkle Root of the current census tree. | 96 | | *siblings* | 🔐 `private` | Siblings of the voter ZkAddress leaf in the census tree. | 97 | | *nullifier* | 📢 `public` | Parameter that combines the *privateKey* with the *electionId* to avoid proof reusability. | 98 | | *electionId* | 📢 `public` | Encoded ID of the election. | 99 | | *voteHash* | 📢 `public` | Parameter that combines the *privateKey* with the *factoryWeight* to be include it into the proof witness. | 100 | 101 | ### Available commands 102 | * **Compile circuit, prover and run a web example** 103 | ```sh 104 | make run-tinygo-web-example-g16 105 | ``` 106 | or for Plonk 107 | ```sh 108 | make run-tinygo-web-example-plonk 109 | ``` 110 | 111 | #### Other commands 112 | See Makefile -------------------------------------------------------------------------------- /artifacts/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vocdoni/gnark-prover-tinygo/a826b77b783c2b3d909bca4e45ebccf673628779/artifacts/.gitkeep -------------------------------------------------------------------------------- /artifacts/artifacts_test.go: -------------------------------------------------------------------------------- 1 | package artifacts 2 | 3 | import ( 4 | "bytes" 5 | "os" 6 | "testing" 7 | 8 | "gnark-prover-tinygo/prover" 9 | 10 | "github.com/consensys/gnark-crypto/ecc" 11 | "github.com/consensys/gnark-crypto/kzg" 12 | "github.com/consensys/gnark/backend/plonk" 13 | "github.com/consensys/gnark/backend/witness" 14 | qt "github.com/frankban/quicktest" 15 | ) 16 | 17 | func TestArtifacts(t *testing.T) { 18 | c := qt.New(t) 19 | // load ccs, srs, pkey, vkey and witness artifacts 20 | bccs, err := os.ReadFile("./zkcensus.ccs") 21 | c.Assert(err, qt.IsNil) 22 | // dismiss error opening srs (not required with groth16) 23 | bsrs, _ := os.ReadFile("./zkcensus.srs") 24 | bpkey, err := os.ReadFile("./zkcensus.pkey") 25 | c.Assert(err, qt.IsNil) 26 | bvkey, err := os.ReadFile("./zkcensus.vkey") 27 | c.Assert(err, qt.IsNil) 28 | bwitness, err := os.ReadFile("./zkcensus.witness") 29 | c.Assert(err, qt.IsNil) 30 | // generate proof with plonk and verify it 31 | bproof, bpubwitness, err := prover.GenerateProof(bccs, bsrs, bpkey, bwitness) 32 | c.Assert(err, qt.IsNil) 33 | // parse the verifiying key 34 | verifiyingKey := plonk.NewVerifyingKey(ecc.BN254) 35 | _, err = verifiyingKey.ReadFrom(bytes.NewBuffer(bvkey)) 36 | c.Assert(err, qt.IsNil) 37 | // Read and initialize SSR 38 | srs := kzg.NewSRS(ecc.BN254) 39 | _, err = srs.ReadFrom(bytes.NewReader(bsrs)) 40 | c.Assert(err, qt.IsNil) 41 | err = verifiyingKey.InitKZG(srs) 42 | c.Assert(err, qt.IsNil) 43 | // parse the proof 44 | proof := plonk.NewProof(ecc.BN254) 45 | _, err = proof.ReadFrom(bytes.NewBuffer(bproof)) 46 | c.Assert(err, qt.IsNil) 47 | // parse the public witness 48 | pubWitness, err := witness.New(ecc.BN254.ScalarField()) 49 | c.Assert(err, qt.IsNil) 50 | _, err = pubWitness.ReadFrom(bytes.NewReader(bpubwitness)) 51 | c.Assert(err, qt.IsNil) 52 | // assert the result of the verification process 53 | err = plonk.Verify(proof, verifiyingKey, pubWitness) 54 | c.Assert(err, qt.IsNil) 55 | } 56 | -------------------------------------------------------------------------------- /artifacts/wasm_exec_go.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | "use strict"; 6 | 7 | (() => { 8 | const enosys = () => { 9 | const err = new Error("not implemented"); 10 | err.code = "ENOSYS"; 11 | return err; 12 | }; 13 | 14 | if (!globalThis.fs) { 15 | let outputBuf = ""; 16 | globalThis.fs = { 17 | constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused 18 | writeSync(fd, buf) { 19 | outputBuf += decoder.decode(buf); 20 | const nl = outputBuf.lastIndexOf("\n"); 21 | if (nl != -1) { 22 | console.log(outputBuf.substring(0, nl)); 23 | outputBuf = outputBuf.substring(nl + 1); 24 | } 25 | return buf.length; 26 | }, 27 | write(fd, buf, offset, length, position, callback) { 28 | if (offset !== 0 || length !== buf.length || position !== null) { 29 | callback(enosys()); 30 | return; 31 | } 32 | const n = this.writeSync(fd, buf); 33 | callback(null, n); 34 | }, 35 | chmod(path, mode, callback) { callback(enosys()); }, 36 | chown(path, uid, gid, callback) { callback(enosys()); }, 37 | close(fd, callback) { callback(enosys()); }, 38 | fchmod(fd, mode, callback) { callback(enosys()); }, 39 | fchown(fd, uid, gid, callback) { callback(enosys()); }, 40 | fstat(fd, callback) { callback(enosys()); }, 41 | fsync(fd, callback) { callback(null); }, 42 | ftruncate(fd, length, callback) { callback(enosys()); }, 43 | lchown(path, uid, gid, callback) { callback(enosys()); }, 44 | link(path, link, callback) { callback(enosys()); }, 45 | lstat(path, callback) { callback(enosys()); }, 46 | mkdir(path, perm, callback) { callback(enosys()); }, 47 | open(path, flags, mode, callback) { callback(enosys()); }, 48 | read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, 49 | readdir(path, callback) { callback(enosys()); }, 50 | readlink(path, callback) { callback(enosys()); }, 51 | rename(from, to, callback) { callback(enosys()); }, 52 | rmdir(path, callback) { callback(enosys()); }, 53 | stat(path, callback) { callback(enosys()); }, 54 | symlink(path, link, callback) { callback(enosys()); }, 55 | truncate(path, length, callback) { callback(enosys()); }, 56 | unlink(path, callback) { callback(enosys()); }, 57 | utimes(path, atime, mtime, callback) { callback(enosys()); }, 58 | }; 59 | } 60 | 61 | if (!globalThis.process) { 62 | globalThis.process = { 63 | getuid() { return -1; }, 64 | getgid() { return -1; }, 65 | geteuid() { return -1; }, 66 | getegid() { return -1; }, 67 | getgroups() { throw enosys(); }, 68 | pid: -1, 69 | ppid: -1, 70 | umask() { throw enosys(); }, 71 | cwd() { throw enosys(); }, 72 | chdir() { throw enosys(); }, 73 | } 74 | } 75 | 76 | if (!globalThis.crypto) { 77 | throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); 78 | } 79 | 80 | if (!globalThis.performance) { 81 | throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); 82 | } 83 | 84 | if (!globalThis.TextEncoder) { 85 | throw new Error("globalThis.TextEncoder is not available, polyfill required"); 86 | } 87 | 88 | if (!globalThis.TextDecoder) { 89 | throw new Error("globalThis.TextDecoder is not available, polyfill required"); 90 | } 91 | 92 | const encoder = new TextEncoder("utf-8"); 93 | const decoder = new TextDecoder("utf-8"); 94 | 95 | globalThis.Go = class { 96 | constructor() { 97 | this.argv = ["js"]; 98 | this.env = {}; 99 | this.exit = (code) => { 100 | if (code !== 0) { 101 | console.warn("exit code:", code); 102 | } 103 | }; 104 | this._exitPromise = new Promise((resolve) => { 105 | this._resolveExitPromise = resolve; 106 | }); 107 | this._pendingEvent = null; 108 | this._scheduledTimeouts = new Map(); 109 | this._nextCallbackTimeoutID = 1; 110 | 111 | const setInt64 = (addr, v) => { 112 | this.mem.setUint32(addr + 0, v, true); 113 | this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); 114 | } 115 | 116 | const getInt64 = (addr) => { 117 | const low = this.mem.getUint32(addr + 0, true); 118 | const high = this.mem.getInt32(addr + 4, true); 119 | return low + high * 4294967296; 120 | } 121 | 122 | const loadValue = (addr) => { 123 | const f = this.mem.getFloat64(addr, true); 124 | if (f === 0) { 125 | return undefined; 126 | } 127 | if (!isNaN(f)) { 128 | return f; 129 | } 130 | 131 | const id = this.mem.getUint32(addr, true); 132 | return this._values[id]; 133 | } 134 | 135 | const storeValue = (addr, v) => { 136 | const nanHead = 0x7FF80000; 137 | 138 | if (typeof v === "number" && v !== 0) { 139 | if (isNaN(v)) { 140 | this.mem.setUint32(addr + 4, nanHead, true); 141 | this.mem.setUint32(addr, 0, true); 142 | return; 143 | } 144 | this.mem.setFloat64(addr, v, true); 145 | return; 146 | } 147 | 148 | if (v === undefined) { 149 | this.mem.setFloat64(addr, 0, true); 150 | return; 151 | } 152 | 153 | let id = this._ids.get(v); 154 | if (id === undefined) { 155 | id = this._idPool.pop(); 156 | if (id === undefined) { 157 | id = this._values.length; 158 | } 159 | this._values[id] = v; 160 | this._goRefCounts[id] = 0; 161 | this._ids.set(v, id); 162 | } 163 | this._goRefCounts[id]++; 164 | let typeFlag = 0; 165 | switch (typeof v) { 166 | case "object": 167 | if (v !== null) { 168 | typeFlag = 1; 169 | } 170 | break; 171 | case "string": 172 | typeFlag = 2; 173 | break; 174 | case "symbol": 175 | typeFlag = 3; 176 | break; 177 | case "function": 178 | typeFlag = 4; 179 | break; 180 | } 181 | this.mem.setUint32(addr + 4, nanHead | typeFlag, true); 182 | this.mem.setUint32(addr, id, true); 183 | } 184 | 185 | const loadSlice = (addr) => { 186 | const array = getInt64(addr + 0); 187 | const len = getInt64(addr + 8); 188 | return new Uint8Array(this._inst.exports.mem.buffer, array, len); 189 | } 190 | 191 | const loadSliceOfValues = (addr) => { 192 | const array = getInt64(addr + 0); 193 | const len = getInt64(addr + 8); 194 | const a = new Array(len); 195 | for (let i = 0; i < len; i++) { 196 | a[i] = loadValue(array + i * 8); 197 | } 198 | return a; 199 | } 200 | 201 | const loadString = (addr) => { 202 | const saddr = getInt64(addr + 0); 203 | const len = getInt64(addr + 8); 204 | return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); 205 | } 206 | 207 | const timeOrigin = Date.now() - performance.now(); 208 | this.importObject = { 209 | go: { 210 | // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) 211 | // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported 212 | // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). 213 | // This changes the SP, thus we have to update the SP used by the imported function. 214 | 215 | // func wasmExit(code int32) 216 | "runtime.wasmExit": (sp) => { 217 | sp >>>= 0; 218 | const code = this.mem.getInt32(sp + 8, true); 219 | this.exited = true; 220 | delete this._inst; 221 | delete this._values; 222 | delete this._goRefCounts; 223 | delete this._ids; 224 | delete this._idPool; 225 | this.exit(code); 226 | }, 227 | 228 | // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) 229 | "runtime.wasmWrite": (sp) => { 230 | sp >>>= 0; 231 | const fd = getInt64(sp + 8); 232 | const p = getInt64(sp + 16); 233 | const n = this.mem.getInt32(sp + 24, true); 234 | fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); 235 | }, 236 | 237 | // func resetMemoryDataView() 238 | "runtime.resetMemoryDataView": (sp) => { 239 | sp >>>= 0; 240 | this.mem = new DataView(this._inst.exports.mem.buffer); 241 | }, 242 | 243 | // func nanotime1() int64 244 | "runtime.nanotime1": (sp) => { 245 | sp >>>= 0; 246 | setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); 247 | }, 248 | 249 | // func walltime() (sec int64, nsec int32) 250 | "runtime.walltime": (sp) => { 251 | sp >>>= 0; 252 | const msec = (new Date).getTime(); 253 | setInt64(sp + 8, msec / 1000); 254 | this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); 255 | }, 256 | 257 | // func scheduleTimeoutEvent(delay int64) int32 258 | "runtime.scheduleTimeoutEvent": (sp) => { 259 | sp >>>= 0; 260 | const id = this._nextCallbackTimeoutID; 261 | this._nextCallbackTimeoutID++; 262 | this._scheduledTimeouts.set(id, setTimeout( 263 | () => { 264 | this._resume(); 265 | while (this._scheduledTimeouts.has(id)) { 266 | // for some reason Go failed to register the timeout event, log and try again 267 | // (temporary workaround for https://github.com/golang/go/issues/28975) 268 | console.warn("scheduleTimeoutEvent: missed timeout event"); 269 | } 270 | }, 271 | getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early 272 | )); 273 | this.mem.setInt32(sp + 16, id, true); 274 | }, 275 | 276 | // func clearTimeoutEvent(id int32) 277 | "runtime.clearTimeoutEvent": (sp) => { 278 | sp >>>= 0; 279 | const id = this.mem.getInt32(sp + 8, true); 280 | clearTimeout(this._scheduledTimeouts.get(id)); 281 | this._scheduledTimeouts.delete(id); 282 | }, 283 | 284 | // func getRandomData(r []byte) 285 | "runtime.getRandomData": (sp) => { 286 | sp >>>= 0; 287 | crypto.getRandomValues(loadSlice(sp + 8)); 288 | }, 289 | 290 | // func finalizeRef(v ref) 291 | "syscall/js.finalizeRef": (sp) => { 292 | sp >>>= 0; 293 | const id = this.mem.getUint32(sp + 8, true); 294 | this._goRefCounts[id]--; 295 | if (this._goRefCounts[id] === 0) { 296 | const v = this._values[id]; 297 | this._values[id] = null; 298 | this._ids.delete(v); 299 | this._idPool.push(id); 300 | } 301 | }, 302 | 303 | // func stringVal(value string) ref 304 | "syscall/js.stringVal": (sp) => { 305 | sp >>>= 0; 306 | storeValue(sp + 24, loadString(sp + 8)); 307 | }, 308 | 309 | // func valueGet(v ref, p string) ref 310 | "syscall/js.valueGet": (sp) => { 311 | sp >>>= 0; 312 | const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); 313 | sp = this._inst.exports.getsp() >>> 0; // see comment above 314 | storeValue(sp + 32, result); 315 | }, 316 | 317 | // func valueSet(v ref, p string, x ref) 318 | "syscall/js.valueSet": (sp) => { 319 | sp >>>= 0; 320 | Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); 321 | }, 322 | 323 | // func valueDelete(v ref, p string) 324 | "syscall/js.valueDelete": (sp) => { 325 | sp >>>= 0; 326 | Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); 327 | }, 328 | 329 | // func valueIndex(v ref, i int) ref 330 | "syscall/js.valueIndex": (sp) => { 331 | sp >>>= 0; 332 | storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); 333 | }, 334 | 335 | // valueSetIndex(v ref, i int, x ref) 336 | "syscall/js.valueSetIndex": (sp) => { 337 | sp >>>= 0; 338 | Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); 339 | }, 340 | 341 | // func valueCall(v ref, m string, args []ref) (ref, bool) 342 | "syscall/js.valueCall": (sp) => { 343 | sp >>>= 0; 344 | try { 345 | const v = loadValue(sp + 8); 346 | const m = Reflect.get(v, loadString(sp + 16)); 347 | const args = loadSliceOfValues(sp + 32); 348 | const result = Reflect.apply(m, v, args); 349 | sp = this._inst.exports.getsp() >>> 0; // see comment above 350 | storeValue(sp + 56, result); 351 | this.mem.setUint8(sp + 64, 1); 352 | } catch (err) { 353 | sp = this._inst.exports.getsp() >>> 0; // see comment above 354 | storeValue(sp + 56, err); 355 | this.mem.setUint8(sp + 64, 0); 356 | } 357 | }, 358 | 359 | // func valueInvoke(v ref, args []ref) (ref, bool) 360 | "syscall/js.valueInvoke": (sp) => { 361 | sp >>>= 0; 362 | try { 363 | const v = loadValue(sp + 8); 364 | const args = loadSliceOfValues(sp + 16); 365 | const result = Reflect.apply(v, undefined, args); 366 | sp = this._inst.exports.getsp() >>> 0; // see comment above 367 | storeValue(sp + 40, result); 368 | this.mem.setUint8(sp + 48, 1); 369 | } catch (err) { 370 | sp = this._inst.exports.getsp() >>> 0; // see comment above 371 | storeValue(sp + 40, err); 372 | this.mem.setUint8(sp + 48, 0); 373 | } 374 | }, 375 | 376 | // func valueNew(v ref, args []ref) (ref, bool) 377 | "syscall/js.valueNew": (sp) => { 378 | sp >>>= 0; 379 | try { 380 | const v = loadValue(sp + 8); 381 | const args = loadSliceOfValues(sp + 16); 382 | const result = Reflect.construct(v, args); 383 | sp = this._inst.exports.getsp() >>> 0; // see comment above 384 | storeValue(sp + 40, result); 385 | this.mem.setUint8(sp + 48, 1); 386 | } catch (err) { 387 | sp = this._inst.exports.getsp() >>> 0; // see comment above 388 | storeValue(sp + 40, err); 389 | this.mem.setUint8(sp + 48, 0); 390 | } 391 | }, 392 | 393 | // func valueLength(v ref) int 394 | "syscall/js.valueLength": (sp) => { 395 | sp >>>= 0; 396 | setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); 397 | }, 398 | 399 | // valuePrepareString(v ref) (ref, int) 400 | "syscall/js.valuePrepareString": (sp) => { 401 | sp >>>= 0; 402 | const str = encoder.encode(String(loadValue(sp + 8))); 403 | storeValue(sp + 16, str); 404 | setInt64(sp + 24, str.length); 405 | }, 406 | 407 | // valueLoadString(v ref, b []byte) 408 | "syscall/js.valueLoadString": (sp) => { 409 | sp >>>= 0; 410 | const str = loadValue(sp + 8); 411 | loadSlice(sp + 16).set(str); 412 | }, 413 | 414 | // func valueInstanceOf(v ref, t ref) bool 415 | "syscall/js.valueInstanceOf": (sp) => { 416 | sp >>>= 0; 417 | this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); 418 | }, 419 | 420 | // func copyBytesToGo(dst []byte, src ref) (int, bool) 421 | "syscall/js.copyBytesToGo": (sp) => { 422 | sp >>>= 0; 423 | const dst = loadSlice(sp + 8); 424 | const src = loadValue(sp + 32); 425 | if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { 426 | this.mem.setUint8(sp + 48, 0); 427 | return; 428 | } 429 | const toCopy = src.subarray(0, dst.length); 430 | dst.set(toCopy); 431 | setInt64(sp + 40, toCopy.length); 432 | this.mem.setUint8(sp + 48, 1); 433 | }, 434 | 435 | // func copyBytesToJS(dst ref, src []byte) (int, bool) 436 | "syscall/js.copyBytesToJS": (sp) => { 437 | sp >>>= 0; 438 | const dst = loadValue(sp + 8); 439 | const src = loadSlice(sp + 16); 440 | if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { 441 | this.mem.setUint8(sp + 48, 0); 442 | return; 443 | } 444 | const toCopy = src.subarray(0, dst.length); 445 | dst.set(toCopy); 446 | setInt64(sp + 40, toCopy.length); 447 | this.mem.setUint8(sp + 48, 1); 448 | }, 449 | 450 | "debug": (value) => { 451 | console.log(value); 452 | print.log(value) 453 | }, 454 | } 455 | }; 456 | } 457 | 458 | async run(instance) { 459 | if (!(instance instanceof WebAssembly.Instance)) { 460 | throw new Error("Go.run: WebAssembly.Instance expected"); 461 | } 462 | this._inst = instance; 463 | this.mem = new DataView(this._inst.exports.mem.buffer); 464 | this._values = [ // JS values that Go currently has references to, indexed by reference id 465 | NaN, 466 | 0, 467 | null, 468 | true, 469 | false, 470 | globalThis, 471 | this, 472 | ]; 473 | this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id 474 | this._ids = new Map([ // mapping from JS values to reference ids 475 | [0, 1], 476 | [null, 2], 477 | [true, 3], 478 | [false, 4], 479 | [globalThis, 5], 480 | [this, 6], 481 | ]); 482 | this._idPool = []; // unused ids that have been garbage collected 483 | this.exited = false; // whether the Go program has exited 484 | 485 | // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. 486 | let offset = 4096; 487 | 488 | const strPtr = (str) => { 489 | const ptr = offset; 490 | const bytes = encoder.encode(str + "\0"); 491 | new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); 492 | offset += bytes.length; 493 | if (offset % 8 !== 0) { 494 | offset += 8 - (offset % 8); 495 | } 496 | return ptr; 497 | }; 498 | 499 | const argc = this.argv.length; 500 | 501 | const argvPtrs = []; 502 | this.argv.forEach((arg) => { 503 | argvPtrs.push(strPtr(arg)); 504 | }); 505 | argvPtrs.push(0); 506 | 507 | const keys = Object.keys(this.env).sort(); 508 | keys.forEach((key) => { 509 | argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); 510 | }); 511 | argvPtrs.push(0); 512 | 513 | const argv = offset; 514 | argvPtrs.forEach((ptr) => { 515 | this.mem.setUint32(offset, ptr, true); 516 | this.mem.setUint32(offset + 4, 0, true); 517 | offset += 8; 518 | }); 519 | 520 | // The linker guarantees global data starts from at least wasmMinDataAddr. 521 | // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. 522 | const wasmMinDataAddr = 4096 + 8192; 523 | if (offset >= wasmMinDataAddr) { 524 | throw new Error("total length of command line and environment variables exceeds limit"); 525 | } 526 | 527 | this._inst.exports.run(argc, argv); 528 | if (this.exited) { 529 | this._resolveExitPromise(); 530 | } 531 | await this._exitPromise; 532 | } 533 | 534 | _resume() { 535 | if (this.exited) { 536 | throw new Error("Go program has already exited"); 537 | } 538 | this._inst.exports.resume(); 539 | if (this.exited) { 540 | this._resolveExitPromise(); 541 | } 542 | } 543 | 544 | _makeFuncWrapper(id) { 545 | const go = this; 546 | return function() { 547 | const event = { id: id, this: this, args: arguments }; 548 | go._pendingEvent = event; 549 | go._resume(); 550 | return event.result; 551 | }; 552 | } 553 | } 554 | })(); -------------------------------------------------------------------------------- /artifacts/wasm_exec_tinygo.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | // 5 | // This file has been modified for use by the TinyGo compiler. 6 | 7 | (() => { 8 | // Map multiple JavaScript environments to a single common API, 9 | // preferring web standards over Node.js API. 10 | // 11 | // Environments considered: 12 | // - Browsers 13 | // - Node.js 14 | // - Electron 15 | // - Parcel 16 | 17 | if (typeof global !== "undefined") { 18 | // global already exists 19 | } else if (typeof window !== "undefined") { 20 | window.global = window; 21 | } else if (typeof self !== "undefined") { 22 | self.global = self; 23 | } else { 24 | throw new Error("cannot export Go (neither global, window nor self is defined)"); 25 | } 26 | 27 | if (!global.require && typeof require !== "undefined") { 28 | global.require = require; 29 | } 30 | 31 | if (!global.fs && global.require) { 32 | global.fs = require("fs"); 33 | } 34 | 35 | const enosys = () => { 36 | const err = new Error("not implemented"); 37 | err.code = "ENOSYS"; 38 | return err; 39 | }; 40 | 41 | if (!global.fs) { 42 | let outputBuf = ""; 43 | global.fs = { 44 | constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused 45 | writeSync(fd, buf) { 46 | outputBuf += decoder.decode(buf); 47 | const nl = outputBuf.lastIndexOf("\n"); 48 | if (nl != -1) { 49 | console.log(outputBuf.substr(0, nl)); 50 | outputBuf = outputBuf.substr(nl + 1); 51 | } 52 | return buf.length; 53 | }, 54 | write(fd, buf, offset, length, position, callback) { 55 | if (offset !== 0 || length !== buf.length || position !== null) { 56 | callback(enosys()); 57 | return; 58 | } 59 | const n = this.writeSync(fd, buf); 60 | callback(null, n); 61 | }, 62 | chmod(path, mode, callback) { callback(enosys()); }, 63 | chown(path, uid, gid, callback) { callback(enosys()); }, 64 | close(fd, callback) { callback(enosys()); }, 65 | fchmod(fd, mode, callback) { callback(enosys()); }, 66 | fchown(fd, uid, gid, callback) { callback(enosys()); }, 67 | fstat(fd, callback) { callback(enosys()); }, 68 | fsync(fd, callback) { callback(null); }, 69 | ftruncate(fd, length, callback) { callback(enosys()); }, 70 | lchown(path, uid, gid, callback) { callback(enosys()); }, 71 | link(path, link, callback) { callback(enosys()); }, 72 | lstat(path, callback) { callback(enosys()); }, 73 | mkdir(path, perm, callback) { callback(enosys()); }, 74 | open(path, flags, mode, callback) { callback(enosys()); }, 75 | read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, 76 | readdir(path, callback) { callback(enosys()); }, 77 | readlink(path, callback) { callback(enosys()); }, 78 | rename(from, to, callback) { callback(enosys()); }, 79 | rmdir(path, callback) { callback(enosys()); }, 80 | stat(path, callback) { callback(enosys()); }, 81 | symlink(path, link, callback) { callback(enosys()); }, 82 | truncate(path, length, callback) { callback(enosys()); }, 83 | unlink(path, callback) { callback(enosys()); }, 84 | utimes(path, atime, mtime, callback) { callback(enosys()); }, 85 | }; 86 | } 87 | 88 | if (!global.process) { 89 | global.process = { 90 | getuid() { return -1; }, 91 | getgid() { return -1; }, 92 | geteuid() { return -1; }, 93 | getegid() { return -1; }, 94 | getgroups() { throw enosys(); }, 95 | pid: -1, 96 | ppid: -1, 97 | umask() { throw enosys(); }, 98 | cwd() { throw enosys(); }, 99 | chdir() { throw enosys(); }, 100 | } 101 | } 102 | 103 | if (!global.crypto) { 104 | const nodeCrypto = require("crypto"); 105 | global.crypto = { 106 | getRandomValues(b) { 107 | nodeCrypto.randomFillSync(b); 108 | }, 109 | }; 110 | } 111 | 112 | if (!global.performance) { 113 | global.performance = { 114 | now() { 115 | const [sec, nsec] = process.hrtime(); 116 | return sec * 1000 + nsec / 1000000; 117 | }, 118 | }; 119 | } 120 | 121 | if (!global.TextEncoder) { 122 | global.TextEncoder = require("util").TextEncoder; 123 | } 124 | 125 | if (!global.TextDecoder) { 126 | global.TextDecoder = require("util").TextDecoder; 127 | } 128 | 129 | // End of polyfills for common API. 130 | 131 | const encoder = new TextEncoder("utf-8"); 132 | const decoder = new TextDecoder("utf-8"); 133 | var logLine = []; 134 | 135 | global.Go = class { 136 | constructor() { 137 | this._callbackTimeouts = new Map(); 138 | this._nextCallbackTimeoutID = 1; 139 | 140 | const mem = () => { 141 | // The buffer may change when requesting more memory. 142 | return new DataView(this._inst.exports.memory.buffer); 143 | } 144 | 145 | const setInt64 = (addr, v) => { 146 | mem().setUint32(addr + 0, v, true); 147 | mem().setUint32(addr + 4, Math.floor(v / 4294967296), true); 148 | } 149 | 150 | const getInt64 = (addr) => { 151 | const low = mem().getUint32(addr + 0, true); 152 | const high = mem().getInt32(addr + 4, true); 153 | return low + high * 4294967296; 154 | } 155 | 156 | const loadValue = (addr) => { 157 | const f = mem().getFloat64(addr, true); 158 | if (f === 0) { 159 | return undefined; 160 | } 161 | if (!isNaN(f)) { 162 | return f; 163 | } 164 | 165 | const id = mem().getUint32(addr, true); 166 | return this._values[id]; 167 | } 168 | 169 | const storeValue = (addr, v) => { 170 | const nanHead = 0x7FF80000; 171 | 172 | if (typeof v === "number") { 173 | if (isNaN(v)) { 174 | mem().setUint32(addr + 4, nanHead, true); 175 | mem().setUint32(addr, 0, true); 176 | return; 177 | } 178 | if (v === 0) { 179 | mem().setUint32(addr + 4, nanHead, true); 180 | mem().setUint32(addr, 1, true); 181 | return; 182 | } 183 | mem().setFloat64(addr, v, true); 184 | return; 185 | } 186 | 187 | switch (v) { 188 | case undefined: 189 | mem().setFloat64(addr, 0, true); 190 | return; 191 | case null: 192 | mem().setUint32(addr + 4, nanHead, true); 193 | mem().setUint32(addr, 2, true); 194 | return; 195 | case true: 196 | mem().setUint32(addr + 4, nanHead, true); 197 | mem().setUint32(addr, 3, true); 198 | return; 199 | case false: 200 | mem().setUint32(addr + 4, nanHead, true); 201 | mem().setUint32(addr, 4, true); 202 | return; 203 | } 204 | 205 | let id = this._ids.get(v); 206 | if (id === undefined) { 207 | id = this._idPool.pop(); 208 | if (id === undefined) { 209 | id = this._values.length; 210 | } 211 | this._values[id] = v; 212 | this._goRefCounts[id] = 0; 213 | this._ids.set(v, id); 214 | } 215 | this._goRefCounts[id]++; 216 | let typeFlag = 1; 217 | switch (typeof v) { 218 | case "string": 219 | typeFlag = 2; 220 | break; 221 | case "symbol": 222 | typeFlag = 3; 223 | break; 224 | case "function": 225 | typeFlag = 4; 226 | break; 227 | } 228 | mem().setUint32(addr + 4, nanHead | typeFlag, true); 229 | mem().setUint32(addr, id, true); 230 | } 231 | 232 | const loadSlice = (array, len, cap) => { 233 | return new Uint8Array(this._inst.exports.memory.buffer, array, len); 234 | } 235 | 236 | const loadSliceOfValues = (array, len, cap) => { 237 | const a = new Array(len); 238 | for (let i = 0; i < len; i++) { 239 | a[i] = loadValue(array + i * 8); 240 | } 241 | return a; 242 | } 243 | 244 | const loadString = (ptr, len) => { 245 | return decoder.decode(new DataView(this._inst.exports.memory.buffer, ptr, len)); 246 | } 247 | 248 | const timeOrigin = Date.now() - performance.now(); 249 | this.importObject = { 250 | wasi_snapshot_preview1: { 251 | // https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_write 252 | fd_write: function(fd, iovs_ptr, iovs_len, nwritten_ptr) { 253 | let nwritten = 0; 254 | if (fd == 1) { 255 | for (let iovs_i=0; iovs_i 0, // dummy 281 | fd_fdstat_get: () => 0, // dummy 282 | fd_seek: () => 0, // dummy 283 | "proc_exit": (code) => { 284 | if (global.process) { 285 | // Node.js 286 | process.exit(code); 287 | } else { 288 | // Can't exit in a browser. 289 | throw 'trying to exit with code ' + code; 290 | } 291 | }, 292 | random_get: (bufPtr, bufLen) => { 293 | crypto.getRandomValues(loadSlice(bufPtr, bufLen)); 294 | return 0; 295 | }, 296 | }, 297 | env: { 298 | // func ticks() float64 299 | "runtime.ticks": () => { 300 | return timeOrigin + performance.now(); 301 | }, 302 | 303 | // func sleepTicks(timeout float64) 304 | "runtime.sleepTicks": (timeout) => { 305 | // Do not sleep, only reactivate scheduler after the given timeout. 306 | setTimeout(this._inst.exports.go_scheduler, timeout); 307 | }, 308 | 309 | // func finalizeRef(v ref) 310 | "syscall/js.finalizeRef": (sp) => { 311 | // Note: TinyGo does not support finalizers so this should never be 312 | // called. 313 | console.error('syscall/js.finalizeRef not implemented'); 314 | }, 315 | 316 | // func stringVal(value string) ref 317 | "syscall/js.stringVal": (ret_ptr, value_ptr, value_len) => { 318 | const s = loadString(value_ptr, value_len); 319 | storeValue(ret_ptr, s); 320 | }, 321 | 322 | // func valueGet(v ref, p string) ref 323 | "syscall/js.valueGet": (retval, v_addr, p_ptr, p_len) => { 324 | let prop = loadString(p_ptr, p_len); 325 | let value = loadValue(v_addr); 326 | let result = Reflect.get(value, prop); 327 | storeValue(retval, result); 328 | }, 329 | 330 | // func valueSet(v ref, p string, x ref) 331 | "syscall/js.valueSet": (v_addr, p_ptr, p_len, x_addr) => { 332 | const v = loadValue(v_addr); 333 | const p = loadString(p_ptr, p_len); 334 | const x = loadValue(x_addr); 335 | Reflect.set(v, p, x); 336 | }, 337 | 338 | // func valueDelete(v ref, p string) 339 | "syscall/js.valueDelete": (v_addr, p_ptr, p_len) => { 340 | const v = loadValue(v_addr); 341 | const p = loadString(p_ptr, p_len); 342 | Reflect.deleteProperty(v, p); 343 | }, 344 | 345 | // func valueIndex(v ref, i int) ref 346 | "syscall/js.valueIndex": (ret_addr, v_addr, i) => { 347 | storeValue(ret_addr, Reflect.get(loadValue(v_addr), i)); 348 | }, 349 | 350 | // valueSetIndex(v ref, i int, x ref) 351 | "syscall/js.valueSetIndex": (v_addr, i, x_addr) => { 352 | Reflect.set(loadValue(v_addr), i, loadValue(x_addr)); 353 | }, 354 | 355 | // func valueCall(v ref, m string, args []ref) (ref, bool) 356 | "syscall/js.valueCall": (ret_addr, v_addr, m_ptr, m_len, args_ptr, args_len, args_cap) => { 357 | const v = loadValue(v_addr); 358 | const name = loadString(m_ptr, m_len); 359 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 360 | try { 361 | const m = Reflect.get(v, name); 362 | storeValue(ret_addr, Reflect.apply(m, v, args)); 363 | mem().setUint8(ret_addr + 8, 1); 364 | } catch (err) { 365 | storeValue(ret_addr, err); 366 | mem().setUint8(ret_addr + 8, 0); 367 | } 368 | }, 369 | 370 | // func valueInvoke(v ref, args []ref) (ref, bool) 371 | "syscall/js.valueInvoke": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { 372 | try { 373 | const v = loadValue(v_addr); 374 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 375 | storeValue(ret_addr, Reflect.apply(v, undefined, args)); 376 | mem().setUint8(ret_addr + 8, 1); 377 | } catch (err) { 378 | storeValue(ret_addr, err); 379 | mem().setUint8(ret_addr + 8, 0); 380 | } 381 | }, 382 | 383 | // func valueNew(v ref, args []ref) (ref, bool) 384 | "syscall/js.valueNew": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { 385 | const v = loadValue(v_addr); 386 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 387 | try { 388 | storeValue(ret_addr, Reflect.construct(v, args)); 389 | mem().setUint8(ret_addr + 8, 1); 390 | } catch (err) { 391 | storeValue(ret_addr, err); 392 | mem().setUint8(ret_addr+ 8, 0); 393 | } 394 | }, 395 | 396 | // func valueLength(v ref) int 397 | "syscall/js.valueLength": (v_addr) => { 398 | return loadValue(v_addr).length; 399 | }, 400 | 401 | // valuePrepareString(v ref) (ref, int) 402 | "syscall/js.valuePrepareString": (ret_addr, v_addr) => { 403 | const s = String(loadValue(v_addr)); 404 | const str = encoder.encode(s); 405 | storeValue(ret_addr, str); 406 | setInt64(ret_addr + 8, str.length); 407 | }, 408 | 409 | // valueLoadString(v ref, b []byte) 410 | "syscall/js.valueLoadString": (v_addr, slice_ptr, slice_len, slice_cap) => { 411 | const str = loadValue(v_addr); 412 | loadSlice(slice_ptr, slice_len, slice_cap).set(str); 413 | }, 414 | 415 | // func valueInstanceOf(v ref, t ref) bool 416 | "syscall/js.valueInstanceOf": (v_addr, t_addr) => { 417 | return loadValue(v_addr) instanceof loadValue(t_addr); 418 | }, 419 | 420 | // func copyBytesToGo(dst []byte, src ref) (int, bool) 421 | "syscall/js.copyBytesToGo": (ret_addr, dest_addr, dest_len, dest_cap, source_addr) => { 422 | let num_bytes_copied_addr = ret_addr; 423 | let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable 424 | 425 | const dst = loadSlice(dest_addr, dest_len); 426 | const src = loadValue(source_addr); 427 | if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { 428 | mem().setUint8(returned_status_addr, 0); // Return "not ok" status 429 | return; 430 | } 431 | const toCopy = src.subarray(0, dst.length); 432 | dst.set(toCopy); 433 | setInt64(num_bytes_copied_addr, toCopy.length); 434 | mem().setUint8(returned_status_addr, 1); // Return "ok" status 435 | }, 436 | 437 | // copyBytesToJS(dst ref, src []byte) (int, bool) 438 | // Originally copied from upstream Go project, then modified: 439 | // https://github.com/golang/go/blob/3f995c3f3b43033013013e6c7ccc93a9b1411ca9/misc/wasm/wasm_exec.js#L404-L416 440 | "syscall/js.copyBytesToJS": (ret_addr, dest_addr, source_addr, source_len, source_cap) => { 441 | let num_bytes_copied_addr = ret_addr; 442 | let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable 443 | 444 | const dst = loadValue(dest_addr); 445 | const src = loadSlice(source_addr, source_len); 446 | if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { 447 | mem().setUint8(returned_status_addr, 0); // Return "not ok" status 448 | return; 449 | } 450 | const toCopy = src.subarray(0, dst.length); 451 | dst.set(toCopy); 452 | setInt64(num_bytes_copied_addr, toCopy.length); 453 | mem().setUint8(returned_status_addr, 1); // Return "ok" status 454 | }, 455 | } 456 | }; 457 | } 458 | 459 | async run(instance) { 460 | this._inst = instance; 461 | this._values = [ // JS values that Go currently has references to, indexed by reference id 462 | NaN, 463 | 0, 464 | null, 465 | true, 466 | false, 467 | global, 468 | this, 469 | ]; 470 | this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id 471 | this._ids = new Map(); // mapping from JS values to reference ids 472 | this._idPool = []; // unused ids that have been garbage collected 473 | this.exited = false; // whether the Go program has exited 474 | 475 | const mem = new DataView(this._inst.exports.memory.buffer) 476 | 477 | while (true) { 478 | const callbackPromise = new Promise((resolve) => { 479 | this._resolveCallbackPromise = () => { 480 | if (this.exited) { 481 | throw new Error("bad callback: Go program has already exited"); 482 | } 483 | setTimeout(resolve, 0); // make sure it is asynchronous 484 | }; 485 | }); 486 | this._inst.exports._start(); 487 | if (this.exited) { 488 | break; 489 | } 490 | await callbackPromise; 491 | } 492 | } 493 | 494 | _resume() { 495 | if (this.exited) { 496 | throw new Error("Go program has already exited"); 497 | } 498 | this._inst.exports.resume(); 499 | if (this.exited) { 500 | this._resolveExitPromise(); 501 | } 502 | } 503 | 504 | _makeFuncWrapper(id) { 505 | const go = this; 506 | return function () { 507 | const event = { id: id, this: this, args: arguments }; 508 | go._pendingEvent = event; 509 | go._resume(); 510 | return event.result; 511 | }; 512 | } 513 | } 514 | 515 | if ( 516 | global.require && 517 | global.require.main === module && 518 | global.process && 519 | global.process.versions && 520 | !global.process.versions.electron 521 | ) { 522 | if (process.argv.length != 3) { 523 | console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"); 524 | process.exit(1); 525 | } 526 | 527 | const go = new Go(); 528 | WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => { 529 | return go.run(result.instance); 530 | }).catch((err) => { 531 | console.error(err); 532 | process.exit(1); 533 | }); 534 | } 535 | })(); 536 | -------------------------------------------------------------------------------- /circuits/zkcensus/zkcensus.go: -------------------------------------------------------------------------------- 1 | /* 2 | ZkCensus is the Vocdoni ZKSnark circuit to proof that a given voter is part of a 3 | created election census (in a Arbo Merkle Tree). The circuit checks: 4 | 5 | -the prover is the owner of the private key 6 | -keyHash (hash of the user's public key) belongs to the census 7 | -the public key is generated based on the provided private key 8 | -the public key is inside a hash, which is inside the Merkletree with 9 | the CensusRoot and siblings (key=keyHash, value=factoryWeight) 10 | -H(private key, processID) == nullifier 11 | -to avoid proof reusability 12 | -factoryWeight is the weight assigned by default to the owner of the private 13 | key andincluded as merkle tree leaf value. 14 | -votingWeight is the weight desired to vote by the owner of the private key 15 | and must be less than or equal to the factoryWeightht. 16 | */ 17 | package zkcensus 18 | 19 | import ( 20 | "gnark-prover-tinygo/std/hash/poseidon" 21 | "gnark-prover-tinygo/std/smt" 22 | "gnark-prover-tinygo/std/zkaddress" 23 | 24 | "github.com/consensys/gnark/frontend" 25 | ) 26 | 27 | type ZkCensusCircuit struct { 28 | // Public inputs 29 | ElectionId [2]frontend.Variable `gnark:",public"` 30 | CensusRoot frontend.Variable `gnark:",public"` 31 | Nullifier frontend.Variable `gnark:",public"` 32 | FactoryWeight frontend.Variable `gnark:",public"` 33 | VoteHash [2]frontend.Variable `gnark:",public"` 34 | // Private inputs 35 | CensusSiblings [160]frontend.Variable 36 | PrivateKey frontend.Variable 37 | VotingWeight frontend.Variable 38 | } 39 | 40 | func (circuit *ZkCensusCircuit) Define(api frontend.API) error { 41 | // votingWeight represents the weight that the user wants to use to perform 42 | // a vote and must be lower than factoryWeight 43 | api.AssertIsLessOrEqual(circuit.VotingWeight, circuit.FactoryWeight) 44 | // voteHash is not operated inside the circuit, assuming that in 45 | // Circom an input that is not used will be included in the constraints 46 | // system and in the witness 47 | api.AssertIsDifferent(circuit.VoteHash[0], 0) 48 | api.AssertIsDifferent(circuit.VoteHash[1], 0) 49 | // calculate the zkaddress from the private key 50 | zkAddr, err := zkaddress.FromPrivate(api, circuit.PrivateKey) 51 | if err != nil { 52 | return err 53 | } 54 | // check the Merkletree with census root, siblings, zkAddress and factory 55 | // weight 56 | if err := smt.Verifier(api, circuit.CensusRoot, zkAddr.Scalar, circuit.FactoryWeight, circuit.CensusSiblings[:]); err != nil { 57 | return err 58 | } 59 | // check nullifier (electionID + privateKey) 60 | computedNullifier := poseidon.Hash(api, circuit.PrivateKey, circuit.ElectionId[0], circuit.ElectionId[1]) 61 | api.AssertIsEqual(circuit.Nullifier, computedNullifier) 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /circuits/zkcensus/zkcensus_inputs.go: -------------------------------------------------------------------------------- 1 | package zkcensus 2 | 3 | import ( 4 | "crypto/sha256" 5 | "fmt" 6 | "gnark-prover-tinygo/internal/zkaddress" 7 | "math/big" 8 | "os" 9 | "strings" 10 | 11 | "github.com/consensys/gnark/frontend" 12 | "github.com/iden3/go-iden3-crypto/poseidon" 13 | "go.vocdoni.io/dvote/db" 14 | "go.vocdoni.io/dvote/db/pebbledb" 15 | "go.vocdoni.io/dvote/tree/arbo" 16 | "go.vocdoni.io/dvote/util" 17 | ) 18 | 19 | func BytesToArbo(input []byte) [2]*big.Int { 20 | hash := sha256.Sum256(input) 21 | return [2]*big.Int{ 22 | new(big.Int).SetBytes(arbo.SwapEndianness(hash[:16])), 23 | new(big.Int).SetBytes(arbo.SwapEndianness(hash[16:])), 24 | } 25 | } 26 | 27 | func ZkCensusInputs(nLevels, nKeys int) (ZkCensusCircuit, error) { 28 | dbTemp, err := os.MkdirTemp("", "db") 29 | if err != nil { 30 | return ZkCensusCircuit{}, err 31 | } 32 | database, err := pebbledb.New(db.Options{Path: dbTemp}) 33 | if err != nil { 34 | return ZkCensusCircuit{}, err 35 | } 36 | 37 | arboTree, err := arbo.NewTree(arbo.Config{ 38 | Database: database, 39 | MaxLevels: nLevels, 40 | HashFunction: arbo.HashFunctionPoseidon, 41 | }) 42 | if err != nil { 43 | return ZkCensusCircuit{}, err 44 | } 45 | 46 | factoryWeight := big.NewInt(10) 47 | encFactoryWeight := arbo.BigIntToBytes(arbo.HashFunctionPoseidon.Len(), factoryWeight) 48 | candidate, err := zkaddress.FromBytes([]byte("1b505cdafb4b1150b1a740633af41e5e1f19a5c4")) 49 | if err != nil { 50 | return ZkCensusCircuit{}, err 51 | } 52 | 53 | err = arboTree.Add(candidate.ArboBytes(), encFactoryWeight) 54 | if err != nil { 55 | return ZkCensusCircuit{}, err 56 | } 57 | 58 | for i := 1; i < nKeys; i++ { 59 | k, err := zkaddress.FromBytes(util.RandomBytes(32)) 60 | if err != nil { 61 | return ZkCensusCircuit{}, err 62 | } 63 | 64 | err = arboTree.Add(k.ArboBytes(), encFactoryWeight) 65 | if err != nil { 66 | return ZkCensusCircuit{}, err 67 | } 68 | } 69 | 70 | _, _, pSiblings, exist, err := arboTree.GenProof(candidate.ArboBytes()) 71 | if err != nil { 72 | return ZkCensusCircuit{}, err 73 | } else if !exist { 74 | return ZkCensusCircuit{}, fmt.Errorf("key does not exists") 75 | } 76 | 77 | uSiblings, err := arbo.UnpackSiblings(arbo.HashFunctionPoseidon, pSiblings) 78 | if err != nil { 79 | return ZkCensusCircuit{}, err 80 | } 81 | 82 | siblings := [160]frontend.Variable{} 83 | for i := 0; i < 160; i++ { 84 | if i < len(uSiblings) { 85 | siblings[i] = arbo.BytesToBigInt(uSiblings[i]) 86 | } else { 87 | siblings[i] = big.NewInt(0) 88 | } 89 | } 90 | 91 | root, err := arboTree.Root() 92 | if err != nil { 93 | return ZkCensusCircuit{}, err 94 | } 95 | 96 | electionId := BytesToArbo(util.RandomBytes(32)) 97 | nullifier, err := poseidon.Hash([]*big.Int{candidate.Private, electionId[0], electionId[1]}) 98 | if err != nil { 99 | return ZkCensusCircuit{}, err 100 | } 101 | 102 | voteHash := BytesToArbo(factoryWeight.Bytes()) 103 | return ZkCensusCircuit{ 104 | ElectionId: [2]frontend.Variable{electionId[0], electionId[1]}, 105 | CensusRoot: arbo.BytesToBigInt(root), 106 | Nullifier: nullifier, 107 | FactoryWeight: factoryWeight, 108 | VoteHash: [2]frontend.Variable{voteHash[0], voteHash[1]}, 109 | CensusSiblings: siblings, 110 | PrivateKey: candidate.Private, 111 | VotingWeight: big.NewInt(5), 112 | }, nil 113 | } 114 | 115 | func (z *ZkCensusCircuit) String() string { 116 | str := strings.Builder{} 117 | str.WriteString(fmt.Sprintf("ElectionId: %x\n", z.ElectionId)) 118 | str.WriteString(fmt.Sprintf("CensusRoot: %x\n", z.CensusRoot)) 119 | str.WriteString(fmt.Sprintf("Nullifier: %x\n", z.Nullifier)) 120 | str.WriteString(fmt.Sprintf("FactoryWeight: %s\n", z.FactoryWeight)) 121 | str.WriteString(fmt.Sprintf("VoteHash: %x\n", z.VoteHash)) 122 | str.WriteString(fmt.Sprintf("Siblings: %x\n", z.CensusSiblings)) 123 | str.WriteString(fmt.Sprintf("PrivKey: %x\n", z.PrivateKey)) 124 | str.WriteString(fmt.Sprintf("VotingWeight: %s\n", z.VotingWeight)) 125 | return str.String() 126 | } 127 | -------------------------------------------------------------------------------- /circuits/zkcensus/zkcensus_test.go: -------------------------------------------------------------------------------- 1 | package zkcensus 2 | 3 | import ( 4 | "flag" 5 | "testing" 6 | 7 | "github.com/consensys/gnark-crypto/ecc" 8 | "github.com/consensys/gnark/backend" 9 | "github.com/consensys/gnark/test" 10 | ) 11 | 12 | var nLevels = flag.Int("nLevels", 160, "number of levels of the arbo tree") 13 | var nKeys = flag.Int("nKyes", 200, "number of keys to add to the arbo tree") 14 | 15 | func TestZkCensusCircuit(t *testing.T) { 16 | assert := test.NewAssert(t) 17 | var circuit ZkCensusCircuit 18 | 19 | success, _ := ZkCensusInputs(*nLevels, *nKeys) 20 | assert.SolvingSucceeded(&circuit, &success, test.WithCurves(ecc.BN254), test.WithBackends(backend.PLONK)) 21 | assert.SolvingSucceeded(&circuit, &success, test.WithCurves(ecc.BN254), test.WithBackends(backend.GROTH16)) 22 | } 23 | -------------------------------------------------------------------------------- /cmd/compiler/groth16.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "gnark-prover-tinygo/circuits/zkcensus" 5 | "os" 6 | 7 | "github.com/consensys/gnark-crypto/ecc" 8 | "github.com/consensys/gnark/backend/groth16" 9 | "github.com/consensys/gnark/constraint" 10 | cs "github.com/consensys/gnark/constraint/bn254" 11 | "github.com/consensys/gnark/frontend" 12 | "github.com/consensys/gnark/frontend/cs/r1cs" 13 | ) 14 | 15 | func compileGroth16() (constraint.ConstraintSystem, groth16.ProvingKey, groth16.VerifyingKey, error) { 16 | var c zkcensus.ZkCensusCircuit 17 | ccs, err := frontend.Compile(ecc.BN254.ScalarField(), r1cs.NewBuilder, &c) 18 | if err != nil { 19 | return nil, nil, nil, err 20 | } 21 | 22 | provingKey, verifyingKey, err := groth16.Setup(ccs) 23 | if err != nil { 24 | return nil, nil, nil, err 25 | } 26 | 27 | return ccs, provingKey, verifyingKey, nil 28 | } 29 | 30 | func saveGroth16(ccs constraint.ConstraintSystem, provingKey groth16.ProvingKey, 31 | verifyingKey groth16.VerifyingKey, ccsDst, pKeyDst, vKeyDst string) error { 32 | fdCCS, err := os.Create(ccsDst) 33 | if err != nil { 34 | return err 35 | } 36 | defer fdCCS.Close() 37 | _r1cs := ccs.(*cs.R1CS) 38 | if _, err := _r1cs.WriteTo(fdCCS); err != nil { 39 | return err 40 | } 41 | 42 | fdPKey, err := os.Create(pKeyDst) 43 | if err != nil { 44 | return err 45 | } 46 | defer fdPKey.Close() 47 | if _, err := provingKey.WriteRawTo(fdPKey); err != nil { 48 | return err 49 | } 50 | 51 | fdVKey, err := os.Create(vKeyDst) 52 | if err != nil { 53 | return err 54 | } 55 | defer fdVKey.Close() 56 | if _, err := verifyingKey.WriteRawTo(fdVKey); err != nil { 57 | return err 58 | } 59 | return nil 60 | } 61 | -------------------------------------------------------------------------------- /cmd/compiler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "gnark-prover-tinygo/circuits/zkcensus" 7 | "log" 8 | "os" 9 | 10 | "github.com/consensys/gnark-crypto/ecc" 11 | "github.com/consensys/gnark/frontend" 12 | ) 13 | 14 | var ( 15 | ccsOutput = flag.String("ccs", "./artifacts/zkcensus.ccs", "Output file to the encoded output Gnark Circuit Constrain System, result of circuit compilation") 16 | srsOutput = flag.String("srs", "./artifacts/zkcensus.srs", "Output file to the encoded output Gnark KZG polynomial commitment, result of circuit compilation") 17 | pKeyOutput = flag.String("pkey", "./artifacts/zkcensus.pkey", "Circuit proving key") 18 | vKeyOutput = flag.String("vkey", "./artifacts/zkcensus.vkey", "Circuit verifying key") 19 | witnessOutput = flag.String("witness", "./artifacts/zkcensus.witness", "Circuit witness") 20 | 21 | g16circuitOutput = flag.String("g16circuit", "./artifacts/g16_zkcensus.ccs", "Output file to the encoded output Gnark Circuit Constrain System, result of circuit compilation") 22 | g16pKeyOutput = flag.String("g16pkey", "./artifacts/g16_zkcensus.pkey", "Circuit proving key") 23 | g16vKeyOutput = flag.String("g16vkey", "./artifacts/g16_zkcensus.vkey", "Circuit verifying key") 24 | 25 | protocol = flag.String("protocol", "plonk", "Protocol to use: plonk or groth16") 26 | ) 27 | 28 | func main() { 29 | flag.Parse() 30 | input, _ := zkcensus.ZkCensusInputs(160, 100) 31 | witness, _ := frontend.NewWitness(&input, ecc.BN254.ScalarField()) 32 | fdWitness, err := os.Create(*witnessOutput) 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | defer fdWitness.Close() 37 | if _, err := witness.WriteTo(fdWitness); err != nil { 38 | log.Fatal(err) 39 | } 40 | 41 | switch *protocol { 42 | case "plonk": 43 | ccs, srs, pKey, vKey, err := compilePlonk() 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | if err := savePlonk(ccs, srs, pKey, vKey, *ccsOutput, *srsOutput, *pKeyOutput, *vKeyOutput); err != nil { 48 | log.Fatal(err) 49 | } 50 | case "groth16": 51 | g16circuit, g16pKey, g16vKey, err := compileGroth16() 52 | if err != nil { 53 | log.Fatal(err) 54 | } 55 | if err := saveGroth16(g16circuit, g16pKey, g16vKey, *g16circuitOutput, *g16pKeyOutput, *g16vKeyOutput); err != nil { 56 | log.Fatal(err) 57 | } 58 | } 59 | fmt.Printf("%s", input.String()) 60 | } 61 | -------------------------------------------------------------------------------- /cmd/compiler/plonk.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "gnark-prover-tinygo/circuits/zkcensus" 7 | "os" 8 | 9 | "github.com/consensys/gnark-crypto/ecc" 10 | "github.com/consensys/gnark-crypto/ecc/bn254/fr/kzg" 11 | "github.com/consensys/gnark/backend/plonk" 12 | "github.com/consensys/gnark/constraint" 13 | cs "github.com/consensys/gnark/constraint/bn254" 14 | "github.com/consensys/gnark/frontend" 15 | "github.com/consensys/gnark/frontend/cs/scs" 16 | ) 17 | 18 | const srsKZGsize = (1 << 14) + 3 19 | 20 | func compilePlonk() (constraint.ConstraintSystem, *kzg.SRS, plonk.ProvingKey, plonk.VerifyingKey, error) { 21 | var c zkcensus.ZkCensusCircuit 22 | 23 | // Compile circuit 24 | ccs, err := frontend.Compile(ecc.BN254.ScalarField(), scs.NewBuilder, &c) 25 | if err != nil { 26 | return nil, nil, nil, nil, err 27 | } 28 | 29 | // Generate KZG file (trusted setup) 30 | curveID := ecc.BN254 31 | alpha, err := rand.Int(rand.Reader, curveID.ScalarField()) 32 | if err != nil { 33 | return nil, nil, nil, nil, err 34 | } 35 | 36 | // calculate the size for the KZG 37 | nbConstraints := ccs.GetNbConstraints() 38 | sizeSystem := nbConstraints + ccs.GetNbPublicVariables() 39 | kzgSize := ecc.NextPowerOfTwo(uint64(sizeSystem)) + 3 40 | 41 | fmt.Println("Generating KZG SRS for curve", curveID.String(), "with size", kzgSize) 42 | kzg, err := kzg.NewSRS(kzgSize, alpha) 43 | if err != nil { 44 | return nil, nil, nil, nil, err 45 | } 46 | 47 | // Generate proving and verifying keys 48 | fmt.Println("Generating proving and verifying keys") 49 | provingKey, verifyingKey, err := plonk.Setup(ccs, kzg) 50 | if err != nil { 51 | return nil, nil, nil, nil, err 52 | } 53 | 54 | return ccs, kzg, provingKey, verifyingKey, nil 55 | } 56 | 57 | func savePlonk(ccs constraint.ConstraintSystem, kzg *kzg.SRS, provingKey plonk.ProvingKey, verifyingKey plonk.VerifyingKey, ccsDst, srsDst, pKeyDst, vKeyDst string) error { 58 | fdSRS, err := os.Create(srsDst) 59 | if err != nil { 60 | return err 61 | } 62 | defer fdSRS.Close() 63 | // KZG has its own binary encoding 64 | n, err := kzg.WriteTo(fdSRS) 65 | if err != nil { 66 | return err 67 | } 68 | println("KZG size:", n) 69 | 70 | fdCCS, err := os.Create(ccsDst) 71 | if err != nil { 72 | return err 73 | } 74 | defer fdCCS.Close() 75 | _scs := ccs.(*cs.SparseR1CS) 76 | n, err = _scs.WriteTo(fdCCS) 77 | if err != nil { 78 | return err 79 | } 80 | println("CCS Gob size:", n) 81 | 82 | fdPKey, err := os.Create(pKeyDst) 83 | if err != nil { 84 | return err 85 | } 86 | defer fdPKey.Close() 87 | n, err = provingKey.WriteTo(fdPKey) 88 | if err != nil { 89 | return err 90 | } 91 | println("ProvingKey size:", n) 92 | 93 | fdVKey, err := os.Create(vKeyDst) 94 | if err != nil { 95 | return err 96 | } 97 | defer fdVKey.Close() 98 | n, err = verifyingKey.WriteTo(fdVKey) 99 | if err != nil { 100 | return err 101 | } 102 | println("VerifyingKey size:", n) 103 | 104 | return nil 105 | } 106 | -------------------------------------------------------------------------------- /cmd/prover/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | 8 | cp "gnark-prover-tinygo/prover" 9 | ) 10 | 11 | func main() { 12 | fdcircuit := flag.String("circuit", "", "circuit file") 13 | fdsrs := flag.String("srs", "", "srs file") 14 | fdpkey := flag.String("pkey", "", "proving key file") 15 | fdwitness := flag.String("witness", "", "witness file") 16 | protocol := flag.String("protocol", "plonk", "Protocol to use: plonk or groth16") 17 | 18 | flag.Parse() 19 | 20 | // Read the files into byte slices and call the generateProof function 21 | fmt.Println("reading circuit file: ", *fdcircuit) 22 | bccs, err := os.ReadFile(*fdcircuit) 23 | if err != nil { 24 | panic(err) 25 | } 26 | 27 | fmt.Println("reading proving key file: ", *fdpkey) 28 | bpkey, err := os.ReadFile(*fdpkey) 29 | if err != nil { 30 | panic(err) 31 | } 32 | 33 | fmt.Println("reading witness file: ", *fdwitness) 34 | bwitness, err := os.ReadFile(*fdwitness) 35 | if err != nil { 36 | panic(err) 37 | } 38 | 39 | switch *protocol { 40 | case "plonk": 41 | fmt.Println("reading srs file: ", *fdsrs) 42 | bsrs, err := os.ReadFile(*fdsrs) 43 | if err != nil { 44 | panic(err) 45 | } 46 | fmt.Println("calling generateProof function") 47 | proof, publicWitness, err := cp.GenerateProofPlonk(bccs, bsrs, bpkey, bwitness) 48 | if err != nil { 49 | panic(err) 50 | } 51 | fmt.Printf("proof: %x\n", proof) 52 | fmt.Printf("public witness: %x\n", publicWitness) 53 | case "groth16": 54 | fmt.Println("calling generateProof function") 55 | proof, publicWitness, err := cp.GenerateProofGroth16(bccs, bpkey, bwitness) 56 | if err != nil { 57 | panic(err) 58 | } 59 | fmt.Printf("proof: %x\n", proof) 60 | fmt.Printf("public witness: %x\n", publicWitness) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /examples/go/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "time" 7 | 8 | "gnark-prover-tinygo/prover" 9 | ) 10 | 11 | func main() { 12 | ccs, err := os.ReadFile("./artifacts/zkcensus.ccs") 13 | if err != nil { 14 | panic(err) 15 | } 16 | srs, _ := os.ReadFile("./artifacts/zkcensus.srs") 17 | pkey, err := os.ReadFile("./artifacts/zkcensus.pkey") 18 | if err != nil { 19 | panic(err) 20 | } 21 | witness, err := os.ReadFile("./artifacts/zkcensus.witness") 22 | if err != nil { 23 | panic(err) 24 | } 25 | 26 | start := time.Now() 27 | proof, pubWitness, err := prover.GenerateProofPlonk(ccs, srs, pkey, witness) 28 | if err != nil { 29 | panic(err) 30 | } 31 | log.Println(proof, pubWitness) 32 | log.Println("Took", time.Since(start)) 33 | } 34 | -------------------------------------------------------------------------------- /examples/tinygowasi/.parcelrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@parcel/config-default", 3 | "resolvers": ["parcel-resolver-ignore", "..."] 4 | } -------------------------------------------------------------------------------- /examples/tinygowasi/artifacts/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vocdoni/gnark-prover-tinygo/a826b77b783c2b3d909bca4e45ebccf673628779/examples/tinygowasi/artifacts/.gitkeep -------------------------------------------------------------------------------- /examples/tinygowasi/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/tinygowasi/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example1", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "@wasmer/wasi": "^1.2.2", 13 | "@wasmer/wasmfs": "0.12.0", 14 | "parcel": "^2.8.3" 15 | }, 16 | "devDependencies": { 17 | "buffer": "^5.7.1", 18 | "crypto-browserify": "^3.12.0", 19 | "events": "^3.3.0", 20 | "parcel-resolver-ignore": "^2.1.3", 21 | "process": "^0.11.10", 22 | "stream-browserify": "^3.0.0", 23 | "util": "^0.12.5" 24 | }, 25 | "parcelIgnore": [ 26 | "wasmer_wasi_js_bg.wasm" 27 | ] 28 | } -------------------------------------------------------------------------------- /examples/tinygowasi/wasm_exec.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | // 5 | // This file has been modified for use by the TinyGo compiler. 6 | 7 | (() => { 8 | // Map multiple JavaScript environments to a single common API, 9 | // preferring web standards over Node.js API. 10 | // 11 | // Environments considered: 12 | // - Browsers 13 | // - Node.js 14 | // - Electron 15 | // - Parcel 16 | 17 | if (typeof global !== "undefined") { 18 | // global already exists 19 | } else if (typeof window !== "undefined") { 20 | window.global = window; 21 | } else if (typeof self !== "undefined") { 22 | self.global = self; 23 | } else { 24 | throw new Error("cannot export Go (neither global, window nor self is defined)"); 25 | } 26 | 27 | if (!global.require && typeof require !== "undefined") { 28 | global.require = require; 29 | } 30 | 31 | if (!global.fs && global.require) { 32 | global.fs = require("fs"); 33 | } 34 | 35 | const enosys = () => { 36 | const err = new Error("not implemented"); 37 | err.code = "ENOSYS"; 38 | return err; 39 | }; 40 | 41 | if (!global.fs) { 42 | let outputBuf = ""; 43 | global.fs = { 44 | constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused 45 | writeSync(fd, buf) { 46 | outputBuf += decoder.decode(buf); 47 | const nl = outputBuf.lastIndexOf("\n"); 48 | if (nl != -1) { 49 | console.log(outputBuf.substr(0, nl)); 50 | outputBuf = outputBuf.substr(nl + 1); 51 | } 52 | return buf.length; 53 | }, 54 | write(fd, buf, offset, length, position, callback) { 55 | if (offset !== 0 || length !== buf.length || position !== null) { 56 | callback(enosys()); 57 | return; 58 | } 59 | const n = this.writeSync(fd, buf); 60 | callback(null, n); 61 | }, 62 | chmod(path, mode, callback) { callback(enosys()); }, 63 | chown(path, uid, gid, callback) { callback(enosys()); }, 64 | close(fd, callback) { callback(enosys()); }, 65 | fchmod(fd, mode, callback) { callback(enosys()); }, 66 | fchown(fd, uid, gid, callback) { callback(enosys()); }, 67 | fstat(fd, callback) { callback(enosys()); }, 68 | fsync(fd, callback) { callback(null); }, 69 | ftruncate(fd, length, callback) { callback(enosys()); }, 70 | lchown(path, uid, gid, callback) { callback(enosys()); }, 71 | link(path, link, callback) { callback(enosys()); }, 72 | lstat(path, callback) { callback(enosys()); }, 73 | mkdir(path, perm, callback) { callback(enosys()); }, 74 | open(path, flags, mode, callback) { callback(enosys()); }, 75 | read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, 76 | readdir(path, callback) { callback(enosys()); }, 77 | readlink(path, callback) { callback(enosys()); }, 78 | rename(from, to, callback) { callback(enosys()); }, 79 | rmdir(path, callback) { callback(enosys()); }, 80 | stat(path, callback) { callback(enosys()); }, 81 | symlink(path, link, callback) { callback(enosys()); }, 82 | truncate(path, length, callback) { callback(enosys()); }, 83 | unlink(path, callback) { callback(enosys()); }, 84 | utimes(path, atime, mtime, callback) { callback(enosys()); }, 85 | }; 86 | } 87 | 88 | if (!global.process) { 89 | global.process = { 90 | getuid() { return -1; }, 91 | getgid() { return -1; }, 92 | geteuid() { return -1; }, 93 | getegid() { return -1; }, 94 | getgroups() { throw enosys(); }, 95 | pid: -1, 96 | ppid: -1, 97 | umask() { throw enosys(); }, 98 | cwd() { throw enosys(); }, 99 | chdir() { throw enosys(); }, 100 | } 101 | } 102 | 103 | if (!global.crypto) { 104 | const nodeCrypto = require("crypto"); 105 | global.crypto = { 106 | getRandomValues(b) { 107 | nodeCrypto.randomFillSync(b); 108 | }, 109 | }; 110 | } 111 | 112 | if (!global.performance) { 113 | global.performance = { 114 | now() { 115 | const [sec, nsec] = process.hrtime(); 116 | return sec * 1000 + nsec / 1000000; 117 | }, 118 | }; 119 | } 120 | 121 | if (!global.TextEncoder) { 122 | global.TextEncoder = require("util").TextEncoder; 123 | } 124 | 125 | if (!global.TextDecoder) { 126 | global.TextDecoder = require("util").TextDecoder; 127 | } 128 | 129 | // End of polyfills for common API. 130 | 131 | const encoder = new TextEncoder("utf-8"); 132 | const decoder = new TextDecoder("utf-8"); 133 | var logLine = []; 134 | 135 | global.Go = class { 136 | constructor() { 137 | this._callbackTimeouts = new Map(); 138 | this._nextCallbackTimeoutID = 1; 139 | 140 | const mem = () => { 141 | // The buffer may change when requesting more memory. 142 | return new DataView(this._inst.exports.memory.buffer); 143 | } 144 | 145 | const setInt64 = (addr, v) => { 146 | mem().setUint32(addr + 0, v, true); 147 | mem().setUint32(addr + 4, Math.floor(v / 4294967296), true); 148 | } 149 | 150 | const getInt64 = (addr) => { 151 | const low = mem().getUint32(addr + 0, true); 152 | const high = mem().getInt32(addr + 4, true); 153 | return low + high * 4294967296; 154 | } 155 | 156 | const loadValue = (addr) => { 157 | const f = mem().getFloat64(addr, true); 158 | if (f === 0) { 159 | return undefined; 160 | } 161 | if (!isNaN(f)) { 162 | return f; 163 | } 164 | 165 | const id = mem().getUint32(addr, true); 166 | return this._values[id]; 167 | } 168 | 169 | const storeValue = (addr, v) => { 170 | const nanHead = 0x7FF80000; 171 | 172 | if (typeof v === "number") { 173 | if (isNaN(v)) { 174 | mem().setUint32(addr + 4, nanHead, true); 175 | mem().setUint32(addr, 0, true); 176 | return; 177 | } 178 | if (v === 0) { 179 | mem().setUint32(addr + 4, nanHead, true); 180 | mem().setUint32(addr, 1, true); 181 | return; 182 | } 183 | mem().setFloat64(addr, v, true); 184 | return; 185 | } 186 | 187 | switch (v) { 188 | case undefined: 189 | mem().setFloat64(addr, 0, true); 190 | return; 191 | case null: 192 | mem().setUint32(addr + 4, nanHead, true); 193 | mem().setUint32(addr, 2, true); 194 | return; 195 | case true: 196 | mem().setUint32(addr + 4, nanHead, true); 197 | mem().setUint32(addr, 3, true); 198 | return; 199 | case false: 200 | mem().setUint32(addr + 4, nanHead, true); 201 | mem().setUint32(addr, 4, true); 202 | return; 203 | } 204 | 205 | let id = this._ids.get(v); 206 | if (id === undefined) { 207 | id = this._idPool.pop(); 208 | if (id === undefined) { 209 | id = this._values.length; 210 | } 211 | this._values[id] = v; 212 | this._goRefCounts[id] = 0; 213 | this._ids.set(v, id); 214 | } 215 | this._goRefCounts[id]++; 216 | let typeFlag = 1; 217 | switch (typeof v) { 218 | case "string": 219 | typeFlag = 2; 220 | break; 221 | case "symbol": 222 | typeFlag = 3; 223 | break; 224 | case "function": 225 | typeFlag = 4; 226 | break; 227 | } 228 | mem().setUint32(addr + 4, nanHead | typeFlag, true); 229 | mem().setUint32(addr, id, true); 230 | } 231 | 232 | const loadSlice = (array, len, cap) => { 233 | return new Uint8Array(this._inst.exports.memory.buffer, array, len); 234 | } 235 | 236 | const loadSliceOfValues = (array, len, cap) => { 237 | const a = new Array(len); 238 | for (let i = 0; i < len; i++) { 239 | a[i] = loadValue(array + i * 8); 240 | } 241 | return a; 242 | } 243 | 244 | const loadString = (ptr, len) => { 245 | return decoder.decode(new DataView(this._inst.exports.memory.buffer, ptr, len)); 246 | } 247 | 248 | const timeOrigin = Date.now() - performance.now(); 249 | this.importObject = { 250 | wasi_snapshot_preview1: { 251 | // https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_write 252 | fd_write: function(fd, iovs_ptr, iovs_len, nwritten_ptr) { 253 | let nwritten = 0; 254 | if (fd == 1) { 255 | for (let iovs_i=0; iovs_i 0, // dummy 281 | fd_fdstat_get: () => 0, // dummy 282 | fd_seek: () => 0, // dummy 283 | "proc_exit": (code) => { 284 | if (global.process) { 285 | // Node.js 286 | process.exit(code); 287 | } else { 288 | // Can't exit in a browser. 289 | throw 'trying to exit with code ' + code; 290 | } 291 | }, 292 | random_get: (bufPtr, bufLen) => { 293 | crypto.getRandomValues(loadSlice(bufPtr, bufLen)); 294 | return 0; 295 | }, 296 | }, 297 | env: { 298 | // func ticks() float64 299 | "runtime.ticks": () => { 300 | return timeOrigin + performance.now(); 301 | }, 302 | 303 | // func sleepTicks(timeout float64) 304 | "runtime.sleepTicks": (timeout) => { 305 | // Do not sleep, only reactivate scheduler after the given timeout. 306 | setTimeout(this._inst.exports.go_scheduler, timeout); 307 | }, 308 | 309 | // func finalizeRef(v ref) 310 | "syscall/js.finalizeRef": (sp) => { 311 | // Note: TinyGo does not support finalizers so this should never be 312 | // called. 313 | console.error('syscall/js.finalizeRef not implemented'); 314 | }, 315 | 316 | // func stringVal(value string) ref 317 | "syscall/js.stringVal": (ret_ptr, value_ptr, value_len) => { 318 | const s = loadString(value_ptr, value_len); 319 | storeValue(ret_ptr, s); 320 | }, 321 | 322 | // func valueGet(v ref, p string) ref 323 | "syscall/js.valueGet": (retval, v_addr, p_ptr, p_len) => { 324 | let prop = loadString(p_ptr, p_len); 325 | let value = loadValue(v_addr); 326 | let result = Reflect.get(value, prop); 327 | storeValue(retval, result); 328 | }, 329 | 330 | // func valueSet(v ref, p string, x ref) 331 | "syscall/js.valueSet": (v_addr, p_ptr, p_len, x_addr) => { 332 | const v = loadValue(v_addr); 333 | const p = loadString(p_ptr, p_len); 334 | const x = loadValue(x_addr); 335 | Reflect.set(v, p, x); 336 | }, 337 | 338 | // func valueDelete(v ref, p string) 339 | "syscall/js.valueDelete": (v_addr, p_ptr, p_len) => { 340 | const v = loadValue(v_addr); 341 | const p = loadString(p_ptr, p_len); 342 | Reflect.deleteProperty(v, p); 343 | }, 344 | 345 | // func valueIndex(v ref, i int) ref 346 | "syscall/js.valueIndex": (ret_addr, v_addr, i) => { 347 | storeValue(ret_addr, Reflect.get(loadValue(v_addr), i)); 348 | }, 349 | 350 | // valueSetIndex(v ref, i int, x ref) 351 | "syscall/js.valueSetIndex": (v_addr, i, x_addr) => { 352 | Reflect.set(loadValue(v_addr), i, loadValue(x_addr)); 353 | }, 354 | 355 | // func valueCall(v ref, m string, args []ref) (ref, bool) 356 | "syscall/js.valueCall": (ret_addr, v_addr, m_ptr, m_len, args_ptr, args_len, args_cap) => { 357 | const v = loadValue(v_addr); 358 | const name = loadString(m_ptr, m_len); 359 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 360 | try { 361 | const m = Reflect.get(v, name); 362 | storeValue(ret_addr, Reflect.apply(m, v, args)); 363 | mem().setUint8(ret_addr + 8, 1); 364 | } catch (err) { 365 | storeValue(ret_addr, err); 366 | mem().setUint8(ret_addr + 8, 0); 367 | } 368 | }, 369 | 370 | // func valueInvoke(v ref, args []ref) (ref, bool) 371 | "syscall/js.valueInvoke": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { 372 | try { 373 | const v = loadValue(v_addr); 374 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 375 | storeValue(ret_addr, Reflect.apply(v, undefined, args)); 376 | mem().setUint8(ret_addr + 8, 1); 377 | } catch (err) { 378 | storeValue(ret_addr, err); 379 | mem().setUint8(ret_addr + 8, 0); 380 | } 381 | }, 382 | 383 | // func valueNew(v ref, args []ref) (ref, bool) 384 | "syscall/js.valueNew": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { 385 | const v = loadValue(v_addr); 386 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 387 | try { 388 | storeValue(ret_addr, Reflect.construct(v, args)); 389 | mem().setUint8(ret_addr + 8, 1); 390 | } catch (err) { 391 | storeValue(ret_addr, err); 392 | mem().setUint8(ret_addr+ 8, 0); 393 | } 394 | }, 395 | 396 | // func valueLength(v ref) int 397 | "syscall/js.valueLength": (v_addr) => { 398 | return loadValue(v_addr).length; 399 | }, 400 | 401 | // valuePrepareString(v ref) (ref, int) 402 | "syscall/js.valuePrepareString": (ret_addr, v_addr) => { 403 | const s = String(loadValue(v_addr)); 404 | const str = encoder.encode(s); 405 | storeValue(ret_addr, str); 406 | setInt64(ret_addr + 8, str.length); 407 | }, 408 | 409 | // valueLoadString(v ref, b []byte) 410 | "syscall/js.valueLoadString": (v_addr, slice_ptr, slice_len, slice_cap) => { 411 | const str = loadValue(v_addr); 412 | loadSlice(slice_ptr, slice_len, slice_cap).set(str); 413 | }, 414 | 415 | // func valueInstanceOf(v ref, t ref) bool 416 | "syscall/js.valueInstanceOf": (v_addr, t_addr) => { 417 | return loadValue(v_addr) instanceof loadValue(t_addr); 418 | }, 419 | 420 | // func copyBytesToGo(dst []byte, src ref) (int, bool) 421 | "syscall/js.copyBytesToGo": (ret_addr, dest_addr, dest_len, dest_cap, source_addr) => { 422 | let num_bytes_copied_addr = ret_addr; 423 | let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable 424 | 425 | const dst = loadSlice(dest_addr, dest_len); 426 | const src = loadValue(source_addr); 427 | if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { 428 | mem().setUint8(returned_status_addr, 0); // Return "not ok" status 429 | return; 430 | } 431 | const toCopy = src.subarray(0, dst.length); 432 | dst.set(toCopy); 433 | setInt64(num_bytes_copied_addr, toCopy.length); 434 | mem().setUint8(returned_status_addr, 1); // Return "ok" status 435 | }, 436 | 437 | // copyBytesToJS(dst ref, src []byte) (int, bool) 438 | // Originally copied from upstream Go project, then modified: 439 | // https://github.com/golang/go/blob/3f995c3f3b43033013013e6c7ccc93a9b1411ca9/misc/wasm/wasm_exec.js#L404-L416 440 | "syscall/js.copyBytesToJS": (ret_addr, dest_addr, source_addr, source_len, source_cap) => { 441 | let num_bytes_copied_addr = ret_addr; 442 | let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable 443 | 444 | const dst = loadValue(dest_addr); 445 | const src = loadSlice(source_addr, source_len); 446 | if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { 447 | mem().setUint8(returned_status_addr, 0); // Return "not ok" status 448 | return; 449 | } 450 | const toCopy = src.subarray(0, dst.length); 451 | dst.set(toCopy); 452 | setInt64(num_bytes_copied_addr, toCopy.length); 453 | mem().setUint8(returned_status_addr, 1); // Return "ok" status 454 | }, 455 | } 456 | }; 457 | } 458 | 459 | async run(instance) { 460 | this._inst = instance; 461 | this._values = [ // JS values that Go currently has references to, indexed by reference id 462 | NaN, 463 | 0, 464 | null, 465 | true, 466 | false, 467 | global, 468 | this, 469 | ]; 470 | this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id 471 | this._ids = new Map(); // mapping from JS values to reference ids 472 | this._idPool = []; // unused ids that have been garbage collected 473 | this.exited = false; // whether the Go program has exited 474 | 475 | const mem = new DataView(this._inst.exports.memory.buffer) 476 | 477 | while (true) { 478 | const callbackPromise = new Promise((resolve) => { 479 | this._resolveCallbackPromise = () => { 480 | if (this.exited) { 481 | throw new Error("bad callback: Go program has already exited"); 482 | } 483 | setTimeout(resolve, 0); // make sure it is asynchronous 484 | }; 485 | }); 486 | this._inst.exports._start(); 487 | if (this.exited) { 488 | break; 489 | } 490 | await callbackPromise; 491 | } 492 | } 493 | 494 | _resume() { 495 | if (this.exited) { 496 | throw new Error("Go program has already exited"); 497 | } 498 | this._inst.exports.resume(); 499 | if (this.exited) { 500 | this._resolveExitPromise(); 501 | } 502 | } 503 | 504 | _makeFuncWrapper(id) { 505 | const go = this; 506 | return function () { 507 | const event = { id: id, this: this, args: arguments }; 508 | go._pendingEvent = event; 509 | go._resume(); 510 | return event.result; 511 | }; 512 | } 513 | } 514 | 515 | if ( 516 | global.require && 517 | global.require.main === module && 518 | global.process && 519 | global.process.versions && 520 | !global.process.versions.electron 521 | ) { 522 | if (process.argv.length != 3) { 523 | console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"); 524 | process.exit(1); 525 | } 526 | 527 | const go = new Go(); 528 | WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => { 529 | return go.run(result.instance); 530 | }).catch((err) => { 531 | console.error(err); 532 | process.exit(1); 533 | }); 534 | } 535 | })(); 536 | -------------------------------------------------------------------------------- /examples/tinygowasi/worker.js: -------------------------------------------------------------------------------- 1 | import './wasm_exec.js'; 2 | 3 | import { init, WASI } from '@wasmer/wasi'; 4 | 5 | import witnessUrl from "url:./artifacts/zkcensus.witness"; 6 | import wasmUrl from "url:./artifacts/g16_prover.wasm"; 7 | 8 | addEventListener('message', async(e) => { 9 | await init(); 10 | 11 | let start = Date.now(); 12 | console.log("reading artifacts..."); 13 | 14 | let resWitness = await fetch(witnessUrl); 15 | let witnessBuff = await resWitness.arrayBuffer(); 16 | let witness = new Uint8Array(witnessBuff); 17 | 18 | console.log("loading go env and wasm..."); 19 | let wasi = new WASI({ 20 | env: {}, 21 | args: [ 22 | `[${witness.join(",")}]`, 23 | ], 24 | }); 25 | const wasmModule = await WebAssembly.compileStreaming(fetch(wasmUrl)); 26 | const instance = await wasi.instantiate(wasmModule, { 27 | ...wasi.getImports(wasmModule) 28 | }); 29 | console.log(instance) 30 | 31 | console.log("generating proof..."); 32 | let status = wasi.start(); 33 | console.log("status code", status); 34 | 35 | let res = wasi.getStdoutString(); 36 | console.log("result", res); 37 | 38 | let end = Date.now(); 39 | let elapsed = end - start; 40 | console.log("Finished!", `${ elapsed / 1000 }s`); 41 | }); -------------------------------------------------------------------------------- /examples/web/index_g16.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Gnark ZkCensus-Wasm prover test | Vocdoni 6 | 7 | 20 | 21 | 22 | 23 |

24 | Gnark ZkCensus-Wasm prover test 25 |

26 | 27 |
⚠️🚧 This repository is currently a proof of concept. 🚧⚠️
28 | 29 |
30 | 31 | 32 | 61 | 62 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /examples/web/index_plonk.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Gnark ZkCensus-Wasm prover test | Vocdoni 6 | 7 | 20 | 21 | 22 | 23 |

24 | Gnark ZkCensus-Wasm prover test 25 |

26 | 27 |
⚠️🚧 This repository is currently a proof of concept. 🚧⚠️
28 | 29 |
30 | 31 | 32 | 61 | 62 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /examples/web/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "path/filepath" 8 | "runtime" 9 | "strings" 10 | ) 11 | 12 | func main() { 13 | _, callerFile, _, ok := runtime.Caller(0) 14 | if !ok { 15 | fmt.Println("unable to get the current caller file") 16 | return 17 | } 18 | examplePath := filepath.Dir(callerFile) 19 | artifactsPath := filepath.Join(examplePath, "../../artifacts") 20 | 21 | exampleFs := http.FileServer(http.Dir(examplePath)) 22 | artifactsFs := http.FileServer(http.Dir(artifactsPath)) 23 | 24 | artifactsHandler := http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { 25 | resp.Header().Add("Cache-Control", "no-cache") 26 | if strings.HasSuffix(req.URL.Path, ".wasm") { 27 | resp.Header().Set("content-type", "application/wasm") 28 | } 29 | artifactsFs.ServeHTTP(resp, req) 30 | log.Println("artifactsHandler: ", req.URL.Path) 31 | }) 32 | 33 | http.Handle("/", exampleFs) 34 | http.Handle("/artifacts/", http.StripPrefix("/artifacts/", artifactsHandler)) 35 | 36 | fmt.Println("Starting http server... Example url: http://0.0.0.0:5050/. Check the console!") 37 | if err := http.ListenAndServe(":5050", nil); err != nil { 38 | fmt.Println(err) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /examples/web/wasm_exec.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | // 5 | // This file has been modified for use by the TinyGo compiler. 6 | 7 | (() => { 8 | // Map multiple JavaScript environments to a single common API, 9 | // preferring web standards over Node.js API. 10 | // 11 | // Environments considered: 12 | // - Browsers 13 | // - Node.js 14 | // - Electron 15 | // - Parcel 16 | 17 | if (typeof global !== "undefined") { 18 | // global already exists 19 | } else if (typeof window !== "undefined") { 20 | window.global = window; 21 | } else if (typeof self !== "undefined") { 22 | self.global = self; 23 | } else { 24 | throw new Error("cannot export Go (neither global, window nor self is defined)"); 25 | } 26 | 27 | if (!global.require && typeof require !== "undefined") { 28 | global.require = require; 29 | } 30 | 31 | if (!global.fs && global.require) { 32 | global.fs = require("fs"); 33 | } 34 | 35 | const enosys = () => { 36 | const err = new Error("not implemented"); 37 | err.code = "ENOSYS"; 38 | return err; 39 | }; 40 | 41 | if (!global.fs) { 42 | let outputBuf = ""; 43 | global.fs = { 44 | constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused 45 | writeSync(fd, buf) { 46 | outputBuf += decoder.decode(buf); 47 | const nl = outputBuf.lastIndexOf("\n"); 48 | if (nl != -1) { 49 | console.log(outputBuf.substr(0, nl)); 50 | outputBuf = outputBuf.substr(nl + 1); 51 | } 52 | return buf.length; 53 | }, 54 | write(fd, buf, offset, length, position, callback) { 55 | if (offset !== 0 || length !== buf.length || position !== null) { 56 | callback(enosys()); 57 | return; 58 | } 59 | const n = this.writeSync(fd, buf); 60 | callback(null, n); 61 | }, 62 | chmod(path, mode, callback) { callback(enosys()); }, 63 | chown(path, uid, gid, callback) { callback(enosys()); }, 64 | close(fd, callback) { callback(enosys()); }, 65 | fchmod(fd, mode, callback) { callback(enosys()); }, 66 | fchown(fd, uid, gid, callback) { callback(enosys()); }, 67 | fstat(fd, callback) { callback(enosys()); }, 68 | fsync(fd, callback) { callback(null); }, 69 | ftruncate(fd, length, callback) { callback(enosys()); }, 70 | lchown(path, uid, gid, callback) { callback(enosys()); }, 71 | link(path, link, callback) { callback(enosys()); }, 72 | lstat(path, callback) { callback(enosys()); }, 73 | mkdir(path, perm, callback) { callback(enosys()); }, 74 | open(path, flags, mode, callback) { callback(enosys()); }, 75 | read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, 76 | readdir(path, callback) { callback(enosys()); }, 77 | readlink(path, callback) { callback(enosys()); }, 78 | rename(from, to, callback) { callback(enosys()); }, 79 | rmdir(path, callback) { callback(enosys()); }, 80 | stat(path, callback) { callback(enosys()); }, 81 | symlink(path, link, callback) { callback(enosys()); }, 82 | truncate(path, length, callback) { callback(enosys()); }, 83 | unlink(path, callback) { callback(enosys()); }, 84 | utimes(path, atime, mtime, callback) { callback(enosys()); }, 85 | }; 86 | } 87 | 88 | if (!global.process) { 89 | global.process = { 90 | getuid() { return -1; }, 91 | getgid() { return -1; }, 92 | geteuid() { return -1; }, 93 | getegid() { return -1; }, 94 | getgroups() { throw enosys(); }, 95 | pid: -1, 96 | ppid: -1, 97 | umask() { throw enosys(); }, 98 | cwd() { throw enosys(); }, 99 | chdir() { throw enosys(); }, 100 | } 101 | } 102 | 103 | if (!global.crypto) { 104 | const nodeCrypto = require("crypto"); 105 | global.crypto = { 106 | getRandomValues(b) { 107 | nodeCrypto.randomFillSync(b); 108 | }, 109 | }; 110 | } 111 | 112 | if (!global.performance) { 113 | global.performance = { 114 | now() { 115 | const [sec, nsec] = process.hrtime(); 116 | return sec * 1000 + nsec / 1000000; 117 | }, 118 | }; 119 | } 120 | 121 | if (!global.TextEncoder) { 122 | global.TextEncoder = require("util").TextEncoder; 123 | } 124 | 125 | if (!global.TextDecoder) { 126 | global.TextDecoder = require("util").TextDecoder; 127 | } 128 | 129 | // End of polyfills for common API. 130 | 131 | const encoder = new TextEncoder("utf-8"); 132 | const decoder = new TextDecoder("utf-8"); 133 | var logLine = []; 134 | 135 | global.Go = class { 136 | constructor() { 137 | this._callbackTimeouts = new Map(); 138 | this._nextCallbackTimeoutID = 1; 139 | 140 | const mem = () => { 141 | // The buffer may change when requesting more memory. 142 | return new DataView(this._inst.exports.memory.buffer); 143 | } 144 | 145 | const setInt64 = (addr, v) => { 146 | mem().setUint32(addr + 0, v, true); 147 | mem().setUint32(addr + 4, Math.floor(v / 4294967296), true); 148 | } 149 | 150 | const getInt64 = (addr) => { 151 | const low = mem().getUint32(addr + 0, true); 152 | const high = mem().getInt32(addr + 4, true); 153 | return low + high * 4294967296; 154 | } 155 | 156 | const loadValue = (addr) => { 157 | const f = mem().getFloat64(addr, true); 158 | if (f === 0) { 159 | return undefined; 160 | } 161 | if (!isNaN(f)) { 162 | return f; 163 | } 164 | 165 | const id = mem().getUint32(addr, true); 166 | return this._values[id]; 167 | } 168 | 169 | const storeValue = (addr, v) => { 170 | const nanHead = 0x7FF80000; 171 | 172 | if (typeof v === "number") { 173 | if (isNaN(v)) { 174 | mem().setUint32(addr + 4, nanHead, true); 175 | mem().setUint32(addr, 0, true); 176 | return; 177 | } 178 | if (v === 0) { 179 | mem().setUint32(addr + 4, nanHead, true); 180 | mem().setUint32(addr, 1, true); 181 | return; 182 | } 183 | mem().setFloat64(addr, v, true); 184 | return; 185 | } 186 | 187 | switch (v) { 188 | case undefined: 189 | mem().setFloat64(addr, 0, true); 190 | return; 191 | case null: 192 | mem().setUint32(addr + 4, nanHead, true); 193 | mem().setUint32(addr, 2, true); 194 | return; 195 | case true: 196 | mem().setUint32(addr + 4, nanHead, true); 197 | mem().setUint32(addr, 3, true); 198 | return; 199 | case false: 200 | mem().setUint32(addr + 4, nanHead, true); 201 | mem().setUint32(addr, 4, true); 202 | return; 203 | } 204 | 205 | let id = this._ids.get(v); 206 | if (id === undefined) { 207 | id = this._idPool.pop(); 208 | if (id === undefined) { 209 | id = this._values.length; 210 | } 211 | this._values[id] = v; 212 | this._goRefCounts[id] = 0; 213 | this._ids.set(v, id); 214 | } 215 | this._goRefCounts[id]++; 216 | let typeFlag = 1; 217 | switch (typeof v) { 218 | case "string": 219 | typeFlag = 2; 220 | break; 221 | case "symbol": 222 | typeFlag = 3; 223 | break; 224 | case "function": 225 | typeFlag = 4; 226 | break; 227 | } 228 | mem().setUint32(addr + 4, nanHead | typeFlag, true); 229 | mem().setUint32(addr, id, true); 230 | } 231 | 232 | const loadSlice = (array, len, cap) => { 233 | return new Uint8Array(this._inst.exports.memory.buffer, array, len); 234 | } 235 | 236 | const loadSliceOfValues = (array, len, cap) => { 237 | const a = new Array(len); 238 | for (let i = 0; i < len; i++) { 239 | a[i] = loadValue(array + i * 8); 240 | } 241 | return a; 242 | } 243 | 244 | const loadString = (ptr, len) => { 245 | return decoder.decode(new DataView(this._inst.exports.memory.buffer, ptr, len)); 246 | } 247 | 248 | const timeOrigin = Date.now() - performance.now(); 249 | this.importObject = { 250 | wasi_snapshot_preview1: { 251 | // https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_write 252 | fd_write: function(fd, iovs_ptr, iovs_len, nwritten_ptr) { 253 | let nwritten = 0; 254 | if (fd == 1) { 255 | for (let iovs_i=0; iovs_i 0, // dummy 281 | fd_fdstat_get: () => 0, // dummy 282 | fd_seek: () => 0, // dummy 283 | "proc_exit": (code) => { 284 | if (global.process) { 285 | // Node.js 286 | process.exit(code); 287 | } else { 288 | // Can't exit in a browser. 289 | throw 'trying to exit with code ' + code; 290 | } 291 | }, 292 | random_get: (bufPtr, bufLen) => { 293 | crypto.getRandomValues(loadSlice(bufPtr, bufLen)); 294 | return 0; 295 | }, 296 | }, 297 | env: { 298 | // func ticks() float64 299 | "runtime.ticks": () => { 300 | return timeOrigin + performance.now(); 301 | }, 302 | 303 | // func sleepTicks(timeout float64) 304 | "runtime.sleepTicks": (timeout) => { 305 | // Do not sleep, only reactivate scheduler after the given timeout. 306 | setTimeout(this._inst.exports.go_scheduler, timeout); 307 | }, 308 | 309 | // func finalizeRef(v ref) 310 | "syscall/js.finalizeRef": (sp) => { 311 | // Note: TinyGo does not support finalizers so this should never be 312 | // called. 313 | console.error('syscall/js.finalizeRef not implemented'); 314 | }, 315 | 316 | // func stringVal(value string) ref 317 | "syscall/js.stringVal": (ret_ptr, value_ptr, value_len) => { 318 | const s = loadString(value_ptr, value_len); 319 | storeValue(ret_ptr, s); 320 | }, 321 | 322 | // func valueGet(v ref, p string) ref 323 | "syscall/js.valueGet": (retval, v_addr, p_ptr, p_len) => { 324 | let prop = loadString(p_ptr, p_len); 325 | let value = loadValue(v_addr); 326 | let result = Reflect.get(value, prop); 327 | storeValue(retval, result); 328 | }, 329 | 330 | // func valueSet(v ref, p string, x ref) 331 | "syscall/js.valueSet": (v_addr, p_ptr, p_len, x_addr) => { 332 | const v = loadValue(v_addr); 333 | const p = loadString(p_ptr, p_len); 334 | const x = loadValue(x_addr); 335 | Reflect.set(v, p, x); 336 | }, 337 | 338 | // func valueDelete(v ref, p string) 339 | "syscall/js.valueDelete": (v_addr, p_ptr, p_len) => { 340 | const v = loadValue(v_addr); 341 | const p = loadString(p_ptr, p_len); 342 | Reflect.deleteProperty(v, p); 343 | }, 344 | 345 | // func valueIndex(v ref, i int) ref 346 | "syscall/js.valueIndex": (ret_addr, v_addr, i) => { 347 | storeValue(ret_addr, Reflect.get(loadValue(v_addr), i)); 348 | }, 349 | 350 | // valueSetIndex(v ref, i int, x ref) 351 | "syscall/js.valueSetIndex": (v_addr, i, x_addr) => { 352 | Reflect.set(loadValue(v_addr), i, loadValue(x_addr)); 353 | }, 354 | 355 | // func valueCall(v ref, m string, args []ref) (ref, bool) 356 | "syscall/js.valueCall": (ret_addr, v_addr, m_ptr, m_len, args_ptr, args_len, args_cap) => { 357 | const v = loadValue(v_addr); 358 | const name = loadString(m_ptr, m_len); 359 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 360 | try { 361 | const m = Reflect.get(v, name); 362 | storeValue(ret_addr, Reflect.apply(m, v, args)); 363 | mem().setUint8(ret_addr + 8, 1); 364 | } catch (err) { 365 | storeValue(ret_addr, err); 366 | mem().setUint8(ret_addr + 8, 0); 367 | } 368 | }, 369 | 370 | // func valueInvoke(v ref, args []ref) (ref, bool) 371 | "syscall/js.valueInvoke": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { 372 | try { 373 | const v = loadValue(v_addr); 374 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 375 | storeValue(ret_addr, Reflect.apply(v, undefined, args)); 376 | mem().setUint8(ret_addr + 8, 1); 377 | } catch (err) { 378 | storeValue(ret_addr, err); 379 | mem().setUint8(ret_addr + 8, 0); 380 | } 381 | }, 382 | 383 | // func valueNew(v ref, args []ref) (ref, bool) 384 | "syscall/js.valueNew": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { 385 | const v = loadValue(v_addr); 386 | const args = loadSliceOfValues(args_ptr, args_len, args_cap); 387 | try { 388 | storeValue(ret_addr, Reflect.construct(v, args)); 389 | mem().setUint8(ret_addr + 8, 1); 390 | } catch (err) { 391 | storeValue(ret_addr, err); 392 | mem().setUint8(ret_addr+ 8, 0); 393 | } 394 | }, 395 | 396 | // func valueLength(v ref) int 397 | "syscall/js.valueLength": (v_addr) => { 398 | return loadValue(v_addr).length; 399 | }, 400 | 401 | // valuePrepareString(v ref) (ref, int) 402 | "syscall/js.valuePrepareString": (ret_addr, v_addr) => { 403 | const s = String(loadValue(v_addr)); 404 | const str = encoder.encode(s); 405 | storeValue(ret_addr, str); 406 | setInt64(ret_addr + 8, str.length); 407 | }, 408 | 409 | // valueLoadString(v ref, b []byte) 410 | "syscall/js.valueLoadString": (v_addr, slice_ptr, slice_len, slice_cap) => { 411 | const str = loadValue(v_addr); 412 | loadSlice(slice_ptr, slice_len, slice_cap).set(str); 413 | }, 414 | 415 | // func valueInstanceOf(v ref, t ref) bool 416 | "syscall/js.valueInstanceOf": (v_addr, t_addr) => { 417 | return loadValue(v_addr) instanceof loadValue(t_addr); 418 | }, 419 | 420 | // func copyBytesToGo(dst []byte, src ref) (int, bool) 421 | "syscall/js.copyBytesToGo": (ret_addr, dest_addr, dest_len, dest_cap, source_addr) => { 422 | let num_bytes_copied_addr = ret_addr; 423 | let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable 424 | 425 | const dst = loadSlice(dest_addr, dest_len); 426 | const src = loadValue(source_addr); 427 | if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { 428 | mem().setUint8(returned_status_addr, 0); // Return "not ok" status 429 | return; 430 | } 431 | const toCopy = src.subarray(0, dst.length); 432 | dst.set(toCopy); 433 | setInt64(num_bytes_copied_addr, toCopy.length); 434 | mem().setUint8(returned_status_addr, 1); // Return "ok" status 435 | }, 436 | 437 | // copyBytesToJS(dst ref, src []byte) (int, bool) 438 | // Originally copied from upstream Go project, then modified: 439 | // https://github.com/golang/go/blob/3f995c3f3b43033013013e6c7ccc93a9b1411ca9/misc/wasm/wasm_exec.js#L404-L416 440 | "syscall/js.copyBytesToJS": (ret_addr, dest_addr, source_addr, source_len, source_cap) => { 441 | let num_bytes_copied_addr = ret_addr; 442 | let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable 443 | 444 | const dst = loadValue(dest_addr); 445 | const src = loadSlice(source_addr, source_len); 446 | if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { 447 | mem().setUint8(returned_status_addr, 0); // Return "not ok" status 448 | return; 449 | } 450 | const toCopy = src.subarray(0, dst.length); 451 | dst.set(toCopy); 452 | setInt64(num_bytes_copied_addr, toCopy.length); 453 | mem().setUint8(returned_status_addr, 1); // Return "ok" status 454 | }, 455 | } 456 | }; 457 | } 458 | 459 | async run(instance) { 460 | this._inst = instance; 461 | this._values = [ // JS values that Go currently has references to, indexed by reference id 462 | NaN, 463 | 0, 464 | null, 465 | true, 466 | false, 467 | global, 468 | this, 469 | ]; 470 | this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id 471 | this._ids = new Map(); // mapping from JS values to reference ids 472 | this._idPool = []; // unused ids that have been garbage collected 473 | this.exited = false; // whether the Go program has exited 474 | 475 | const mem = new DataView(this._inst.exports.memory.buffer) 476 | 477 | while (true) { 478 | const callbackPromise = new Promise((resolve) => { 479 | this._resolveCallbackPromise = () => { 480 | if (this.exited) { 481 | throw new Error("bad callback: Go program has already exited"); 482 | } 483 | setTimeout(resolve, 0); // make sure it is asynchronous 484 | }; 485 | }); 486 | this._inst.exports._start(); 487 | if (this.exited) { 488 | break; 489 | } 490 | await callbackPromise; 491 | } 492 | } 493 | 494 | _resume() { 495 | if (this.exited) { 496 | throw new Error("Go program has already exited"); 497 | } 498 | this._inst.exports.resume(); 499 | if (this.exited) { 500 | this._resolveExitPromise(); 501 | } 502 | } 503 | 504 | _makeFuncWrapper(id) { 505 | const go = this; 506 | return function () { 507 | const event = { id: id, this: this, args: arguments }; 508 | go._pendingEvent = event; 509 | go._resume(); 510 | return event.result; 511 | }; 512 | } 513 | } 514 | 515 | if ( 516 | global.require && 517 | global.require.main === module && 518 | global.process && 519 | global.process.versions && 520 | !global.process.versions.electron 521 | ) { 522 | if (process.argv.length != 3) { 523 | console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"); 524 | process.exit(1); 525 | } 526 | 527 | const go = new Go(); 528 | WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => { 529 | return go.run(result.instance); 530 | }).catch((err) => { 531 | console.error(err); 532 | process.exit(1); 533 | }); 534 | } 535 | })(); 536 | -------------------------------------------------------------------------------- /examples/web/worker_g16.js: -------------------------------------------------------------------------------- 1 | importScripts("wasm_exec.js"); 2 | 3 | const workerConsole = { 4 | log: (message) => { 5 | postMessage({ type: "log", message: message }); 6 | }, 7 | error: (message) => { 8 | postMessage({ type: "error", message: message }); 9 | }, 10 | }; 11 | 12 | console.log = workerConsole.log; 13 | console.error = workerConsole.error; 14 | 15 | const go = new Go(); 16 | const WASM_URL = "./artifacts/g16_prover.wasm"; 17 | 18 | // Replace the console.log function in the Go environment 19 | go.importObject.env["syscall/js.console_log"] = (sp) => { 20 | const s = go._inst.exports.ram.loadString(sp); 21 | postMessage({ type: "log", message: s }); 22 | }; 23 | 24 | onmessage = async (event) => { 25 | if (event.data.type === "generateProof") { 26 | const witness = event.data.witness; 27 | 28 | try { 29 | let wasm; 30 | 31 | // Instantiate and run the wasm module with the modified Go environment 32 | if ('instantiateStreaming' in WebAssembly) { 33 | const result = await WebAssembly.instantiateStreaming(fetch(WASM_URL), go.importObject); 34 | wasm = result.instance; 35 | } else { 36 | const resp = await fetch(WASM_URL); 37 | const bytes = await resp.arrayBuffer(); 38 | const result = await WebAssembly.instantiate(bytes, go.importObject); 39 | wasm = result.instance; 40 | } 41 | 42 | go.run(wasm); 43 | 44 | // Call the generateProof function with the witness data 45 | elapsedTime = generateProof(witness); 46 | 47 | // Calculate the time taken for proof generation 48 | console.log(`Benchkmark output time: ${elapsedTime} ms`); 49 | 50 | // Send the result back to the main thread 51 | postMessage({ type: "proofGenerated", result: elapsedTime }); 52 | } catch (error) { 53 | postMessage({ type: "error", message: error.message }); 54 | } 55 | } 56 | }; -------------------------------------------------------------------------------- /examples/web/worker_plonk.js: -------------------------------------------------------------------------------- 1 | importScripts("wasm_exec.js"); 2 | 3 | const workerConsole = { 4 | log: (message) => { 5 | postMessage({ type: "log", message: message }); 6 | }, 7 | error: (message) => { 8 | postMessage({ type: "error", message: message }); 9 | }, 10 | }; 11 | 12 | console.log = workerConsole.log; 13 | console.error = workerConsole.error; 14 | 15 | const go = new Go(); 16 | const WASM_URL = "./artifacts/plonk_prover.wasm"; 17 | 18 | // Replace the console.log function in the Go environment 19 | go.importObject.env["syscall/js.console_log"] = (sp) => { 20 | const s = go._inst.exports.ram.loadString(sp); 21 | postMessage({ type: "log", message: s }); 22 | }; 23 | 24 | onmessage = async (event) => { 25 | if (event.data.type === "generateProof") { 26 | const witness = event.data.witness; 27 | 28 | try { 29 | let wasm; 30 | 31 | // Instantiate and run the wasm module with the modified Go environment 32 | if ('instantiateStreaming' in WebAssembly) { 33 | const result = await WebAssembly.instantiateStreaming(fetch(WASM_URL), go.importObject); 34 | wasm = result.instance; 35 | } else { 36 | const resp = await fetch(WASM_URL); 37 | const bytes = await resp.arrayBuffer(); 38 | const result = await WebAssembly.instantiate(bytes, go.importObject); 39 | wasm = result.instance; 40 | } 41 | 42 | go.run(wasm); 43 | 44 | // Call the generateProof function with the witness data 45 | elapsedTime = generateProof(witness); 46 | 47 | // Calculate the time taken for proof generation 48 | console.log(`Benchkmark output time: ${elapsedTime} ms`); 49 | 50 | // Send the result back to the main thread 51 | postMessage({ type: "proofGenerated", result: elapsedTime }); 52 | } catch (error) { 53 | postMessage({ type: "error", message: error.message }); 54 | } 55 | } 56 | }; -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module gnark-prover-tinygo 2 | 3 | go 1.19 4 | 5 | // replace github.com/vocdoni/gnark-wasm-prover => /home/p4u/repos/vocdoni/gprover 6 | // replace github.com/vocdoni/gnark-wasm-prover => /Users/lucasmenendez/Workspace/vocdoni/forks/gnark-wasm-prover 7 | // replace github.com/vocdoni/gnark-crypto => /home/p4u/repos/vocdoni/gnark-crypto 8 | // replace github.com/consensys/gnark => /home/p4u/repos/vocdoni/gnark 9 | 10 | replace github.com/consensys/gnark => github.com/vocdoni/gnark v0.0.0-20230413134136-187f3b3ead69 11 | 12 | replace github.com/consensys/gnark-crypto => github.com/vocdoni/gnark-crypto v0.10.1-0.20230411213837-3e72368bec7e 13 | 14 | require ( 15 | github.com/consensys/gnark v0.7.2-0.20230314134620-02dca8cec284 16 | github.com/consensys/gnark-crypto v0.9.2-0.20230314094804-5185eb8c3978 17 | github.com/frankban/quicktest v1.14.4 18 | github.com/iden3/go-iden3-crypto v0.0.13 19 | go.vocdoni.io/dvote v1.0.4-0.20230321132211-6095f229cd59 20 | ) 21 | 22 | require ( 23 | github.com/DataDog/zstd v1.4.8 // indirect 24 | github.com/beorn7/perks v1.0.1 // indirect 25 | github.com/bits-and-blooms/bitset v1.5.0 // indirect 26 | github.com/blang/semver/v4 v4.0.0 // indirect 27 | github.com/cespare/xxhash/v2 v2.2.0 // indirect 28 | github.com/cockroachdb/errors v1.8.9 // indirect 29 | github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect 30 | github.com/cockroachdb/pebble v0.0.0-20230309163202-51422ae2d449 // indirect 31 | github.com/cockroachdb/redact v1.1.3 // indirect 32 | github.com/consensys/bavard v0.1.13 // indirect 33 | github.com/davecgh/go-spew v1.1.1 // indirect 34 | github.com/getsentry/sentry-go v0.12.0 // indirect 35 | github.com/glendc/go-external-ip v0.1.0 // indirect 36 | github.com/gogo/protobuf v1.3.2 // indirect 37 | github.com/golang/protobuf v1.5.2 // indirect 38 | github.com/golang/snappy v0.0.4 // indirect 39 | github.com/google/go-cmp v0.5.9 // indirect 40 | github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect 41 | github.com/klauspost/compress v1.16.0 // indirect 42 | github.com/kr/pretty v0.3.1 // indirect 43 | github.com/kr/text v0.2.0 // indirect 44 | github.com/mattn/go-colorable v0.1.13 // indirect 45 | github.com/mattn/go-isatty v0.0.17 // indirect 46 | github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect 47 | github.com/mmcloughlin/addchain v0.4.0 // indirect 48 | github.com/pkg/errors v0.9.1 // indirect 49 | github.com/pmezard/go-difflib v1.0.0 // indirect 50 | github.com/prometheus/client_golang v1.14.0 // indirect 51 | github.com/prometheus/client_model v0.3.0 // indirect 52 | github.com/prometheus/common v0.37.0 // indirect 53 | github.com/prometheus/procfs v0.9.0 // indirect 54 | github.com/rogpeppe/go-internal v1.9.0 // indirect 55 | github.com/rs/zerolog v1.29.0 // indirect 56 | github.com/stretchr/testify v1.8.2 // indirect 57 | golang.org/x/crypto v0.7.0 // indirect 58 | golang.org/x/exp v0.0.0-20230310171629-522b1b587ee0 // indirect 59 | golang.org/x/sys v0.6.0 // indirect 60 | google.golang.org/protobuf v1.28.1 // indirect 61 | gopkg.in/yaml.v3 v3.0.1 // indirect 62 | rsc.io/tmplfunc v0.0.3 // indirect 63 | ) 64 | -------------------------------------------------------------------------------- /internal/zkaddress/zkaddress.go: -------------------------------------------------------------------------------- 1 | package zkaddress 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards" 7 | "github.com/iden3/go-iden3-crypto/poseidon" 8 | ) 9 | 10 | const DefaultZkAddressLen = 20 11 | 12 | type ZkAddress struct { 13 | Private *big.Int 14 | Public *big.Int 15 | Scalar *big.Int 16 | } 17 | 18 | func (zkAddr *ZkAddress) ArboBytes() []byte { 19 | bScalar := zkAddr.Scalar.Bytes() 20 | // swap endianess 21 | for i, j := 0, len(bScalar)-1; i < j; i, j = i+1, j-1 { 22 | bScalar[i], bScalar[j] = bScalar[j], bScalar[i] 23 | } 24 | // truncate to default length and return 25 | res := make([]byte, DefaultZkAddressLen) 26 | copy(res[:], bScalar) 27 | return res[:] 28 | } 29 | 30 | func FromBytes(seed []byte) (*ZkAddress, error) { 31 | // Setup the curve 32 | c := twistededwards.GetEdwardsCurve() 33 | // Get scalar private key hashing the seed with Poseidon hash 34 | private, err := poseidon.HashBytes(seed) 35 | if err != nil { 36 | return nil, err 37 | } 38 | // Get the point of the curve that represents the public key multipliying 39 | // the private key scalar by the base of the curve 40 | point := new(twistededwards.PointAffine).ScalarMultiplication(&c.Base, private) 41 | // Get the single scalar that represents the publick key hashing X, Y point 42 | // coordenates with Poseidon hash 43 | bX, bY := new(big.Int), new(big.Int) 44 | bX = point.X.BigInt(bX) 45 | bY = point.Y.BigInt(bY) 46 | public, err := poseidon.Hash([]*big.Int{bX, bY}) 47 | if err != nil { 48 | return nil, err 49 | } 50 | 51 | // truncate the most significant n bytes of the public key (little endian) 52 | // where n is the default ZkAddress length 53 | publicBytes := public.Bytes() 54 | m := len(publicBytes) - DefaultZkAddressLen 55 | scalar := new(big.Int).SetBytes(publicBytes[m:]) 56 | return &ZkAddress{private, public, scalar}, nil 57 | } 58 | -------------------------------------------------------------------------------- /internal/zkaddress/zkaddress_test.go: -------------------------------------------------------------------------------- 1 | package zkaddress 2 | 3 | import ( 4 | "testing" 5 | 6 | qt "github.com/frankban/quicktest" 7 | ) 8 | 9 | func TestFromBytes(t *testing.T) { 10 | c := qt.New(t) 11 | 12 | seed := []byte("1b505cdafb4b1150b1a740633af41e5e1f19a5c4") 13 | zkAddr, err := FromBytes(seed) 14 | c.Assert(err, qt.IsNil) 15 | c.Assert(zkAddr.Private.String(), qt.Equals, "12007696602022466067210558438468234995085206818257350359618361229442198701667") 16 | c.Assert(zkAddr.Public.String(), qt.Equals, "19597797733822453932297698102694210740977986979020091017779598307769964166976") 17 | c.Assert(zkAddr.Scalar.String(), qt.Equals, "647903732945896451226807429503635300036365909824") 18 | } 19 | -------------------------------------------------------------------------------- /prover/groth16.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/consensys/gnark-crypto/ecc" 9 | "github.com/consensys/gnark/backend/groth16" 10 | "github.com/consensys/gnark/backend/witness" 11 | "github.com/consensys/gnark/std" 12 | 13 | // This import fixes the issue that raises when a prover tries to generate a proof 14 | // of a serialized circuit. Check more information here: 15 | // - https://github.com/ConsenSys/gnark/issues/600 16 | // - https://github.com/phated/gnark-browser/blob/2446c65e89156f1a04163724a89e5dcb7e4c4886/README.md#solution-hint-registration 17 | _ "github.com/consensys/gnark/std/math/bits" 18 | ) 19 | 20 | // GenerateProofGroth16 sets up the circuit with the constrain system and the srs files 21 | // provided and generates the proof for the JSON encoded inputs (witness). It 22 | // returns the verification key, the proof and the public witness, all of this 23 | // outputs will be encoded as JSON. If something fails, it returns an error. 24 | func GenerateProofGroth16(bccs, bpkey, inputs []byte) ([]byte, []byte, error) { 25 | step := time.Now() 26 | // Read and initialize circuit CS 27 | ccs := groth16.NewCS(ecc.BN254) 28 | if _, err := ccs.ReadFrom(bytes.NewReader(bccs)); err != nil { 29 | fmt.Println("error reading circuit cs: ", err) 30 | return nil, nil, fmt.Errorf("error reading circuit cs: %w", err) 31 | } 32 | fmt.Println("ccs loaded, took (s):", time.Since(step)) 33 | step = time.Now() 34 | // Read proving key 35 | provingKey := groth16.NewProvingKey(ecc.BN254) 36 | if _, err := provingKey.UnsafeReadFrom(bytes.NewReader(bpkey)); err != nil { 37 | fmt.Println("error reading circuit pkey: ", err) 38 | return nil, nil, fmt.Errorf("error reading circuit pkey: %w", err) 39 | } 40 | fmt.Println("pKey loaded, took (s):", time.Since(step)) 41 | step = time.Now() 42 | // Read and initialize the witness 43 | cWitness, err := witness.New(ecc.BN254.ScalarField()) 44 | if err != nil { 45 | fmt.Println("error initializing witness: ", err) 46 | return nil, nil, fmt.Errorf("error initializing witness: %w", err) 47 | } 48 | if _, err := cWitness.ReadFrom(bytes.NewReader(inputs)); err != nil { 49 | fmt.Println("error reading witness: ", err) 50 | return nil, nil, fmt.Errorf("error reading witness: %w", err) 51 | } 52 | fmt.Println("witness loaded, took (s):", time.Since(step)) 53 | 54 | std.RegisterHints() 55 | 56 | step = time.Now() 57 | // Generate the proof 58 | proof, err := groth16.Prove(ccs, provingKey, cWitness) 59 | if err != nil { 60 | fmt.Printf("error generating proof: %v\n", err) 61 | return nil, nil, fmt.Errorf("error generating proof: %w", err) 62 | } 63 | fmt.Println("proof generated, took (s):", time.Since(step)) 64 | proofBuff := bytes.Buffer{} 65 | if _, err := proof.WriteTo(&proofBuff); err != nil { 66 | return nil, nil, fmt.Errorf("error encoding proof: %w", err) 67 | } 68 | // Get public witness part and encode it 69 | publicWitness, err := cWitness.Public() 70 | if err != nil { 71 | return nil, nil, fmt.Errorf("error generating public witness: %w", err) 72 | } 73 | publicWitnessBuff := bytes.Buffer{} 74 | if _, err := publicWitness.WriteTo(&publicWitnessBuff); err != nil { 75 | return nil, nil, fmt.Errorf("error encoding public witness: %w", err) 76 | } 77 | return proofBuff.Bytes(), publicWitnessBuff.Bytes(), nil 78 | } 79 | -------------------------------------------------------------------------------- /prover/prover.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/consensys/gnark-crypto/ecc" 9 | "github.com/consensys/gnark-crypto/kzg" 10 | prover "github.com/consensys/gnark/backend/plonk/bn254" 11 | witness "github.com/consensys/gnark/backend/witness" 12 | csbn254 "github.com/consensys/gnark/constraint/bn254" 13 | "github.com/consensys/gnark/std" 14 | ) 15 | 16 | // GenerateProofPlonk sets up the circuit with the constrain system and the srs files 17 | // provided and generates the proof for the JSON encoded inputs (witness). It 18 | // returns the verification key, the proof and the public witness, all of this 19 | // outputs will be encoded as JSON. If something fails, it returns an error. 20 | func GenerateProofPlonk(bccs, bsrs, bpkey, inputs []byte) ([]byte, []byte, error) { 21 | step := time.Now() 22 | // Read and initialize circuit CS 23 | fmt.Println("loading circuit...") 24 | ccs := &csbn254.SparseR1CS{} 25 | if _, err := ccs.ReadFrom(bytes.NewReader(bccs)); err != nil { 26 | return nil, nil, fmt.Errorf("error reading circuit cs: %w", err) 27 | } 28 | fmt.Println("ccs loaded, took (s):", time.Since(step)) 29 | step = time.Now() 30 | // Read and initialize SSR 31 | srs := kzg.NewSRS(ecc.BN254) 32 | if _, err := srs.ReadFrom(bytes.NewReader(bsrs)); err != nil { 33 | return nil, nil, err 34 | } 35 | fmt.Println("srs loaded, took (s):", time.Since(step)) 36 | step = time.Now() 37 | // Read proving key 38 | provingKey := &prover.ProvingKey{} 39 | if _, err := provingKey.ReadFrom(bytes.NewReader(bpkey)); err != nil { 40 | return nil, nil, fmt.Errorf("error reading circuit pkey: %w", err) 41 | } 42 | fmt.Println("pKey loaded, took (s):", time.Since(step)) 43 | step = time.Now() 44 | // Instance KZG into the proving key 45 | if err := provingKey.InitKZG(srs); err != nil { 46 | return nil, nil, fmt.Errorf("error initializating kzg into the pkey: %w", err) 47 | } 48 | fmt.Println("kzg initializated into the pKey, took (s):", time.Since(step)) 49 | step = time.Now() 50 | // Read and initialize the witness 51 | cWitness, err := witness.New(ecc.BN254.ScalarField()) 52 | if err != nil { 53 | return nil, nil, fmt.Errorf("error initializing witness: %w", err) 54 | } 55 | if _, err := cWitness.ReadFrom(bytes.NewReader(inputs)); err != nil { 56 | return nil, nil, fmt.Errorf("error reading witness: %w", err) 57 | } 58 | fmt.Println("witness loaded, took (s):", time.Since(step)) 59 | step = time.Now() 60 | 61 | // Initialize the hints registry 62 | std.RegisterHints() 63 | 64 | // Generate the proof 65 | fmt.Println("generating proof...") 66 | proof, err := prover.Prove(ccs, provingKey, cWitness) 67 | if err != nil { 68 | fmt.Println("error generating proof:", err.Error()) 69 | return nil, nil, fmt.Errorf("error generating proof: %w", err) 70 | } 71 | fmt.Println("proof generated, took (s):", time.Since(step)) 72 | proofBuff := bytes.Buffer{} 73 | if _, err := proof.WriteTo(&proofBuff); err != nil { 74 | return nil, nil, fmt.Errorf("error encoding proof: %w", err) 75 | } 76 | pKeyBuff := bytes.Buffer{} 77 | if _, err := provingKey.WriteTo(&pKeyBuff); err != nil { 78 | return nil, nil, fmt.Errorf("error encoding proof: %w", err) 79 | } 80 | // Get public witness part and encode it 81 | publicWitness, err := cWitness.Public() 82 | if err != nil { 83 | return nil, nil, fmt.Errorf("error generating public witness: %w", err) 84 | } 85 | publicWitnessBuff := bytes.Buffer{} 86 | if _, err := publicWitness.WriteTo(&publicWitnessBuff); err != nil { 87 | return nil, nil, fmt.Errorf("error encoding public witness: %w", err) 88 | } 89 | return proofBuff.Bytes(), publicWitnessBuff.Bytes(), nil 90 | } 91 | -------------------------------------------------------------------------------- /prover/prover_test.go: -------------------------------------------------------------------------------- 1 | package prover 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "testing" 7 | 8 | "github.com/consensys/gnark-crypto/ecc" 9 | "github.com/consensys/gnark-crypto/ecc/bn254/fr/kzg" 10 | "github.com/consensys/gnark/constraint" 11 | 12 | plonk "github.com/consensys/gnark/backend/plonk/bn254" 13 | cs "github.com/consensys/gnark/constraint/bn254" 14 | 15 | "github.com/consensys/gnark/frontend" 16 | "github.com/consensys/gnark/frontend/cs/scs" 17 | 18 | qt "github.com/frankban/quicktest" 19 | ) 20 | 21 | type testingCircuit struct { 22 | A, B frontend.Variable `gnark:",public"` 23 | Result frontend.Variable 24 | } 25 | 26 | func (c *testingCircuit) Define(api frontend.API) error { 27 | api.AssertIsEqual(api.Mul(c.A, c.B), c.Result) 28 | return nil 29 | } 30 | 31 | func newKZGSRS(ccs constraint.ConstraintSystem) (*kzg.SRS, error) { 32 | nbConstraints := ccs.GetNbConstraints() 33 | sizeSystem := nbConstraints + ccs.GetNbPublicVariables() 34 | kzgSize := ecc.NextPowerOfTwo(uint64(sizeSystem)) + 3 35 | 36 | curveID := ecc.BN254 37 | alpha, err := rand.Int(rand.Reader, curveID.ScalarField()) 38 | if err != nil { 39 | return nil, err 40 | } 41 | return kzg.NewSRS(kzgSize, alpha) 42 | } 43 | 44 | func TestEnd2EndCircuit(t *testing.T) { 45 | c := qt.New(t) 46 | 47 | var circuit testingCircuit 48 | ccs, err := frontend.Compile(ecc.BN254.ScalarField(), scs.NewBuilder, &circuit) 49 | c.Assert(err, qt.IsNil) 50 | 51 | var ccsBuff bytes.Buffer 52 | _, err = ccs.WriteTo(&ccsBuff) 53 | c.Assert(err, qt.IsNil) 54 | 55 | srs, err := newKZGSRS(ccs) 56 | c.Assert(err, qt.IsNil) 57 | var srsBuff bytes.Buffer 58 | _, err = srs.WriteTo(&srsBuff) 59 | c.Assert(err, qt.IsNil) 60 | 61 | _scs := ccs.(*cs.SparseR1CS) 62 | provingKey, _, err := plonk.Setup(_scs, srs) 63 | c.Assert(err, qt.IsNil) 64 | var pkeyBuff bytes.Buffer 65 | _, err = provingKey.WriteTo(&pkeyBuff) 66 | c.Assert(err, qt.IsNil) 67 | 68 | inputs := &testingCircuit{ 69 | A: 2, 70 | B: 3, 71 | Result: 6, 72 | } 73 | wtns, err := frontend.NewWitness(inputs, ecc.BN254.ScalarField()) 74 | c.Assert(err, qt.IsNil) 75 | 76 | wtnsBuff := bytes.Buffer{} 77 | _, err = wtns.WriteTo(&wtnsBuff) 78 | c.Assert(err, qt.IsNil) 79 | 80 | _, _, err = GenerateProofPlonk(ccsBuff.Bytes(), srsBuff.Bytes(), pkeyBuff.Bytes(), wtnsBuff.Bytes()) 81 | c.Assert(err, qt.IsNil) 82 | } 83 | -------------------------------------------------------------------------------- /std/hash/poseidon/poseidon.go: -------------------------------------------------------------------------------- 1 | package poseidon 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/consensys/gnark/frontend" 7 | ) 8 | 9 | type Poseidon struct { 10 | api frontend.API 11 | data []frontend.Variable 12 | } 13 | 14 | func Hash(api frontend.API, inputs ...frontend.Variable) frontend.Variable { 15 | h := NewPoseidon(api) 16 | h.Write(inputs...) 17 | return h.Sum() 18 | } 19 | 20 | func NewPoseidon(api frontend.API) Poseidon { 21 | return Poseidon{ 22 | api: api, 23 | data: []frontend.Variable{}, 24 | } 25 | } 26 | 27 | func (h *Poseidon) Write(data ...frontend.Variable) { 28 | h.data = append(h.data, data...) 29 | } 30 | 31 | func (h *Poseidon) Reset() { 32 | h.data = []frontend.Variable{} 33 | } 34 | 35 | func (h *Poseidon) Sum() frontend.Variable { 36 | nInputs := len(h.data) 37 | // Using recommended parameters from whitepaper https://eprint.iacr.org/2019/458.pdf (table 2, table 8) 38 | // Generated by https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/calc_round_numbers.py 39 | // And rounded up to nearest integer that divides by t 40 | nRoundsPC := [16]int{56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68} 41 | t := nInputs + 1 42 | nRoundsF := 8 43 | nRoundsP := nRoundsPC[t-2] 44 | c := getConstant(C, t) 45 | s := getConstant(S, t) 46 | m := getConstant(M, t) 47 | p := getConstant(P, t) 48 | 49 | state := make([]frontend.Variable, t) 50 | for j := 0; j < t; j++ { 51 | if j == 0 { 52 | state[0] = 0 53 | } else { 54 | state[j] = h.data[j-1] 55 | } 56 | } 57 | state = h.ark(state, c, 0) 58 | 59 | for r := 0; r < nRoundsF/2-1; r++ { 60 | for j := 0; j < t; j++ { 61 | state[j] = h.sigma(state[j]) 62 | } 63 | state = h.ark(state, c, (r+1)*t) 64 | state = h.mix(state, m) 65 | } 66 | 67 | for j := 0; j < t; j++ { 68 | state[j] = h.sigma(state[j]) 69 | } 70 | state = h.ark(state, c, nRoundsF/2*t) 71 | state = h.mix(state, p) 72 | 73 | for r := 0; r < nRoundsP; r++ { 74 | 75 | state[0] = h.sigma(state[0]) 76 | 77 | state[0] = h.api.Add(state[0], c[(nRoundsF/2+1)*t+r]) 78 | newState0 := frontend.Variable(0) 79 | for j := 0; j < len(state); j++ { 80 | mul := h.api.Mul(s[(t*2-1)*r+j], state[j]) 81 | newState0 = h.api.Add(newState0, mul) 82 | } 83 | 84 | for k := 1; k < t; k++ { 85 | state[k] = h.api.Add(state[k], h.api.Mul(state[0], s[(t*2-1)*r+t+k-1])) 86 | } 87 | state[0] = newState0 88 | } 89 | 90 | for r := 0; r < nRoundsF/2-1; r++ { 91 | for j := 0; j < t; j++ { 92 | state[j] = h.sigma(state[j]) 93 | } 94 | state = h.ark(state, c, (nRoundsF/2+1)*t+nRoundsP+r*t) 95 | state = h.mix(state, m) 96 | } 97 | 98 | for j := 0; j < t; j++ { 99 | state[j] = h.sigma(state[j]) 100 | } 101 | 102 | out := h.mixLast(state, m, 0) 103 | h.data = []frontend.Variable{} 104 | return out 105 | } 106 | 107 | func (h *Poseidon) sigma(in frontend.Variable) frontend.Variable { 108 | in2 := h.api.Mul(in, in) 109 | in4 := h.api.Mul(in2, in2) 110 | return h.api.Mul(in4, in) 111 | } 112 | 113 | func (h *Poseidon) ark(in []frontend.Variable, c []*big.Int, r int) []frontend.Variable { 114 | out := make([]frontend.Variable, len(in)) 115 | for i, v := range in { 116 | out[i] = h.api.Add(v, c[i+r]) 117 | } 118 | return out 119 | } 120 | 121 | func (h *Poseidon) mix(in []frontend.Variable, m [][]*big.Int) []frontend.Variable { 122 | t := len(in) 123 | out := make([]frontend.Variable, t) 124 | for i := 0; i < t; i++ { 125 | lc := frontend.Variable(0) 126 | for j := 0; j < t; j++ { 127 | lc = h.api.Add(lc, h.api.Mul(m[j][i], in[j])) 128 | } 129 | out[i] = lc 130 | } 131 | return out 132 | } 133 | 134 | func (h *Poseidon) mixLast(in []frontend.Variable, m [][]*big.Int, s int) frontend.Variable { 135 | t := len(in) 136 | out := frontend.Variable(0) 137 | for j := 0; j < t; j++ { 138 | out = h.api.Add(out, h.api.Mul(m[j][s], in[j])) 139 | } 140 | return out 141 | } 142 | -------------------------------------------------------------------------------- /std/hash/poseidon/poseidon_test.go: -------------------------------------------------------------------------------- 1 | package poseidon 2 | 3 | import ( 4 | "math/big" 5 | "testing" 6 | 7 | "github.com/consensys/gnark-crypto/ecc" 8 | "github.com/consensys/gnark/backend" 9 | "github.com/consensys/gnark/frontend" 10 | "github.com/consensys/gnark/test" 11 | hash "github.com/iden3/go-iden3-crypto/poseidon" 12 | ) 13 | 14 | type testPoseidonCiruit struct { 15 | Data frontend.Variable 16 | Hash frontend.Variable `gnark:",public"` 17 | } 18 | 19 | func (circuit *testPoseidonCiruit) Define(api frontend.API) error { 20 | h := Hash(api, circuit.Data) 21 | api.AssertIsEqual(h, circuit.Hash) 22 | return nil 23 | } 24 | 25 | func TestPoseidon(t *testing.T) { 26 | assert := test.NewAssert(t) 27 | 28 | var circuit, assignment testPoseidonCiruit 29 | 30 | input, _ := new(big.Int).SetString("297262668938251460872476410954775437897592223497", 10) 31 | assignment.Data = input 32 | assignment.Hash, _ = hash.Hash([]*big.Int{input}) 33 | 34 | assert.SolvingSucceeded(&circuit, &assignment, test.WithCurves(ecc.BN254), test.WithBackends(backend.PLONK)) 35 | } 36 | -------------------------------------------------------------------------------- /std/smt/utils.go: -------------------------------------------------------------------------------- 1 | package smt 2 | 3 | import ( 4 | "gnark-prover-tinygo/std/hash/poseidon" 5 | 6 | "github.com/consensys/gnark/frontend" 7 | ) 8 | 9 | // endLeafValue returns the encoded childless leaf value for the key-value pair 10 | // provided, hashing it with the predefined hashing function 'H': 11 | // 12 | // newLeafValue = H(key | value | 1) 13 | func endLeafValue(api frontend.API, key, value frontend.Variable) frontend.Variable { 14 | return poseidon.Hash(api, key, value, 1) 15 | } 16 | 17 | // intermediateLeafValue returns the encoded intermediate leaf value for the 18 | // key-value pair provided, hashing it with the predefined hashing function 'H': 19 | // 20 | // intermediateLeafValue = H(l | r) 21 | func intermediateLeafValue(api frontend.API, l, r frontend.Variable) frontend.Variable { 22 | return poseidon.Hash(api, l, r) 23 | } 24 | 25 | func switcher(api frontend.API, sel, l, r frontend.Variable) (outL, outR frontend.Variable) { 26 | // aux <== (R-L)*sel; 27 | aux := api.Mul(api.Sub(r, l), sel) 28 | // outL <== aux + L; 29 | outL = api.Add(aux, l) 30 | // outR <== -aux + R; 31 | outR = api.Sub(r, aux) 32 | return 33 | } 34 | 35 | func multiAnd(api frontend.API, inputs ...frontend.Variable) frontend.Variable { 36 | if len(inputs) == 0 { 37 | return 0 38 | } 39 | if len(inputs) == 1 { 40 | return inputs[0] 41 | } 42 | 43 | res := inputs[0] 44 | for i := 1; i < len(inputs); i++ { 45 | res = api.And(res, inputs[i]) 46 | } 47 | return res 48 | } 49 | -------------------------------------------------------------------------------- /std/smt/verifier.go: -------------------------------------------------------------------------------- 1 | // smt is a port of Circom SMTVerifier. It attempts to check a proof 2 | // of a Sparse Merkle Tree (compatible with Arbo Merkle Tree implementation). 3 | // Check the original implementation from Iden3: 4 | // - https://github.com/iden3/circomlib/tree/a8cdb6cd1ad652cca1a409da053ec98f19de6c9d/circuits/smt 5 | package smt 6 | 7 | import "github.com/consensys/gnark/frontend" 8 | 9 | func Verifier(api frontend.API, 10 | root, key, value frontend.Variable, siblings []frontend.Variable) error { 11 | return smtverifier(api, 1, root, 0, 0, 0, key, value, 0, siblings) 12 | } 13 | 14 | func smtverifier(api frontend.API, 15 | enabled, root, oldKey, oldValue, isOld0, key, value, fnc frontend.Variable, 16 | siblings []frontend.Variable) error { 17 | nLevels := len(siblings) 18 | 19 | // Steps: 20 | // 1. Get the hash of both key-value pairs, old and new one. 21 | // 2. Get the binary representation of the key new. 22 | // 3. Get the path of the current key. 23 | // 4. Calculate the root with the siblings provided. 24 | // 5. Compare the calculated root with the provided one. 25 | 26 | // [STEP 1] 27 | // hash1Old = H(oldKey | oldValue | 1) 28 | hash1Old := endLeafValue(api, oldKey, oldValue) 29 | // hash1New = H(key | value | 1) 30 | hash1New := endLeafValue(api, key, value) 31 | 32 | // [STEP 2] 33 | // component n2bNew = Num2Bits_strict(); 34 | // n2bNew.in <== key; 35 | n2bNew := api.ToBinary(key, api.Compiler().FieldBitLen()) 36 | 37 | // [STEP 3] 38 | // component smtLevIns = SMTLevIns(nLevels); 39 | // for (i=0; i 0; i-- { 145 | // levIns[i] = (1-isDone[i])*(1-isZero[i-1]) 146 | levIns[i] = api.Mul(api.Sub(1, isDone[i]), api.Sub(1, isZero[i-1])) 147 | // done[i-1] = levIns[i] + done[i] 148 | isDone[i-1] = api.Add(levIns[i], isDone[i]) 149 | } 150 | // levIns[0] <== (1-done[0]); 151 | levIns[0] = api.Sub(1, isDone[0]) 152 | 153 | return levIns 154 | } 155 | 156 | func smtVerifierSM(api frontend.API, 157 | is0, levIns, fnc, prevTop, prevI0, prevIold, prevInew, prevNa frontend.Variable) ( 158 | stTop, stIold, stI0, stInew, stNa frontend.Variable) { 159 | // prev_top_lev_ins <== prev_top * levIns; 160 | prevTopLevIns := api.Mul(prevTop, levIns) 161 | // prev_top_lev_ins_fnc <== prev_top_lev_ins*fnc 162 | prevTopLevInsFnc := api.Mul(prevTopLevIns, fnc) 163 | 164 | stTop = api.Sub(prevTop, prevTopLevIns) // st_top <== prev_top - prev_top_lev_ins 165 | stIold = api.Mul(prevTopLevInsFnc, api.Sub(1, is0)) // st_iold <== prev_top_lev_ins_fnc * (1 - is0) 166 | stI0 = api.Mul(prevTopLevIns, is0) // st_i0 <== prev_top_lev_ins * is0; 167 | stInew = api.Sub(prevTopLevIns, prevTopLevInsFnc) // st_inew <== prev_top_lev_ins - prev_top_lev_ins_fnc 168 | stNa = api.Add(prevNa, prevInew, prevIold, prevI0) // st_na <== prev_na + prev_inew + prev_iold + prev_i0 169 | return 170 | } 171 | 172 | func smtVerifierLevel(api frontend.API, stTop, stIold, stInew, sibling, 173 | old1leaf, new1leaf, lrbit, child frontend.Variable) frontend.Variable { 174 | // component switcher = Switcher(); 175 | // switcher.sel <== lrbit; 176 | // switcher.L <== child; 177 | // switcher.R <== sibling; 178 | l, r := switcher(api, lrbit, child, sibling) 179 | // component proofHash = SMTHash2(); 180 | // proofHash.L <== switcher.outL; 181 | // proofHash.R <== switcher.outR; 182 | proofHash := intermediateLeafValue(api, l, r) 183 | // aux[0] <== proofHash.out * st_top; 184 | aux0 := api.Mul(proofHash, stTop) 185 | // aux[1] <== old1leaf * st_iold; 186 | aux1 := api.Mul(old1leaf, stIold) 187 | // root <== aux[0] + aux[1] + new1leaf * st_inew; 188 | return api.Add(aux0, aux1, api.Mul(new1leaf, stInew)) 189 | } 190 | -------------------------------------------------------------------------------- /std/smt/verifier_test.go: -------------------------------------------------------------------------------- 1 | package smt 2 | 3 | import ( 4 | "gnark-prover-tinygo/internal/zkaddress" 5 | "math/big" 6 | "testing" 7 | 8 | "github.com/consensys/gnark-crypto/ecc" 9 | "github.com/consensys/gnark/backend" 10 | "github.com/consensys/gnark/frontend" 11 | "github.com/consensys/gnark/test" 12 | qt "github.com/frankban/quicktest" 13 | "go.vocdoni.io/dvote/db" 14 | "go.vocdoni.io/dvote/db/pebbledb" 15 | "go.vocdoni.io/dvote/tree/arbo" 16 | "go.vocdoni.io/dvote/util" 17 | ) 18 | 19 | type testVerifierCircuit struct { 20 | Root frontend.Variable 21 | Key frontend.Variable 22 | Value frontend.Variable 23 | Siblings [160]frontend.Variable 24 | } 25 | 26 | func (circuit *testVerifierCircuit) Define(api frontend.API) error { 27 | return Verifier(api, circuit.Root, circuit.Key, circuit.Value, circuit.Siblings[:]) 28 | } 29 | 30 | func successInputs(t *testing.T) testVerifierCircuit { 31 | c := qt.New(t) 32 | 33 | database, err := pebbledb.New(db.Options{Path: t.TempDir()}) 34 | c.Assert(err, qt.IsNil) 35 | arboTree, err := arbo.NewTree(arbo.Config{ 36 | Database: database, 37 | MaxLevels: 160, 38 | HashFunction: arbo.HashFunctionPoseidon, 39 | }) 40 | c.Assert(err, qt.IsNil) 41 | 42 | factoryWeight := big.NewInt(10) 43 | candidate, err := zkaddress.FromBytes(util.RandomBytes(32)) 44 | c.Assert(err, qt.IsNil) 45 | err = arboTree.Add(candidate.ArboBytes(), arbo.BigIntToBytes(arbo.HashFunctionPoseidon.Len(), factoryWeight)) 46 | c.Assert(err, qt.IsNil) 47 | 48 | for i := 0; i < 100; i++ { 49 | k, err := zkaddress.FromBytes(util.RandomBytes(32)) 50 | c.Assert(err, qt.IsNil) 51 | err = arboTree.Add(k.ArboBytes(), arbo.BigIntToBytes(arbo.HashFunctionPoseidon.Len(), factoryWeight)) 52 | c.Assert(err, qt.IsNil) 53 | } 54 | 55 | key, value, pSiblings, exist, err := arboTree.GenProof(candidate.ArboBytes()) 56 | c.Assert(err, qt.IsNil) 57 | c.Assert(exist, qt.IsTrue) 58 | c.Assert(key, qt.ContentEquals, candidate.ArboBytes()) 59 | c.Assert(value, qt.ContentEquals, arbo.BigIntToBytes(arbo.HashFunctionPoseidon.Len(), factoryWeight)) 60 | 61 | uSiblings, err := arbo.UnpackSiblings(arbo.HashFunctionPoseidon, pSiblings) 62 | c.Assert(err, qt.IsNil) 63 | 64 | siblings := [160]frontend.Variable{} 65 | for i := 0; i < 160; i++ { 66 | if i < len(uSiblings) { 67 | siblings[i] = arbo.BytesToBigInt(uSiblings[i]) 68 | } else { 69 | siblings[i] = big.NewInt(0) 70 | } 71 | } 72 | 73 | root, err := arboTree.Root() 74 | c.Assert(err, qt.IsNil) 75 | return testVerifierCircuit{ 76 | Root: arbo.BytesToBigInt(root), 77 | Key: candidate.Scalar, 78 | Value: factoryWeight, 79 | Siblings: siblings, 80 | } 81 | } 82 | 83 | func TestVerifier(t *testing.T) { 84 | assert := test.NewAssert(t) 85 | 86 | var circuit testVerifierCircuit 87 | inputs := successInputs(t) 88 | assert.SolvingSucceeded(&circuit, &inputs, test.WithCurves(ecc.BN254), test.WithBackends(backend.PLONK)) 89 | } 90 | -------------------------------------------------------------------------------- /std/zkaddress/zkaddress.go: -------------------------------------------------------------------------------- 1 | package zkaddress 2 | 3 | import ( 4 | "gnark-prover-tinygo/std/hash/poseidon" 5 | 6 | ecc "github.com/consensys/gnark-crypto/ecc/twistededwards" 7 | "github.com/consensys/gnark/frontend" 8 | "github.com/consensys/gnark/std/algebra/native/twistededwards" 9 | ) 10 | 11 | const DefaultZkAddressLen = 20 12 | 13 | type ZkAddress struct { 14 | Private frontend.Variable 15 | Public frontend.Variable 16 | Scalar frontend.Variable 17 | } 18 | 19 | func FromPrivate(api frontend.API, private frontend.Variable) (ZkAddress, error) { 20 | curve, err := twistededwards.NewEdCurve(api, ecc.BN254) 21 | if err != nil { 22 | return ZkAddress{}, err 23 | } 24 | 25 | base := twistededwards.Point{ 26 | X: curve.Params().Base[0], 27 | Y: curve.Params().Base[1], 28 | } 29 | point := curve.ScalarMul(base, private) 30 | public := poseidon.Hash(api, point.X, point.Y) 31 | 32 | bPublic := api.ToBinary(public, api.Compiler().FieldBitLen()) 33 | scalar := api.FromBinary(bPublic[:DefaultZkAddressLen*8]...) 34 | 35 | return ZkAddress{ 36 | Private: private, 37 | Public: public, 38 | Scalar: scalar, 39 | }, nil 40 | } 41 | -------------------------------------------------------------------------------- /std/zkaddress/zkaddress_test.go: -------------------------------------------------------------------------------- 1 | package zkaddress 2 | 3 | import ( 4 | "gnark-prover-tinygo/internal/zkaddress" 5 | "testing" 6 | 7 | "github.com/consensys/gnark-crypto/ecc" 8 | "github.com/consensys/gnark/backend" 9 | "github.com/consensys/gnark/frontend" 10 | "github.com/consensys/gnark/test" 11 | ) 12 | 13 | type testZkAddressCiruit struct { 14 | PrivateKey frontend.Variable 15 | PublicKey frontend.Variable `gnark:",public"` 16 | Scalar frontend.Variable `gnark:",public"` 17 | } 18 | 19 | func (circuit *testZkAddressCiruit) Define(api frontend.API) error { 20 | zkAddress, err := FromPrivate(api, circuit.PrivateKey) 21 | if err != nil { 22 | return err 23 | } 24 | 25 | api.AssertIsEqual(circuit.PrivateKey, zkAddress.Private) 26 | api.AssertIsEqual(circuit.PublicKey, zkAddress.Public) 27 | api.AssertIsEqual(circuit.Scalar, zkAddress.Scalar) 28 | return nil 29 | } 30 | 31 | func TestZkAddress(t *testing.T) { 32 | assert := test.NewAssert(t) 33 | 34 | seed := []byte("1b505cdafb4b1150b1a740633af41e5e1f19a5c4") 35 | zkAddr, err := zkaddress.FromBytes(seed) 36 | if err != nil { 37 | t.Error(err) 38 | } 39 | 40 | assignment := testZkAddressCiruit{ 41 | PublicKey: zkAddr.Public, 42 | PrivateKey: zkAddr.Private, 43 | Scalar: zkAddr.Scalar, 44 | } 45 | 46 | var circuit testZkAddressCiruit 47 | assert.SolvingSucceeded(&circuit, &assignment, test.WithCurves(ecc.BN254), test.WithBackends(backend.PLONK)) 48 | } 49 | -------------------------------------------------------------------------------- /wasi/main.go: -------------------------------------------------------------------------------- 1 | //go:build tinygo 2 | // +build tinygo 3 | 4 | package main 5 | 6 | import ( 7 | _ "embed" 8 | "fmt" 9 | "gnark-prover-tinygo/prover" 10 | ) 11 | 12 | //go:embed zkcensus.ccs 13 | var circuit []byte 14 | 15 | //go:embed zkcensus.pkey 16 | var epkey []byte 17 | 18 | func main() { 19 | c := make(chan interface{}) 20 | <-c 21 | } 22 | 23 | //export generateProof 24 | func GenerateProof(bwitness []byte) interface{} { 25 | if _, _, err := prover.GenerateProofGroth16(circuit, epkey, bwitness); err != nil { 26 | fmt.Println(err) 27 | return err.Error() 28 | } 29 | return nil 30 | } 31 | -------------------------------------------------------------------------------- /wasm/g16/main.go: -------------------------------------------------------------------------------- 1 | //go:build tinygo 2 | // +build tinygo 3 | 4 | package main 5 | 6 | import ( 7 | _ "embed" 8 | "fmt" 9 | "gnark-prover-tinygo/prover" 10 | "syscall/js" 11 | "time" 12 | ) 13 | 14 | //go:embed zkcensus.ccs 15 | var circuit []byte 16 | 17 | //go:embed zkcensus.pkey 18 | var epkey []byte 19 | 20 | func main() { 21 | c := make(chan int) 22 | js.Global().Set("generateProof", js.FuncOf(jsGenerateProof)) 23 | <-c 24 | } 25 | 26 | func jsGenerateProof(this js.Value, args []js.Value) interface{} { 27 | bwitness := make([]byte, args[0].Get("length").Int()) 28 | js.CopyBytesToGo(bwitness, args[0]) 29 | fmt.Println("Calling function GenerateProof") 30 | startTime := time.Now() 31 | if _, _, err := prover.GenerateProofGroth16(circuit, epkey, bwitness); err != nil { 32 | fmt.Println("Error calling function GenerateProof", err.Error()) 33 | return 0 34 | } 35 | elapsedTime := int(time.Now().Sub(startTime).Seconds() * 1000) 36 | return elapsedTime 37 | } 38 | -------------------------------------------------------------------------------- /wasm/plonk/main.go: -------------------------------------------------------------------------------- 1 | //go:build tinygo 2 | // +build tinygo 3 | 4 | package main 5 | 6 | import ( 7 | _ "embed" 8 | "fmt" 9 | "gnark-prover-tinygo/prover" 10 | "syscall/js" 11 | "time" 12 | ) 13 | 14 | //go:embed zkcensus.ccs 15 | var eccs []byte 16 | 17 | //go:embed zkcensus.srs 18 | var esrs []byte 19 | 20 | //go:embed zkcensus.pkey 21 | var epkey []byte 22 | 23 | func main() { 24 | c := make(chan int) 25 | js.Global().Set("generateProof", js.FuncOf(jsGenerateProof)) 26 | <-c 27 | } 28 | 29 | func jsGenerateProof(this js.Value, args []js.Value) interface{} { 30 | bwitness := make([]byte, args[0].Get("length").Int()) 31 | js.CopyBytesToGo(bwitness, args[0]) 32 | fmt.Println("Calling function GenerateProof") 33 | startTime := time.Now() 34 | if _, _, err := prover.GenerateProofPlonk(eccs, esrs, epkey, bwitness); err != nil { 35 | fmt.Println("Error calling function GenerateProof", err.Error()) 36 | return 0 37 | } 38 | elapsedTime := int(time.Now().Sub(startTime).Seconds() * 1000) 39 | return elapsedTime 40 | } 41 | --------------------------------------------------------------------------------