initialise

This commit is contained in:
Samuel JJ Gosling 2022-08-28 18:41:09 +00:00
commit ae4309e189
39 changed files with 11010 additions and 0 deletions

674
COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

133
README.md Normal file
View File

@ -0,0 +1,133 @@
# snarkjs: JavaScript implementation of zkSNARKs.
This is a JavaScript implementation of zkSNARK schemes. It allows the original 8points protocol
and the Groth Protocol (3 point only and 3 pairings)
This library allows to do the trusted setup, generate proofs and verify the proofs.
This library uses the compiled circuits generated by the jaz compiler.
### Tutorial.
A good starting point [is this tutorial](https://github.com/iden3/circom/blob/master/TUTORIAL.md)
Also this [video](https://www.youtube.com/watch?v=-9TJa1hVsKA) is a good starting point.
## Install.
```sh
npm install snarkjs
```
## Usage from command line.
```sh
snarkjs --help
```
Will show all the info in how to use the cli.
## Usage from javascript
### Import.
```js
const zkSnark = require("snarkjs");
```
### Load a circuit.
```js
// "myCircuit.cir" is the output of the jaz compiler
const circuitDef = JSON.parse(fs.readFileSync("myCircuit.cir", "utf8"));
const circuit = new zkSnark.Circuit(circuitDef);
```
### Inspect the circuit.
```js
// `signalId` can always be a number or an alias string
circuit.nConstraints; // number of constraints
circuit.nSignals; // number of signals
circuit.nPublic; // number of public signals (nOutputs + nPublicInputs)
// The array of signals is always sorted in this order:
// [ 1, outputs, publicInputs, privateInputs, internalSignals, constants]
// returns a,b and c coeficients of the `signalId` on a given `constraint`
circuit.a(constraint, signalId)
circuit.b(constraint, signalId)
circuit.c(constraint, signalId)
circuit.nOutputs // number of public outputs
circuit.pubInputs // number of public inputs
circuit.nPrvInputs // number of private inputs
circuit.nInputs // number of inputs ( nPublicInputs + nPrivateInputs)
circuit.nVars // number of variables ( not including constants (one is a variable) )
circuit.nSignals // number of signals ( including constants )
circuit.outputIdx(i) // returns the index of the i'th output
circuit.inputIdx(i) // returns the index of the i'th input
circuit.pubInputIdx(i) // returns the index of the i'th public input
circuit.prvInputIdx(i) // returns the index of the i'th private input
circuit.varIdx(i) // returns the index of the i'th variable
circuit.constantIdx(i) // returns the index of the i'th constant
circuit.signalIdx(i) // returns the index of the i'th signal
// returns signal Idx given a signalId
// if the idx >= n , it is a constant
// if the idx == -1, the signal does not exist
circuit.getSignalIdx(name);
// returns an array aliases names of the i'th signal
circuit.signalNames(i)
// input is a key value object where keys are the signal names
// of all the inputs (public and private)
// returns an array of values representing the witness
circuit.calculateWitness(input)
```
### Trusted setup.
```js
const setup = zkSnark.setup(circuit);
fs.writeFileSync("myCircuit.vk_proof", JSON.stringify(setup.vk_proof), "utf8");
fs.writeFileSync("myCircuit.vk_verifier", JSON.stringify(setup.vk_verifier), "utf8");
setup.toxic // Must be discarded.
```
### Generate proof.
```js
const circuitDef = JSON.parse(fs.readFileSync("myCircuit.cir", "utf8"));
const circuit = new zkSnark.Circuit(circuitDef);
const input = {
"main.pubIn1": "123",
"main.out1": "456"
}
const witness = circuit.calculateWitness(input);
const vk_proof = JSON.parse(fs.readFileSync("myCircuit.vk_proof", "utf8"));
const {proof, publicSignals} = zkSnark.genProof(vk_proof, witness);
```
### Verifier.
```js
const vk_verifier = JSON.parse(fs.readFileSync("myCircuit.vk_verifier", "utf8"));
if (zkSnark.isValid(vk_verifier, proof, publicSignals)) {
console.log("The proof is valid");
} else {
console.log("The proof is not valid");
}
```
## License
snarkjs is part of the iden3 project copyright 2018 0KIMS association and published with GPL-3 license. Please check the COPYING file for more details.

544
cli.js Normal file
View File

@ -0,0 +1,544 @@
#!/usr/bin/env node
/*
Copyright 2018 0KIMS association.
This file is part of jaz (Zero Knowledge Circuit Compiler).
jaz is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jaz is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with jaz. If not, see <https://www.gnu.org/licenses/>.
*/
/* eslint-disable no-console */
const fs = require("fs");
const path = require("path");
const zkSnark = require("./index.js");
const {stringifyBigInts, unstringifyBigInts} = require("./src/stringifybigint.js");
const version = require("./package").version;
const argv = require("yargs")
.version(version)
.usage(`snarkjs <command> <options>
setup command
=============
snarkjs setup <option>
Runs a setup for a circuit generating the proving and the verification key.
-c or --circuit <circuitFile>
Filename of the compiled circuit file generated by circom.
Default: circuit.json
--pk or --provingkey <provingKeyFile>
Output filename where the proving key will be stored.
Default: proving_key.json
--vk or --verificationkey <verificationKeyFile>
Output Filename where the verification key will be stored.
Default: verification_key.json
--protocol [original|groth|kimleeoh]
Defines which variant of snark you want to use
Default: original
calculate witness command
=========================
snarkjs calculatewitness <options>
Calculate the witness of a circuit given an input.
-c or --circuit <circuitFile>
Filename of the compiled circuit file generated by circom.
Default: circuit.json
-i or --input <inputFile>
JSON file with the inputs of the circuit.
Default: input.json
Example of a circuit with two inputs a and b:
{"a": "22", "b": "33"}
-w or --witness
Output filename with the generated witness.
Default: witness.json
--lo or --logoutput
Output all the Output signals
--lg or --logget
Output GET access to the signals
--ls or --logset
Output SET access to the signal
--lt or --logtrigger
Output when a subcomponent is triggered and when finished
generate a proof command
========================
snarkjs proof <options>
-w or --witness
Input filename used to calculate the proof.
Default: witness.json
--pk or --provingkey <provingKeyFile>
Input filename with the proving key (generated during the setup).
Default: proving_key.json
-p or --proof
Output filenam with the zero knowlage proof.
Default: proof.json
--pub or --public <publicFilename>
Output filename with the value of the public wires/signals.
This info will be needed to verify the proof.
Default: public.json
verify command
==============
snarkjs verify <options>
The command returns "OK" if the proof is valid
and "INVALID" in case it is not a valid proof.
--vk or --verificationkey <verificationKeyFile>
Input Filename with the verification key (generated during the setup).
Default: verification_key.json
-p or --proof
Input filenam with the zero knowlage proof you want to verify
Default: proof.json
--pub or --public <publicFilename>
Input filename with the public wires/signals.
Default: public.json
generate solidity verifier command
==================================
snarkjs generateverifier <options>
Generates a solidity smart contract that verifies the zero knowlage proof.
--vk or --verificationkey <verificationKeyFile>
Input Filename with the verification key (generated during the setup).
Default: verification_key.json
-v or --verifier
Output file with a solidity smart contract that verifies a zero knowlage proof.
Default: verifier.sol
generate call parameters
========================
snarkjs generatecall <options>
Outputs into the console the raw parameters to be used in 'verifyProof'
method of the solidity verifier function.
-p or --proof
Input filename with the zero knowlage proof you want to use
Default: proof.json
--pub or --public <publicFilename>
Input filename with the public wires/signals.
Default: public.json
circuit info
============
snarkjs info <options>
Print statistics of a circuit
-c or --circuit <circuitFile>
Filename of the compiled circuit file generated by circom.
Default: circuit.json
print constraints
=================
snarkjs printconstraints <options>
Print all the constraints of a given circuit
-c or --circuit <circuitFile>
Filename of the compiled circuit file generated by circom.
Default: circuit.json
`)
.alias("c", "circuit")
.alias("pk", "provingkey")
.alias("vk", "verificationkey")
.alias("w", "witness")
.alias("p", "proof")
.alias("i", "input")
.alias("pub", "public")
.alias("v", "verifier")
.alias("lo", "logoutput")
.alias("lg", "logget")
.alias("ls", "logset")
.alias("lt", "logtrigger")
.help("h")
.alias("h", "help")
.epilogue(`Copyright (C) 2018 0kims association
This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it
under certain conditions; see the COPYING file in the official
repo directory at https://github.com/iden3/circom `)
.argv;
const circuitName = (argv.circuit) ? argv.circuit : "circuit.json";
const provingKeyName = (argv.provingkey) ? argv.provingkey : "proving_key.json";
const verificationKeyName = (argv.verificationkey) ? argv.verificationkey : "verification_key.json";
const inputName = (argv.input) ? argv.input : "input.json";
const witnessName = (argv.witness) ? argv.witness : "witness.json";
const proofName = (argv.proof) ? argv.proof : "proof.json";
const publicName = (argv.public) ? argv.public : "public.json";
const verifierName = (argv.verifier) ? argv.verifier : "verifier.sol";
const protocol = (argv.protocol) ? argv.protocol : "original";
function p256(n) {
let nstr = n.toString(16);
while (nstr.length < 64) nstr = "0"+nstr;
nstr = `"0x${nstr}"`;
return nstr;
}
try {
if (argv._[0].toUpperCase() == "INFO") {
const cirDef = JSON.parse(fs.readFileSync(circuitName, "utf8"));
const cir = new zkSnark.Circuit(cirDef);
console.log(`# Wires: ${cir.nVars}`);
console.log(`# Constraints: ${cir.nConstraints}`);
console.log(`# Private Inputs: ${cir.nPrvInputs}`);
console.log(`# Public Inputs: ${cir.nPubInputs}`);
console.log(`# Outputs: ${cir.nOutputs}`);
} else if (argv._[0].toUpperCase() == "PRINTCONSTRAINTS") {
const cirDef = JSON.parse(fs.readFileSync(circuitName, "utf8"));
const cir = new zkSnark.Circuit(cirDef);
cir.printConstraints();
} else if (argv._[0].toUpperCase() == "SETUP") {
const cirDef = JSON.parse(fs.readFileSync(circuitName, "utf8"));
const cir = new zkSnark.Circuit(cirDef);
if (!zkSnark[protocol]) throw new Error("Invalid protocol");
const setup = zkSnark[protocol].setup(cir);
fs.writeFileSync(provingKeyName, JSON.stringify(stringifyBigInts(setup.vk_proof), null, 1), "utf-8");
fs.writeFileSync(verificationKeyName, JSON.stringify(stringifyBigInts(setup.vk_verifier), null, 1), "utf-8");
process.exit(0);
} else if (argv._[0].toUpperCase() == "CALCULATEWITNESS") {
const cirDef = JSON.parse(fs.readFileSync(circuitName, "utf8"));
const cir = new zkSnark.Circuit(cirDef);
const input = unstringifyBigInts(JSON.parse(fs.readFileSync(inputName, "utf8")));
const witness = cir.calculateWitness(input, {
logOutput: argv.logoutput,
logSet: argv.logset,
logGet: argv.logget,
logTrigger: argv.logtrigger
});
fs.writeFileSync(witnessName, JSON.stringify(stringifyBigInts(witness), null, 1), "utf-8");
process.exit(0);
} else if (argv._[0].toUpperCase() == "PROOF") {
const witness = unstringifyBigInts(JSON.parse(fs.readFileSync(witnessName, "utf8")));
const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync(provingKeyName, "utf8")));
const protocol = provingKey.protocol;
if (!zkSnark[protocol]) throw new Error("Invalid protocol");
const {proof, publicSignals} = zkSnark[protocol].genProof(provingKey, witness);
fs.writeFileSync(proofName, JSON.stringify(stringifyBigInts(proof), null, 1), "utf-8");
fs.writeFileSync(publicName, JSON.stringify(stringifyBigInts(publicSignals), null, 1), "utf-8");
process.exit(0);
} else if (argv._[0].toUpperCase() == "VERIFY") {
const public = unstringifyBigInts(JSON.parse(fs.readFileSync(publicName, "utf8")));
const verificationKey = unstringifyBigInts(JSON.parse(fs.readFileSync(verificationKeyName, "utf8")));
const proof = unstringifyBigInts(JSON.parse(fs.readFileSync(proofName, "utf8")));
const protocol = verificationKey.protocol;
if (!zkSnark[protocol]) throw new Error("Invalid protocol");
const isValid = zkSnark[protocol].isValid(verificationKey, proof, public);
if (isValid) {
console.log("OK");
process.exit(0);
} else {
console.log("INVALID");
process.exit(1);
}
} else if (argv._[0].toUpperCase() == "GENERATEVERIFIER") {
const verificationKey = unstringifyBigInts(JSON.parse(fs.readFileSync(verificationKeyName, "utf8")));
let verifierCode;
if (verificationKey.protocol == "original") {
verifierCode = generateVerifier_original(verificationKey);
} else if (verificationKey.protocol == "groth") {
verifierCode = generateVerifier_groth(verificationKey);
} else if (verificationKey.protocol == "kimleeoh") {
verifierCode = generateVerifier_kimleeoh(verificationKey);
} else {
throw new Error("InvalidProof");
}
fs.writeFileSync(verifierName, verifierCode, "utf-8");
process.exit(0);
} else if (argv._[0].toUpperCase() == "GENERATECALL") {
const public = unstringifyBigInts(JSON.parse(fs.readFileSync(publicName, "utf8")));
const proof = unstringifyBigInts(JSON.parse(fs.readFileSync(proofName, "utf8")));
let inputs = "";
for (let i=0; i<public.length; i++) {
if (inputs != "") inputs = inputs + ",";
inputs = inputs + p256(public[i]);
}
let S;
if ((typeof proof.protocol === "undefined") || (proof.protocol == "original")) {
S=`[${p256(proof.pi_a[0])}, ${p256(proof.pi_a[1])}],` +
`[${p256(proof.pi_ap[0])}, ${p256(proof.pi_ap[1])}],` +
`[[${p256(proof.pi_b[0][1])}, ${p256(proof.pi_b[0][0])}],[${p256(proof.pi_b[1][1])}, ${p256(proof.pi_b[1][0])}]],` +
`[${p256(proof.pi_bp[0])}, ${p256(proof.pi_bp[1])}],` +
`[${p256(proof.pi_c[0])}, ${p256(proof.pi_c[1])}],` +
`[${p256(proof.pi_cp[0])}, ${p256(proof.pi_cp[1])}],` +
`[${p256(proof.pi_h[0])}, ${p256(proof.pi_h[1])}],` +
`[${p256(proof.pi_kp[0])}, ${p256(proof.pi_kp[1])}],` +
`[${inputs}]`;
} else if ((proof.protocol == "groth")||(proof.protocol == "kimleeoh")) {
S=`[${p256(proof.pi_a[0])}, ${p256(proof.pi_a[1])}],` +
`[[${p256(proof.pi_b[0][1])}, ${p256(proof.pi_b[0][0])}],[${p256(proof.pi_b[1][1])}, ${p256(proof.pi_b[1][0])}]],` +
`[${p256(proof.pi_c[0])}, ${p256(proof.pi_c[1])}],` +
`[${inputs}]`;
} else {
throw new Error("InvalidProof");
}
console.log(S);
process.exit(0);
} else {
throw new Error("Invalid Command");
}
} catch(err) {
console.log(err.stack);
console.log("ERROR: " + err);
process.exit(1);
}
function generateVerifier_original(verificationKey) {
let template = fs.readFileSync(path.join( __dirname, "templates", "verifier_original.sol"), "utf-8");
const vka_str = `[${verificationKey.vk_a[0][1].toString()},`+
`${verificationKey.vk_a[0][0].toString()}], `+
`[${verificationKey.vk_a[1][1].toString()},` +
`${verificationKey.vk_a[1][0].toString()}]`;
template = template.replace("<%vk_a%>", vka_str);
const vkb_str = `${verificationKey.vk_b[0].toString()},`+
`${verificationKey.vk_b[1].toString()}`;
template = template.replace("<%vk_b%>", vkb_str);
const vkc_str = `[${verificationKey.vk_c[0][1].toString()},`+
`${verificationKey.vk_c[0][0].toString()}], `+
`[${verificationKey.vk_c[1][1].toString()},` +
`${verificationKey.vk_c[1][0].toString()}]`;
template = template.replace("<%vk_c%>", vkc_str);
const vkg_str = `[${verificationKey.vk_g[0][1].toString()},`+
`${verificationKey.vk_g[0][0].toString()}], `+
`[${verificationKey.vk_g[1][1].toString()},` +
`${verificationKey.vk_g[1][0].toString()}]`;
template = template.replace("<%vk_g%>", vkg_str);
const vkgb1_str = `${verificationKey.vk_gb_1[0].toString()},`+
`${verificationKey.vk_gb_1[1].toString()}`;
template = template.replace("<%vk_gb1%>", vkgb1_str);
const vkgb2_str = `[${verificationKey.vk_gb_2[0][1].toString()},`+
`${verificationKey.vk_gb_2[0][0].toString()}], `+
`[${verificationKey.vk_gb_2[1][1].toString()},` +
`${verificationKey.vk_gb_2[1][0].toString()}]`;
template = template.replace("<%vk_gb2%>", vkgb2_str);
const vkz_str = `[${verificationKey.vk_z[0][1].toString()},`+
`${verificationKey.vk_z[0][0].toString()}], `+
`[${verificationKey.vk_z[1][1].toString()},` +
`${verificationKey.vk_z[1][0].toString()}]`;
template = template.replace("<%vk_z%>", vkz_str);
// The points
template = template.replace(/<%vk_input_length%>/g, (verificationKey.IC.length-1).toString());
template = template.replace("<%vk_ic_length%>", verificationKey.IC.length.toString());
let vi = "";
for (let i=0; i<verificationKey.IC.length; i++) {
if (vi != "") vi = vi + " ";
vi = vi + `vk.IC[${i}] = Pairing.G1Point(${verificationKey.IC[i][0].toString()},`+
`${verificationKey.IC[i][1].toString()});\n`;
}
template = template.replace("<%vk_ic_pts%>", vi);
return template;
}
function generateVerifier_groth(verificationKey) {
let template = fs.readFileSync(path.join( __dirname, "templates", "verifier_groth.sol"), "utf-8");
const vkalfa1_str = `${verificationKey.vk_alfa_1[0].toString()},`+
`${verificationKey.vk_alfa_1[1].toString()}`;
template = template.replace("<%vk_alfa1%>", vkalfa1_str);
const vkbeta2_str = `[${verificationKey.vk_beta_2[0][1].toString()},`+
`${verificationKey.vk_beta_2[0][0].toString()}], `+
`[${verificationKey.vk_beta_2[1][1].toString()},` +
`${verificationKey.vk_beta_2[1][0].toString()}]`;
template = template.replace("<%vk_beta2%>", vkbeta2_str);
const vkgamma2_str = `[${verificationKey.vk_gamma_2[0][1].toString()},`+
`${verificationKey.vk_gamma_2[0][0].toString()}], `+
`[${verificationKey.vk_gamma_2[1][1].toString()},` +
`${verificationKey.vk_gamma_2[1][0].toString()}]`;
template = template.replace("<%vk_gamma2%>", vkgamma2_str);
const vkdelta2_str = `[${verificationKey.vk_delta_2[0][1].toString()},`+
`${verificationKey.vk_delta_2[0][0].toString()}], `+
`[${verificationKey.vk_delta_2[1][1].toString()},` +
`${verificationKey.vk_delta_2[1][0].toString()}]`;
template = template.replace("<%vk_delta2%>", vkdelta2_str);
// The points
template = template.replace(/<%vk_input_length%>/g, (verificationKey.IC.length-1).toString());
template = template.replace("<%vk_ic_length%>", verificationKey.IC.length.toString());
let vi = "";
for (let i=0; i<verificationKey.IC.length; i++) {
if (vi != "") vi = vi + " ";
vi = vi + `vk.IC[${i}] = Pairing.G1Point(${verificationKey.IC[i][0].toString()},`+
`${verificationKey.IC[i][1].toString()});\n`;
}
template = template.replace("<%vk_ic_pts%>", vi);
return template;
}
function generateVerifier_kimleeoh(verificationKey) {
let template = fs.readFileSync(path.join( __dirname, "templates", "verifier_groth.sol"), "utf-8");
const vkalfa1_str = `${verificationKey.vk_alfa_1[0].toString()},`+
`${verificationKey.vk_alfa_1[1].toString()}`;
template = template.replace("<%vk_alfa1%>", vkalfa1_str);
const vkbeta2_str = `[${verificationKey.vk_beta_2[0][1].toString()},`+
`${verificationKey.vk_beta_2[0][0].toString()}], `+
`[${verificationKey.vk_beta_2[1][1].toString()},` +
`${verificationKey.vk_beta_2[1][0].toString()}]`;
template = template.replace("<%vk_beta2%>", vkbeta2_str);
const vkgamma2_str = `[${verificationKey.vk_gamma_2[0][1].toString()},`+
`${verificationKey.vk_gamma_2[0][0].toString()}], `+
`[${verificationKey.vk_gamma_2[1][1].toString()},` +
`${verificationKey.vk_gamma_2[1][0].toString()}]`;
template = template.replace("<%vk_gamma2%>", vkgamma2_str);
const vkdelta2_str = `[${verificationKey.vk_delta_2[0][1].toString()},`+
`${verificationKey.vk_delta_2[0][0].toString()}], `+
`[${verificationKey.vk_delta_2[1][1].toString()},` +
`${verificationKey.vk_delta_2[1][0].toString()}]`;
template = template.replace("<%vk_delta2%>", vkdelta2_str);
// The points
template = template.replace(/<%vk_input_length%>/g, (verificationKey.IC.length-1).toString());
template = template.replace("<%vk_ic_length%>", verificationKey.IC.length.toString());
let vi = "";
for (let i=0; i<verificationKey.IC.length; i++) {
if (vi != "") vi = vi + " ";
vi = vi + `vk.IC[${i}] = Pairing.G1Point(${verificationKey.IC[i][0].toString()},`+
`${verificationKey.IC[i][1].toString()});\n`;
}
template = template.replace("<%vk_ic_pts%>", vi);
return template;
}

44
index.js Normal file
View File

@ -0,0 +1,44 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
exports.Circuit = require("./src/circuit.js");
exports.original = {
setup: require("./src/setup_original.js"),
genProof: require("./src/prover_original.js"),
isValid: require("./src/verifier_original.js")
};
exports.groth = {
setup: require("./src/setup_groth.js"),
genProof: require("./src/prover_groth.js"),
isValid: require("./src/verifier_groth.js")
};
exports.kimleeoh = {
setup: require("./src/setup_kimleeoh.js"),
genProof: require("./src/prover_kimleeoh.js"),
isValid: require("./src/verifier_kimleeoh.js")
};
exports.bigInt = require("./src/bigint.js");
exports.ZqField = require("./src/zqfield.js");
exports.stringifyBigInts = require("./src/stringifybigint.js").stringifyBigInts;
exports.unstringifyBigInts = require("./src/stringifybigint.js").unstringifyBigInts;
const Bn128 = require("./src/bn128.js");
exports.bn128 = new Bn128();

1330
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

42
package.json Normal file
View File

@ -0,0 +1,42 @@
{
"name": "snarkjs",
"version": "0.1.20",
"description": "zkSNARKs implementation in JavaScript",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"bin": {
"snarkjs": "cli.js"
},
"directories": {
"templates": "templates"
},
"keywords": [
"zksnark",
"zcash",
"ethereum",
"zero",
"knowlage",
"cryptography",
"circuit"
],
"author": "Jordi Baylina",
"license": "GPL-3.0",
"repository": {
"type": "git",
"url": "https://github.com/iden3/snarkjs.git"
},
"dependencies": {
"big-integer": "^1.6.43",
"chai": "^4.2.0",
"escape-string-regexp": "^1.0.5",
"eslint": "^5.16.0",
"keccak": "^2.0.0",
"yargs": "^12.0.5"
},
"devDependencies": {
"eslint-plugin-mocha": "^5.3.0",
"mocha": "^5.2.0"
}
}

522
src/bigint.js Normal file
View File

@ -0,0 +1,522 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* global BigInt */
const bigInt = require("big-integer");
let wBigInt;
if (typeof(BigInt) != "undefined") {
wBigInt = BigInt;
wBigInt.one = wBigInt(1);
wBigInt.zero = wBigInt(0);
// Affine
wBigInt.genAffine = (q) => {
const nq = -q;
return (a) => {
let aux = a;
if (aux < 0) {
if (aux <= nq) {
aux = aux % q;
}
if (aux < wBigInt.zero) {
aux = aux + q;
}
} else {
if (aux >= q) {
aux = aux % q;
}
}
return aux.valueOf();
};
};
// Inverse
wBigInt.genInverse = (q) => {
return (a) => {
let t = wBigInt.zero;
let r = q;
let newt = wBigInt.one;
let newr = wBigInt.affine(a, q);
while (newr!=wBigInt.zero) {
let q = r/newr;
[t, newt] = [newt, t-q*newt];
[r, newr] = [newr, r-q*newr];
}
if (t<wBigInt.zero) t += q;
return t;
};
};
// Add
wBigInt.genAdd = (q) => {
if (q) {
return (a,b) => (a+b) % q;
} else {
return (a,b) => a+b;
}
};
// Sub
wBigInt.genSub = (q) => {
if (q) {
return (a,b) => (a-b) % q;
} else {
return (a,b) => a-b;
}
};
// Neg
wBigInt.genNeg = (q) => {
if (q) {
return (a) => (-a) % q;
} else {
return (a) => -a;
}
};
// Mul
wBigInt.genMul = (q) => {
if (q) {
return (a,b) => (a*b) % q;
} else {
return (a,b) => a*b;
}
};
// Shr
wBigInt.genShr = () => {
return (a,b) => a >> wBigInt(b);
};
// Shl
wBigInt.genShl = (q) => {
if (q) {
return (a,b) => (a << wBigInt(b)) % q;
} else {
return (a,b) => a << wBigInt(b);
}
};
// Equals
wBigInt.genEquals = (q) => {
if (q) {
return (a,b) => (a.affine(q) == b.affine(q));
} else {
return (a,b) => a == b;
}
};
// Square
wBigInt.genSquare = (q) => {
if (q) {
return (a) => (a*a) %q;
} else {
return (a) => a*a;
}
};
// Double
wBigInt.genDouble = (q) => {
if (q) {
return (a) => (a+a) %q;
} else {
return (a) => a+a;
}
};
// IsZero
wBigInt.genIsZero = (q) => {
if (q) {
return (a) => (a.affine(q) == wBigInt.zero);
} else {
return (a) => a == wBigInt.zero;
}
};
// Other minor functions
wBigInt.prototype.isOdd = function() {
return (this & wBigInt.one) == wBigInt(1);
};
wBigInt.prototype.isNegative = function() {
return this < wBigInt.zero;
};
wBigInt.prototype.and = function(m) {
return this & m;
};
wBigInt.prototype.div = function(c) {
return this / c;
};
wBigInt.prototype.mod = function(c) {
return this % c;
};
wBigInt.prototype.pow = function(c) {
return this ** c;
};
wBigInt.prototype.abs = function() {
return (this > wBigInt.zero) ? this : -this;
};
wBigInt.prototype.modPow = function(e, m) {
let acc = wBigInt.one;
let exp = this;
let rem = e;
while (rem) {
if (rem & wBigInt.one) {
acc = (acc * exp) %m;
}
exp = (exp * exp) % m;
rem = rem >> wBigInt.one;
}
return acc;
};
wBigInt.prototype.greaterOrEquals = function(b) {
return this >= b;
};
wBigInt.prototype.greater = function(b) {
return this > b;
};
wBigInt.prototype.gt = wBigInt.prototype.greater;
wBigInt.prototype.lesserOrEquals = function(b) {
return this <= b;
};
wBigInt.prototype.lesser = function(b) {
return this < b;
};
wBigInt.prototype.lt = wBigInt.prototype.lesser;
wBigInt.prototype.equals = function(b) {
return this == b;
};
wBigInt.prototype.eq = wBigInt.prototype.equals;
wBigInt.prototype.neq = function(b) {
return this != b;
};
wBigInt.prototype.toJSNumber = function() {
return Number(this);
};
} else {
var oldProto = bigInt.prototype;
wBigInt = function(a) {
if ((typeof a == "string") && (a.slice(0,2) == "0x")) {
return bigInt(a.slice(2), 16);
} else {
return bigInt(a);
}
};
wBigInt.one = bigInt.one;
wBigInt.zero = bigInt.zero;
wBigInt.prototype = oldProto;
wBigInt.prototype.div = function(c) {
return this.divide(c);
};
// Affine
wBigInt.genAffine = (q) => {
const nq = wBigInt.zero.minus(q);
return (a) => {
let aux = a;
if (aux.isNegative()) {
if (aux.lesserOrEquals(nq)) {
aux = aux.mod(q);
}
if (aux.isNegative()) {
aux = aux.add(q);
}
} else {
if (aux.greaterOrEquals(q)) {
aux = aux.mod(q);
}
}
return aux;
};
};
// Inverse
wBigInt.genInverse = (q) => {
return (a) => a.affine(q).modInv(q);
};
// Add
wBigInt.genAdd = (q) => {
if (q) {
return (a,b) => {
const r = a.add(b);
return r.greaterOrEquals(q) ? r.minus(q) : r;
};
} else {
return (a,b) => a.add(b);
}
};
// Sub
wBigInt.genSub = (q) => {
if (q) {
return (a,b) => a.greaterOrEquals(b) ? a.minus(b) : a.minus(b).add(q);
} else {
return (a,b) => a.minus(b);
}
};
wBigInt.genNeg = (q) => {
if (q) {
return (a) => a.isZero() ? a : q.minus(a);
} else {
return (a) => wBigInt.zero.minus(a);
}
};
// Mul
wBigInt.genMul = (q) => {
if (q) {
return (a,b) => a.times(b).mod(q);
} else {
return (a,b) => a.times(b);
}
};
// Shr
wBigInt.genShr = () => {
return (a,b) => a.shiftRight(wBigInt(b).value);
};
// Shr
wBigInt.genShl = (q) => {
if (q) {
return (a,b) => a.shiftLeft(wBigInt(b).value).mod(q);
} else {
return (a,b) => a.shiftLeft(wBigInt(b).value);
}
};
// Square
wBigInt.genSquare = (q) => {
if (q) {
return (a) => a.square().mod(q);
} else {
return (a) => a.square();
}
};
// Double
wBigInt.genDouble = (q) => {
if (q) {
return (a) => a.add(a).mod(q);
} else {
return (a) => a.add(a);
}
};
// Equals
wBigInt.genEquals = (q) => {
if (q) {
return (a,b) => a.affine(q).equals(b.affine(q));
} else {
return (a,b) => a.equals(b);
}
};
// IsZero
wBigInt.genIsZero = (q) => {
if (q) {
return (a) => (a.affine(q).isZero());
} else {
return (a) => a.isZero();
}
};
}
wBigInt.affine = function(a, q) {
return wBigInt.genAffine(q)(a);
};
wBigInt.prototype.affine = function (q) {
return wBigInt.affine(this, q);
};
wBigInt.inverse = function(a, q) {
return wBigInt.genInverse(q)(a);
};
wBigInt.prototype.inverse = function (q) {
return wBigInt.genInverse(q)(this);
};
wBigInt.add = function(a, b, q) {
return wBigInt.genAdd(q)(a,b);
};
wBigInt.prototype.add = function (a, q) {
return wBigInt.genAdd(q)(this, a);
};
wBigInt.sub = function(a, b, q) {
return wBigInt.genSub(q)(a,b);
};
wBigInt.prototype.sub = function (a, q) {
return wBigInt.genSub(q)(this, a);
};
wBigInt.neg = function(a, q) {
return wBigInt.genNeg(q)(a);
};
wBigInt.prototype.neg = function (q) {
return wBigInt.genNeg(q)(this);
};
wBigInt.mul = function(a, b, q) {
return wBigInt.genMul(q)(a,b);
};
wBigInt.prototype.mul = function (a, q) {
return wBigInt.genMul(q)(this, a);
};
wBigInt.shr = function(a, b, q) {
return wBigInt.genShr(q)(a,b);
};
wBigInt.prototype.shr = function (a, q) {
return wBigInt.genShr(q)(this, a);
};
wBigInt.shl = function(a, b, q) {
return wBigInt.genShl(q)(a,b);
};
wBigInt.prototype.shl = function (a, q) {
return wBigInt.genShl(q)(this, a);
};
wBigInt.equals = function(a, b, q) {
return wBigInt.genEquals(q)(a,b);
};
wBigInt.prototype.equals = function (a, q) {
return wBigInt.genEquals(q)(this, a);
};
wBigInt.square = function(a, q) {
return wBigInt.genSquare(q)(a);
};
wBigInt.prototype.square = function (q) {
return wBigInt.genSquare(q)(this);
};
wBigInt.double = function(a, q) {
return wBigInt.genDouble(q)(a);
};
wBigInt.prototype.double = function (q) {
return wBigInt.genDouble(q)(this);
};
wBigInt.isZero = function(a, q) {
return wBigInt.genIsZero(q)(a);
};
wBigInt.prototype.isZero = function (q) {
return wBigInt.genIsZero(q)(this);
};
wBigInt.leBuff2int = function(buff) {
let res = wBigInt.zero;
for (let i=0; i<buff.length; i++) {
const n = wBigInt(buff[i]);
res = res.add(n.shl(i*8));
}
return res;
};
wBigInt.leInt2Buff = function(n, len) {
let r = n;
let o =0;
const buff = Buffer.alloc(len);
while ((r.greater(wBigInt.zero))&&(o<buff.length)) {
let c = Number(r.and(wBigInt("255")));
buff[o] = c;
o++;
r = r.shr(8);
}
if (r.greater(wBigInt.zero)) throw new Error("Number does not feed in buffer");
return buff;
};
wBigInt.prototype.leInt2Buff = function (len) {
return wBigInt.leInt2Buff(this,len);
};
wBigInt.beBuff2int = function(buff) {
let res = wBigInt.zero;
for (let i=0; i<buff.length; i++) {
const n = wBigInt(buff[buff.length - i - 1]);
res = res.add(n.shl(i*8));
}
return res;
};
wBigInt.beInt2Buff = function(n, len) {
let r = n;
let o =len-1;
const buff = Buffer.alloc(len);
while ((r.greater(wBigInt.zero))&&(o>=0)) {
let c = Number(r.and(wBigInt("255")));
buff[o] = c;
o--;
r = r.shr(8);
}
if (r.greater(wBigInt.zero)) throw new Error("Number does not feed in buffer");
return buff;
};
wBigInt.prototype.beInt2Buff = function (len) {
return wBigInt.beInt2Buff(this,len);
};
module.exports = wBigInt;

445
src/bn128.js Normal file
View File

@ -0,0 +1,445 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint.js");
const F1Field = require("./zqfield.js");
const F2Field = require("./f2field.js");
const F3Field = require("./f3field.js");
const GCurve = require("./gcurve.js");
class BN128 {
constructor() {
this.q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583");
this.r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
this.g1 = [ bigInt(1), bigInt(2), bigInt(1)];
this.g2 = [
[
bigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),
bigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")
],
[
bigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),
bigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")
],
[
bigInt("1"),
bigInt("0")
]
];
this.nonResidueF2 = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208582");
this.nonResidueF6 = [ bigInt("9"), bigInt("1") ];
this.F1 = new F1Field(this.q);
this.F2 = new F2Field(this.F1, this.nonResidueF2);
this.G1 = new GCurve(this.F1, this.g1);
this.G2 = new GCurve(this.F2, this.g2);
this.F6 = new F3Field(this.F2, this.nonResidueF6);
this.F12 = new F2Field(this.F6, this.nonResidueF6);
this.Fr = new F1Field(this.r);
const self = this;
this.F12._mulByNonResidue = function(a) {
return [self.F2.mul(this.nonResidue, a[2]), a[0], a[1]];
};
this._preparePairing();
}
_preparePairing() {
this.loopCount = bigInt("29793968203157093288");// CONSTANT
// Set loopCountNeg
if (this.loopCount.isNegative()) {
this.loopCount = this.loopCount.neg();
this.loopCountNeg = true;
} else {
this.loopCountNeg = false;
}
// Set loop_count_bits
let lc = this.loopCount;
this.loop_count_bits = []; // Constant
while (!lc.isZero()) {
this.loop_count_bits.push( lc.isOdd() );
lc = lc.shr(1);
}
this.two_inv = this.F1.inverse(bigInt(2));
this.coef_b = bigInt(3);
this.twist = [bigInt(9) , bigInt(1)];
this.twist_coeff_b = this.F2.mulScalar( this.F2.inverse(this.twist), this.coef_b );
this.frobenius_coeffs_c1_1 = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208582");
this.twist_mul_by_q_X =
[
bigInt("21575463638280843010398324269430826099269044274347216827212613867836435027261"),
bigInt("10307601595873709700152284273816112264069230130616436755625194854815875713954")
];
this.twist_mul_by_q_Y =
[
bigInt("2821565182194536844548159561693502659359617185244120367078079554186484126554"),
bigInt("3505843767911556378687030309984248845540243509899259641013678093033130930403")
];
this.final_exponent = bigInt("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480");
}
pairing(p1, p2) {
const pre1 = this.precomputeG1(p1);
const pre2 = this.precomputeG2(p2);
const r1 = this.millerLoop(pre1, pre2);
const res = this.finalExponentiation(r1);
return res;
}
precomputeG1(p) {
const Pcopy = this.G1.affine(p);
const res = {};
res.PX = Pcopy[0];
res.PY = Pcopy[1];
return res;
}
precomputeG2(p) {
const Qcopy = this.G2.affine(p);
const res = {
QX: Qcopy[0],
QY: Qcopy[1],
coeffs: []
};
const R = {
X: Qcopy[0],
Y: Qcopy[1],
Z: this.F2.one
};
let c;
for (let i = this.loop_count_bits.length-2; i >= 0; --i)
{
const bit = this.loop_count_bits[i];
c = this._doubleStep(R);
res.coeffs.push(c);
if (bit)
{
c = this._addStep(Qcopy, R);
res.coeffs.push(c);
}
}
const Q1 = this.G2.affine(this._g2MulByQ(Qcopy));
if (!this.F2.equals(Q1[2], this.F2.one))
{
throw new Error("Expected values are not equal");
}
const Q2 = this.G2.affine(this._g2MulByQ(Q1));
if (!this.F2.equals(Q2[2], this.F2.one))
{
throw new Error("Expected values are not equal");
}
if (this.loopCountNeg)
{
R.Y = this.F2.neg(R.Y);
}
Q2[1] = this.F2.neg(Q2[1]);
c = this._addStep(Q1, R);
res.coeffs.push(c);
c = this._addStep(Q2, R);
res.coeffs.push(c);
return res;
}
millerLoop(pre1, pre2) {
let f = this.F12.one;
let idx = 0;
let c;
for (let i = this.loop_count_bits.length-2; i >= 0; --i)
{
const bit = this.loop_count_bits[i];
/* code below gets executed for all bits (EXCEPT the MSB itself) of
alt_bn128_param_p (skipping leading zeros) in MSB to LSB
order */
c = pre2.coeffs[idx++];
f = this.F12.square(f);
f = this._mul_by_024(
f,
c.ell_0,
this.F2.mulScalar(c.ell_VW , pre1.PY),
this.F2.mulScalar(c.ell_VV , pre1.PX));
if (bit)
{
c = pre2.coeffs[idx++];
f = this._mul_by_024(
f,
c.ell_0,
this.F2.mulScalar(c.ell_VW, pre1.PY),
this.F2.mulScalar(c.ell_VV, pre1.PX));
}
}
if (this.loopCountNeg)
{
f = this.F12.inverse(f);
}
c = pre2.coeffs[idx++];
f = this._mul_by_024(
f,
c.ell_0,
this.F2.mulScalar(c.ell_VW, pre1.PY),
this.F2.mulScalar(c.ell_VV, pre1.PX));
c = pre2.coeffs[idx++];
f = this._mul_by_024(
f,
c.ell_0,
this.F2.mulScalar(c.ell_VW, pre1.PY),
this.F2.mulScalar(c.ell_VV, pre1.PX));
return f;
}
finalExponentiation(elt) {
// TODO: There is an optimization in FF
const res = this.F12.exp(elt,this.final_exponent);
return res;
}
_doubleStep(current) {
const X = current.X;
const Y = current.Y;
const Z = current.Z;
const A = this.F2.mulScalar(this.F2.mul(X,Y), this.two_inv); // A = X1 * Y1 / 2
const B = this.F2.square(Y); // B = Y1^2
const C = this.F2.square(Z); // C = Z1^2
const D = this.F2.add(C, this.F2.add(C,C)); // D = 3 * C
const E = this.F2.mul(this.twist_coeff_b, D); // E = twist_b * D
const F = this.F2.add(E, this.F2.add(E,E)); // F = 3 * E
const G =
this.F2.mulScalar(
this.F2.add( B , F ),
this.two_inv); // G = (B+F)/2
const H =
this.F2.sub(
this.F2.square( this.F2.add(Y,Z) ),
this.F2.add( B , C)); // H = (Y1+Z1)^2-(B+C)
const I = this.F2.sub(E, B); // I = E-B
const J = this.F2.square(X); // J = X1^2
const E_squared = this.F2.square(E); // E_squared = E^2
current.X = this.F2.mul( A, this.F2.sub(B,F) ); // X3 = A * (B-F)
current.Y =
this.F2.sub(
this.F2.sub( this.F2.square(G) , E_squared ),
this.F2.add( E_squared , E_squared )); // Y3 = G^2 - 3*E^2
current.Z = this.F2.mul( B, H ); // Z3 = B * H
const c = {
ell_0 : this.F2.mul( I, this.twist), // ell_0 = xi * I
ell_VW: this.F2.neg( H ), // ell_VW = - H (later: * yP)
ell_VV: this.F2.add( J , this.F2.add(J,J) ) // ell_VV = 3*J (later: * xP)
};
return c;
}
_addStep(base, current) {
const X1 = current.X;
const Y1 = current.Y;
const Z1 = current.Z;
const x2 = base[0];
const y2 = base[1];
const D = this.F2.sub( X1, this.F2.mul(x2,Z1) ); // D = X1 - X2*Z1
// console.log("Y: "+ A[0].affine(this.q).toString(16));
const E = this.F2.sub( Y1, this.F2.mul(y2,Z1) ); // E = Y1 - Y2*Z1
const F = this.F2.square(D); // F = D^2
const G = this.F2.square(E); // G = E^2
const H = this.F2.mul(D,F); // H = D*F
const I = this.F2.mul(X1,F); // I = X1 * F
const J =
this.F2.sub(
this.F2.add( H, this.F2.mul(Z1,G) ),
this.F2.add( I, I )); // J = H + Z1*G - (I+I)
current.X = this.F2.mul( D , J ); // X3 = D*J
current.Y =
this.F2.sub(
this.F2.mul( E , this.F2.sub(I,J) ),
this.F2.mul( H , Y1)); // Y3 = E*(I-J)-(H*Y1)
current.Z = this.F2.mul(Z1,H);
const c = {
ell_0 :
this.F2.mul(
this.twist,
this.F2.sub(
this.F2.mul(E , x2),
this.F2.mul(D , y2))), // ell_0 = xi * (E * X2 - D * Y2)
ell_VV : this.F2.neg(E), // ell_VV = - E (later: * xP)
ell_VW : D // ell_VW = D (later: * yP )
};
return c;
}
_mul_by_024(a, ell_0, ell_VW, ell_VV) {
// Old implementation
/*
const b = [
[ell_0, this.F2.zero, ell_VV],
[this.F2.zero, ell_VW, this.F2.zero]
];
return this.F12.mul(a,b);
*/
// This is a new implementation,
// But it does not look worthy
// at least in javascript.
let z0 = a[0][0];
let z1 = a[0][1];
let z2 = a[0][2];
let z3 = a[1][0];
let z4 = a[1][1];
let z5 = a[1][2];
const x0 = ell_0;
const x2 = ell_VV;
const x4 = ell_VW;
const D0 = this.F2.mul(z0, x0);
const D2 = this.F2.mul(z2, x2);
const D4 = this.F2.mul(z4, x4);
const t2 = this.F2.add(z0, z4);
let t1 = this.F2.add(z0, z2);
const s0 = this.F2.add(this.F2.add(z1,z3),z5);
// For z.a_.a_ = z0.
let S1 = this.F2.mul(z1, x2);
let T3 = this.F2.add(S1, D4);
let T4 = this.F2.add( this.F2.mul(this.nonResidueF6, T3),D0);
z0 = T4;
// For z.a_.b_ = z1
T3 = this.F2.mul(z5, x4);
S1 = this.F2.add(S1, T3);
T3 = this.F2.add(T3, D2);
T4 = this.F2.mul(this.nonResidueF6, T3);
T3 = this.F2.mul(z1, x0);
S1 = this.F2.add(S1, T3);
T4 = this.F2.add(T4, T3);
z1 = T4;
// For z.a_.c_ = z2
let t0 = this.F2.add(x0, x2);
T3 = this.F2.sub(
this.F2.mul(t1, t0),
this.F2.add(D0, D2));
T4 = this.F2.mul(z3, x4);
S1 = this.F2.add(S1, T4);
// For z.b_.a_ = z3 (z3 needs z2)
t0 = this.F2.add(z2, z4);
z2 = this.F2.add(T3, T4);
t1 = this.F2.add(x2, x4);
T3 = this.F2.sub(
this.F2.mul(t0,t1),
this.F2.add(D2, D4));
T4 = this.F2.mul(this.nonResidueF6, T3);
T3 = this.F2.mul(z3, x0);
S1 = this.F2.add(S1, T3);
T4 = this.F2.add(T4, T3);
z3 = T4;
// For z.b_.b_ = z4
T3 = this.F2.mul(z5, x2);
S1 = this.F2.add(S1, T3);
T4 = this.F2.mul(this.nonResidueF6, T3);
t0 = this.F2.add(x0, x4);
T3 = this.F2.sub(
this.F2.mul(t2,t0),
this.F2.add(D0, D4));
T4 = this.F2.add(T4, T3);
z4 = T4;
// For z.b_.c_ = z5.
t0 = this.F2.add(this.F2.add(x0, x2), x4);
T3 = this.F2.sub(this.F2.mul(s0, t0), S1);
z5 = T3;
return [
[z0, z1, z2],
[z3, z4, z5]
];
}
_g2MulByQ(p) {
const fmx = [p[0][0], this.F1.mul(p[0][1], this.frobenius_coeffs_c1_1 )];
const fmy = [p[1][0], this.F1.mul(p[1][1], this.frobenius_coeffs_c1_1 )];
const fmz = [p[2][0], this.F1.mul(p[2][1], this.frobenius_coeffs_c1_1 )];
return [
this.F2.mul(this.twist_mul_by_q_X , fmx),
this.F2.mul(this.twist_mul_by_q_Y , fmy),
fmz
];
}
}
module.exports = BN128;

233
src/calculateWitness.js Normal file
View File

@ -0,0 +1,233 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint");
module.exports = calculateWitness;
function calculateWitness(circuit, inputSignals, options) {
options = options || {};
if (!options.logFunction) options.logFunction = console.log;
const ctx = new RTCtx(circuit, options);
function iterateSelector(values, sels, cb) {
if (!Array.isArray(values)) {
return cb(sels, values);
}
for (let i=0; i<values.length; i++) {
sels.push(i);
iterateSelector(values[i], sels, cb);
sels.pop(i);
}
}
ctx.setSignal("one", [], bigInt(1));
for (let c in ctx.notInitSignals) {
if (ctx.notInitSignals[c] == 0) ctx.triggerComponent(c);
}
for (let s in inputSignals) {
ctx.currentComponent = "main";
iterateSelector(inputSignals[s], [], function(selector, value) {
if (typeof(value) == "undefined") throw new Error("Signal not defined:" + s);
ctx.setSignal(s, selector, bigInt(value));
});
}
for (let i=0; i<circuit.nInputs; i++) {
const idx = circuit.inputIdx(i);
if (typeof(ctx.witness[idx]) == "undefined") {
throw new Error("Input Signal not assigned: " + circuit.signalNames(idx));
}
}
for (let i=0; i<ctx.witness.length; i++) {
if (typeof(ctx.witness[i]) == "undefined") {
throw new Error("Signal not assigned: " + circuit.signalNames(i));
}
if (options.logOutput) options.logFunction(circuit.signalNames(i) + " --> " + ctx.witness[i].toString());
}
return ctx.witness.slice(0, circuit.nVars);
// return ctx.witness;
}
class RTCtx {
constructor(circuit, options) {
this.options = options;
this.scopes = [];
this.circuit = circuit;
this.witness = new Array(circuit.nSignals);
this.notInitSignals = {};
for (let c in this.circuit.components) {
this.notInitSignals[c] = this.circuit.components[c].inputSignals;
}
}
_sels2str(sels) {
let res = "";
for (let i=0; i<sels.length; i++) {
res += `[${sels[i]}]`;
}
return res;
}
setPin(componentName, componentSels, signalName, signalSels, value) {
let fullName = componentName=="one" ? "one" : this.currentComponent + "." + componentName;
fullName += this._sels2str(componentSels) +
"."+
signalName+
this._sels2str(signalSels);
this.setSignalFullName(fullName, value);
}
setSignal(name, sels, value) {
let fullName = this.currentComponent ? this.currentComponent + "." + name : name;
fullName += this._sels2str(sels);
this.setSignalFullName(fullName, value);
}
triggerComponent(c) {
if (this.options.logTrigger) this.options.logFunction("Component Treiggered: " + this.circuit.components[c].name);
// Set notInitSignals to -1 to not initialize again
this.notInitSignals[c] --;
const oldComponent = this.currentComponent;
this.currentComponent = this.circuit.components[c].name;
const template = this.circuit.components[c].template;
const newScope = {};
for (let p in this.circuit.components[c].params) {
newScope[p] = this.circuit.components[c].params[p];
}
const oldScope = this.scopes;
this.scopes = [ this.scopes[0], newScope ];
// TODO set params.
this.circuit.templates[template](this);
this.scopes = oldScope;
this.currentComponent = oldComponent;
if (this.options.logTrigger) this.options.logFunction("End Component Treiggered: " + this.circuit.components[c].name);
}
callFunction(functionName, params) {
const newScope = {};
for (let p=0; p<this.circuit.functions[functionName].params.length; p++) {
const paramName = this.circuit.functions[functionName].params[p];
newScope[paramName] = params[p];
}
const oldScope = this.scopes;
this.scopes = [ this.scopes[0], newScope ];
// TODO set params.
const res = this.circuit.functions[functionName].func(this);
this.scopes = oldScope;
return res;
}
setSignalFullName(fullName, value) {
if (this.options.logSet) this.options.logFunction("set " + fullName + " <-- " + value.toString());
const sId = this.circuit.getSignalIdx(fullName);
let firstInit =false;
if (typeof(this.witness[sId]) == "undefined") {
firstInit = true;
}
this.witness[sId] = bigInt(value);
const callComponents = [];
for (let i=0; i<this.circuit.signals[sId].triggerComponents.length; i++) {
var idCmp = this.circuit.signals[sId].triggerComponents[i];
if (firstInit) this.notInitSignals[idCmp] --;
callComponents.push(idCmp);
}
callComponents.map( (c) => {
if (this.notInitSignals[c] == 0) this.triggerComponent(c);
});
return this.witness[sId];
}
setVar(name, sels, value) {
function setVarArray(a, sels2, value) {
if (sels2.length == 1) {
a[sels2[0]] = value;
} else {
if (typeof(a[sels2[0]]) == "undefined") a[sels2[0]] = [];
setVarArray(a[sels2[0]], sels2.slice(1), value);
}
}
const scope = this.scopes[this.scopes.length-1];
if (sels.length == 0) {
scope[name] = value;
} else {
if (typeof(scope[name]) == "undefined") scope[name] = [];
setVarArray(scope[name], sels, value);
}
return value;
}
getVar(name, sels) {
function select(a, sels2) {
return (sels2.length == 0) ? a : select(a[sels2[0]], sels2.slice(1));
}
for (let i=this.scopes.length-1; i>=0; i--) {
if (typeof(this.scopes[i][name]) != "undefined") return select(this.scopes[i][name], sels);
}
throw new Error("Variable not defined: " + name);
}
getSignal(name, sels) {
let fullName = name=="one" ? "one" : this.currentComponent + "." + name;
fullName += this._sels2str(sels);
return this.getSignalFullName(fullName);
}
getPin(componentName, componentSels, signalName, signalSels) {
let fullName = componentName=="one" ? "one" : this.currentComponent + "." + componentName;
fullName += this._sels2str(componentSels) +
"."+
signalName+
this._sels2str(signalSels);
return this.getSignalFullName(fullName);
}
getSignalFullName(fullName) {
const sId = this.circuit.getSignalIdx(fullName);
if (typeof(this.witness[sId]) == "undefined") {
throw new Error("Signal not initialized: "+fullName);
}
if (this.options.logGet) this.options.logFunction("get --->" + fullName + " = " + this.witness[sId].toString() );
return this.witness[sId];
}
assert(a,b,errStr) {
const ba = bigInt(a);
const bb = bigInt(b);
if (!ba.equals(bb)) {
throw new Error("Constraint doesn't match "+ this.currentComponent+": "+ errStr + " -> "+ ba.toString() + " != " + bb.toString());
}
}
}

191
src/circuit.js Normal file
View File

@ -0,0 +1,191 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint.js");
const __P__ = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const __MASK__ = bigInt("28948022309329048855892746252171976963317496166410141009864396001978282409983"); // 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
const calculateWitness = require("./calculateWitness.js");
module.exports = class Circuit {
constructor(circuitDef) {
this.nPubInputs = circuitDef.nPubInputs;
this.nPrvInputs = circuitDef.nPrvInputs;
this.nInputs = circuitDef.nInputs;
this.nOutputs = circuitDef.nOutputs;
this.nVars = circuitDef.nVars;
this.nSignals = circuitDef.nSignals;
this.nConstants = circuitDef.nConstants;
this.nConstraints = circuitDef.constraints.length;
this.signalName2Idx = circuitDef.signalName2Idx;
this.components = circuitDef.components;
this.componentName2Idx = circuitDef.componentName2Idx;
this.signals = circuitDef.signals;
this.constraints = circuitDef.constraints;
this.templates = {};
for (let t in circuitDef.templates) {
this.templates[t] = eval(" const __f= " +circuitDef.templates[t] + "\n__f");
}
this.functions = {};
for (let f in circuitDef.functions) {
this.functions[f] = {
params: circuitDef.functions[f].params,
func: eval(" const __f= " +circuitDef.functions[f].func + "\n__f;")
};
}
}
calculateWitness(input, log) {
return calculateWitness(this, input, log);
}
checkWitness(w) {
const evalLC = (lc, w) => {
let acc = bigInt(0);
for (let k in lc) {
acc= acc.add(bigInt(w[k]).mul(bigInt(lc[k]))).mod(__P__);
}
return acc;
}
const checkConstraint = (ct, w) => {
const a=evalLC(ct[0],w);
const b=evalLC(ct[1],w);
const c=evalLC(ct[2],w);
const res = (a.mul(b).sub(c)).affine(__P__);
if (!res.isZero()) return false;
return true;
}
for (let i=0; i<this.constraints.length; i++) {
if (!checkConstraint(this.constraints[i], w)) {
this.printCostraint(this.constraints[i]);
return false;
}
}
return true;
}
printCostraint(c) {
const lc2str = (lc) => {
let S = "";
for (let k in lc) {
let name = this.signals[k].names[0];
if (name == "one") name = "";
let v = bigInt(lc[k]);
let vs;
if (!v.lesserOrEquals(__P__.shr(bigInt(1)))) {
v = __P__.sub(v);
vs = "-"+v.toString();
} else {
if (S!="") {
vs = "+"+v.toString();
} else {
vs = "";
}
if (vs!="1") {
vs = vs + v.toString();;
}
}
S= S + " " + vs + name;
}
return S;
};
const S = `[ ${lc2str(c[0])} ] * [ ${lc2str(c[1])} ] - [ ${lc2str(c[2])} ] = 0`;
console.log(S);
}
printConstraints() {
for (let i=0; i<this.constraints.length; i++) {
this.printCostraint(this.constraints[i]);
}
}
getSignalIdx(name) {
if (typeof(this.signalName2Idx[name]) != "undefined") return this.signalName2Idx[name];
if (!isNaN(name)) return Number(name);
throw new Error("Invalid signal identifier: "+ name);
}
// returns the index of the i'th output
outputIdx(i) {
if (i>=this.nOutputs) throw new Error("Accessing an invalid output: "+i);
return i+1;
}
// returns the index of the i'th input
inputIdx(i) {
if (i>=this.nInputs) throw new Error("Accessing an invalid input: "+i);
return this.nOutputs + 1 + i;
}
// returns the index of the i'th public input
pubInputIdx(i) {
if (i>=this.nPubInputs) throw new Error("Accessing an invalid pubInput: "+i);
return this.inputIdx(i);
}
// returns the index of the i'th private input
prvInputIdx(i) {
if (i>=this.nPrvInputs) throw new Error("Accessing an invalid prvInput: "+i);
return this.inputIdx(this.nPubInputs + i);
}
// returns the index of the i'th variable
varIdx(i) {
if (i>=this.nVars) throw new Error("Accessing an invalid variable: "+i);
return i;
}
// returns the index of the i'th constant
constantIdx(i) {
if (i>=this.nConstants) throw new Error("Accessing an invalid constant: "+i);
return this.nVars + i;
}
// returns the index of the i'th signal
signalIdx(i) {
if (i>=this.nSignls) throw new Error("Accessing an invalid signal: "+i);
return i;
}
signalNames(i) {
return this.signals[ this.getSignalIdx(i) ].names.join(", ");
}
a(constraint, signalIdx) {
return bigInt(this.constraints[constraint][0][signalIdx] || 0 );
}
b(constraint, signalIdx) {
return bigInt(this.constraints[constraint][1][signalIdx] || 0);
}
c(constraint, signalIdx) {
return bigInt(this.constraints[constraint][2][signalIdx] || 0);
}
};

137
src/f2field.js Normal file
View File

@ -0,0 +1,137 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const fUtils = require("./futils.js");
class F2Field {
constructor(F, nonResidue) {
this.F = F;
this.zero = [this.F.zero, this.F.zero];
this.one = [this.F.one, this.F.zero];
this.nonResidue = nonResidue;
}
_mulByNonResidue(a) {
return this.F.mul(this.nonResidue, a);
}
copy(a) {
return [this.F.copy(a[0]), this.F.copy(a[1])];
}
add(a, b) {
return [
this.F.add(a[0], b[0]),
this.F.add(a[1], b[1])
];
}
double(a) {
return this.add(a,a);
}
sub(a, b) {
return [
this.F.sub(a[0], b[0]),
this.F.sub(a[1], b[1])
];
}
neg(a) {
return this.sub(this.zero, a);
}
mul(a, b) {
const aA = this.F.mul(a[0] , b[0]);
const bB = this.F.mul(a[1] , b[1]);
return [
this.F.add( aA , this._mulByNonResidue(bB)),
this.F.sub(
this.F.mul(
this.F.add(a[0], a[1]),
this.F.add(b[0], b[1])),
this.F.add(aA, bB))];
}
inverse(a) {
const t0 = this.F.square(a[0]);
const t1 = this.F.square(a[1]);
const t2 = this.F.sub(t0, this._mulByNonResidue(t1));
const t3 = this.F.inverse(t2);
return [
this.F.mul(a[0], t3),
this.F.neg(this.F.mul( a[1], t3)) ];
}
div(a, b) {
return this.mul(a, this.inverse(b));
}
square(a) {
const ab = this.F.mul(a[0] , a[1]);
/*
[
(a + b) * (a + non_residue * b) - ab - non_residue * ab,
ab + ab
];
*/
return [
this.F.sub(
this.F.mul(
this.F.add(a[0], a[1]) ,
this.F.add(
a[0] ,
this._mulByNonResidue(a[1]))),
this.F.add(
ab,
this._mulByNonResidue(ab))),
this.F.add(ab, ab)
];
}
isZero(a) {
return this.F.isZero(a[0]) && this.F.isZero(a[1]);
}
equals(a, b) {
return this.F.equals(a[0], b[0]) && this.F.equals(a[1], b[1]);
}
affine(a) {
return [this.F.affine(a[0]), this.F.affine(a[1])];
}
mulScalar(base, e) {
return fUtils.mulScalar(this, base, e);
}
exp(base, e) {
return fUtils.exp(this, base, e);
}
toString(a) {
const cp = this.affine(a);
return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`;
}
}
module.exports = F2Field;

177
src/f3field.js Normal file
View File

@ -0,0 +1,177 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const fUtils = require("./futils.js");
class F3Field {
constructor(F, nonResidue) {
this.F = F;
this.zero = [this.F.zero, this.F.zero, this.F.zero];
this.one = [this.F.one, this.F.zero, this.F.zero];
this.nonResidue = nonResidue;
}
_mulByNonResidue(a) {
return this.F.mul(this.nonResidue, a);
}
copy(a) {
return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])];
}
add(a, b) {
return [
this.F.add(a[0], b[0]),
this.F.add(a[1], b[1]),
this.F.add(a[2], b[2])
];
}
double(a) {
return this.add(a,a);
}
sub(a, b) {
return [
this.F.sub(a[0], b[0]),
this.F.sub(a[1], b[1]),
this.F.sub(a[2], b[2])
];
}
neg(a) {
return this.sub(this.zero, a);
}
mul(a, b) {
const aA = this.F.mul(a[0] , b[0]);
const bB = this.F.mul(a[1] , b[1]);
const cC = this.F.mul(a[2] , b[2]);
return [
this.F.add(
aA,
this._mulByNonResidue(
this.F.sub(
this.F.mul(
this.F.add(a[1], a[2]),
this.F.add(b[1], b[2])),
this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC),
this.F.add(
this.F.sub(
this.F.mul(
this.F.add(a[0], a[1]),
this.F.add(b[0], b[1])),
this.F.add(aA, bB)),
this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC
this.F.add(
this.F.sub(
this.F.mul(
this.F.add(a[0], a[2]),
this.F.add(b[0], b[2])),
this.F.add(aA, cC)),
bB)]; // (a+c)*(A+C)-aA+bB-cC)
}
inverse(a) {
const t0 = this.F.square(a[0]); // t0 = a^2 ;
const t1 = this.F.square(a[1]); // t1 = b^2 ;
const t2 = this.F.square(a[2]); // t2 = c^2;
const t3 = this.F.mul(a[0],a[1]); // t3 = ab
const t4 = this.F.mul(a[0],a[2]); // t4 = ac
const t5 = this.F.mul(a[1],a[2]); // t5 = bc;
// c0 = t0 - non_residue * t5;
const c0 = this.F.sub(t0, this._mulByNonResidue(t5));
// c1 = non_residue * t2 - t3;
const c1 = this.F.sub(this._mulByNonResidue(t2), t3);
const c2 = this.F.sub(t1, t4); // c2 = t1-t4
// t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inverse();
const t6 =
this.F.inverse(
this.F.add(
this.F.mul(a[0], c0),
this._mulByNonResidue(
this.F.add(
this.F.mul(a[2], c1),
this.F.mul(a[1], c2)))));
return [
this.F.mul(t6, c0), // t6*c0
this.F.mul(t6, c1), // t6*c1
this.F.mul(t6, c2)]; // t6*c2
}
div(a, b) {
return this.mul(a, this.inverse(b));
}
square(a) {
const s0 = this.F.square(a[0]); // s0 = a^2
const ab = this.F.mul(a[0], a[1]); // ab = a*b
const s1 = this.F.add(ab, ab); // s1 = 2ab;
const s2 = this.F.square(
this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2;
const bc = this.F.mul(a[1],a[2]); // bc = b*c
const s3 = this.F.add(bc, bc); // s3 = 2*bc
const s4 = this.F.square(a[2]); // s4 = c^2
return [
this.F.add(
s0,
this._mulByNonResidue(s3)), // s0 + non_residue * s3,
this.F.add(
s1,
this._mulByNonResidue(s4)), // s1 + non_residue * s4,
this.F.sub(
this.F.add( this.F.add(s1, s2) , s3 ),
this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4
}
isZero(a) {
return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]);
}
equals(a, b) {
return this.F.equals(a[0], b[0]) && this.F.equals(a[1], b[1]) && this.F.equals(a[2], b[2]);
}
affine(a) {
return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])];
}
mulScalar(base, e) {
return fUtils.mulScalar(this, base, e);
}
exp(base, e) {
return fUtils.exp(this, base, e);
}
toString(a) {
const cp = this.affine(a);
return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])}, ${this.F.toString(cp[2])} ]`;
}
}
module.exports = F3Field;

53
src/futils.js Normal file
View File

@ -0,0 +1,53 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint.js");
exports.mulScalar = (F, base, e) =>{
let res = F.zero;
let rem = bigInt(e);
let exp = base;
while (! rem.isZero()) {
if (rem.isOdd()) {
res = F.add(res, exp);
}
exp = F.double(exp);
rem = rem.shr(1);
}
return res;
};
exports.exp = (F, base, e) =>{
let res = F.one;
let rem = bigInt(e);
let exp = base;
while (! rem.isZero()) {
if (rem.isOdd()) {
res = F.mul(res, exp);
}
exp = F.square(exp);
rem = rem.shr(1);
}
return res;
};

190
src/gcurve.js Normal file
View File

@ -0,0 +1,190 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const fUtils = require("./futils.js");
class GCurve {
constructor(F, g) {
this.F = F;
this.g = [F.copy(g[0]), F.copy(g[1])];
if (this.g.length == 2) this.g[2] = this.F.one;
this.zero = [this.F.zero, this.F.one, this.F.zero];
}
isZero(p) {
return this.F.isZero(p[2]);
}
add(p1, p2) {
const F = this.F;
if (this.isZero(p1)) return p2;
if (this.isZero(p2)) return p1;
const res = new Array(3);
const Z1Z1 = F.square( p1[2] );
const Z2Z2 = F.square( p2[2] );
const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2
const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1
const Z1_cubed = F.mul( p1[2] , Z1Z1);
const Z2_cubed = F.mul( p2[2] , Z2Z2);
const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2
const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1
if (F.equals(U1,U2) && F.equals(S1,S2)) {
return this.double(p1);
}
const H = F.sub( U2 , U1 ); // H = U2-U1
const S2_minus_S1 = F.sub( S2 , S1 );
const I = F.square( F.add(H,H) ); // I = (2 * H)^2
const J = F.mul( H , I ); // J = H * I
const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1)
const V = F.mul( U1 , I ); // V = U1 * I
res[0] =
F.sub(
F.sub( F.square(r) , J ),
F.add( V , V )); // X3 = r^2 - J - 2 * V
const S1_J = F.mul( S1 , J );
res[1] =
F.sub(
F.mul( r , F.sub(V,res[0])),
F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J
res[2] =
F.mul(
H,
F.sub(
F.square( F.add(p1[2],p2[2]) ),
F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H
return res;
}
neg(p) {
return [p[0], this.F.neg(p[1]), p[2]];
}
sub(a, b) {
return this.add(a, this.neg(b));
}
double(p) {
const F = this.F;
const res = new Array(3);
if (this.isZero(p)) return p;
const A = F.square( p[0] ); // A = X1^2
const B = F.square( p[1] ); // B = Y1^2
const C = F.square( B ); // C = B^2
let D =
F.sub(
F.square( F.add(p[0] , B )),
F.add( A , C));
D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C)
const E = F.add( F.add(A,A), A); // E = 3 * A
const FF =F.square( E ); // F = E^2
res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D
let eightC = F.add( C , C );
eightC = F.add( eightC , eightC );
eightC = F.add( eightC , eightC );
res[1] =
F.sub(
F.mul(
E,
F.sub( D, res[0] )),
eightC); // Y3 = E * (D - X3) - 8 * C
const Y1Z1 = F.mul( p[1] , p[2] );
res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1
return res;
}
mulScalar(base, e) {
return fUtils.mulScalar(this, base, e);
}
affine(p) {
const F = this.F;
if (this.isZero(p)) {
return this.zero;
} else {
const Z_inv = F.inverse(p[2]);
const Z2_inv = F.square(Z_inv);
const Z3_inv = F.mul(Z2_inv, Z_inv);
const res = new Array(3);
res[0] = F.affine( F.mul(p[0],Z2_inv));
res[1] = F.affine( F.mul(p[1],Z3_inv));
res[2] = F.one;
return res;
}
}
equals(p1, p2) {
const F = this.F;
if (this.isZero(p1)) return this.isZero(p2);
if (this.isZero(p2)) return this.isZero(p1);
const Z1Z1 = F.square( p1[2] );
const Z2Z2 = F.square( p2[2] );
const U1 = F.mul( p1[0] , Z2Z2 );
const U2 = F.mul( p2[0] , Z1Z1 );
const Z1_cubed = F.mul( p1[2] , Z1Z1);
const Z2_cubed = F.mul( p2[2] , Z2Z2);
const S1 = F.mul( p1[1] , Z2_cubed);
const S2 = F.mul( p2[1] , Z1_cubed);
return (F.equals(U1,U2) && F.equals(S1,S2));
}
toString(p) {
const cp = this.affine(p);
return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`;
}
}
module.exports = GCurve;

534
src/polfield.js Normal file
View File

@ -0,0 +1,534 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/*
This library does operations on polynomials with coefficients in a field F.
A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented
by the array [ p0, p1, p2, ... , pn ].
*/
const bigInt = require("./bigint.js");
class PolField {
constructor (F) {
this.F = F;
const q = this.F.q;
let rem = q.sub(bigInt(1));
let s = 0;
while (!rem.isOdd()) {
s ++;
rem = rem.shr(1);
}
const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one);
this.w = new Array(s+1);
this.wi = new Array(s+1);
this.w[s] = this.F.exp(five, rem);
this.wi[s] = this.F.inverse(this.w[s]);
let n=s-1;
while (n>=0) {
this.w[n] = this.F.square(this.w[n+1]);
this.wi[n] = this.F.square(this.wi[n+1]);
n--;
}
this.roots = [];
/* for (let i=0; i<16; i++) {
let r = this.F.one;
n = 1 << i;
const rootsi = new Array(n);
for (let j=0; j<n; j++) {
rootsi[j] = r;
r = this.F.mul(r, this.w[i]);
}
this.roots.push(rootsi);
}
*/
this._setRoots(15);
}
_setRoots(n) {
for (let i=n; (i>=0) && (!this.roots[i]); i--) {
let r = this.F.one;
const nroots = 1 << i;
const rootsi = new Array(nroots);
for (let j=0; j<nroots; j++) {
rootsi[j] = r;
r = this.F.mul(r, this.w[i]);
}
this.roots[i] = rootsi;
}
}
add(a, b) {
const m = Math.max(a.length, b.length);
const res = new Array(m);
for (let i=0; i<m; i++) {
res[i] = this.F.add(a[i] || this.F.zero, b[i] || this.F.zero);
}
return this.reduce(res);
}
double(a) {
return this.add(a,a);
}
sub(a, b) {
const m = Math.max(a.length, b.length);
const res = new Array(m);
for (let i=0; i<m; i++) {
res[i] = this.F.sub(a[i] || this.F.zero, b[i] || this.F.zero);
}
return this.reduce(res);
}
mulScalar(p, b) {
if (this.F.isZero(b)) return [];
if (this.F.equals(b, this.F.one)) return p;
const res = new Array(p.length);
for (let i=0; i<p.length; i++) {
res[i] = this.F.mul(p[i], b);
}
return res;
}
mul(a, b) {
if (a.length == 0) return [];
if (b.length == 0) return [];
if (a.length == 1) return this.mulScalar(b, a[0]);
if (b.length == 1) return this.mulScalar(a, b[0]);
if (b.length > a.length) {
[b, a] = [a, b];
}
if ((b.length <= 2) || (b.length < log2(a.length))) {
return this.mulNormal(a,b);
} else {
return this.mulFFT(a,b);
}
}
mulNormal(a, b) {
let res = [];
b = this.affine(b);
for (let i=0; i<b.length; i++) {
res = this.add(res, this.scaleX(this.mulScalar(a, b[i]), i) );
}
return res;
}
mulFFT(a,b) {
const longestN = Math.max(a.length, b.length);
const bitsResult = log2(longestN-1)+2;
this._setRoots(bitsResult);
const m = 1 << bitsResult;
const ea = this.extend(a,m);
const eb = this.extend(b,m);
const ta = __fft(this, ea, bitsResult, 0, 1, false);
const tb = __fft(this, eb, bitsResult, 0, 1, false);
const tres = new Array(m);
for (let i=0; i<m; i++) {
tres[i] = this.F.mul(ta[i], tb[i]);
}
const res = __fft(this, tres, bitsResult, 0, 1, true);
const twoinvm = this.F.inverse( this.F.mulScalar(this.F.one, m) );
const resn = new Array(m);
for (let i=0; i<m; i++) {
resn[i] = this.F.mul(res[(m-i)%m], twoinvm);
}
return this.reduce(this.affine(resn));
}
square(a) {
return this.mul(a,a);
}
scaleX(p, n) {
if (n==0) {
return p;
} else if (n>0) {
const z = new Array(n).fill(this.F.zero);
return z.concat(p);
} else {
if (-n >= p.length) return [];
return p.slice(-n);
}
}
eval2(p, x) {
let v = this.F.zero;
let ix = this.F.one;
for (let i=0; i<p.length; i++) {
v = this.F.add(v, this.F.mul(p[i], ix));
ix = this.F.mul(ix, x);
}
return v;
}
eval(p,x) {
const F = this.F;
if (p.length == 0) return F.zero;
const m = this._next2Power(p.length);
const ep = this.extend(p, m);
return _eval(ep, x, 0, 1, m);
function _eval(p, x, offset, step, n) {
if (n==1) return p[offset];
const newX = F.square(x);
const res= F.add(
_eval(p, newX, offset, step << 1, n >> 1),
F.mul(
x,
_eval(p, newX, offset+step , step << 1, n >> 1)));
return res;
}
}
lagrange(points) {
let roots = [this.F.one];
for (let i=0; i<points.length; i++) {
roots = this.mul(roots, [this.F.neg(points[i][0]), this.F.one]);
}
let sum = [];
for (let i=0; i<points.length; i++) {
let mpol = this.ruffini(roots, points[i][0]);
const factor =
this.F.mul(
this.F.inverse(this.eval(mpol, points[i][0])),
points[i][1]);
mpol = this.mulScalar(mpol, factor);
sum = this.add(sum, mpol);
}
return sum;
}
fft(p) {
if (p.length <= 1) return p;
const bits = log2(p.length-1)+1;
this._setRoots(bits);
const m = 1 << bits;
const ep = this.extend(p, m);
const res = __fft(this, ep, bits, 0, 1);
return res;
}
ifft(p) {
if (p.length <= 1) return p;
const bits = log2(p.length-1)+1;
this._setRoots(bits);
const m = 1 << bits;
const ep = this.extend(p, m);
const res = __fft(this, ep, bits, 0, 1);
const twoinvm = this.F.inverse( this.F.mulScalar(this.F.one, m) );
const resn = new Array(m);
for (let i=0; i<m; i++) {
resn[i] = this.F.mul(res[(m-i)%m], twoinvm);
}
return resn;
}
_fft(pall, bits, offset, step) {
const n = 1 << bits;
if (n==1) {
return [ pall[offset] ];
}
const ndiv2 = n >> 1;
const p1 = this._fft(pall, bits-1, offset, step*2);
const p2 = this._fft(pall, bits-1, offset+step, step*2);
const out = new Array(n);
let m= this.F.one;
for (let i=0; i<ndiv2; i++) {
out[i] = this.F.add(p1[i], this.F.mul(m, p2[i]));
out[i+ndiv2] = this.F.sub(p1[i], this.F.mul(m, p2[i]));
m = this.F.mul(m, this.w[bits]);
}
return out;
}
extend(p, e) {
if (e == p.length) return p;
const z = new Array(e-p.length).fill(this.F.zero);
return p.concat(z);
}
reduce(p) {
if (p.length == 0) return p;
if (! this.F.isZero(p[p.length-1]) ) return p;
let i=p.length-1;
while( i>0 && this.F.isZero(p[i]) ) i--;
return p.slice(0, i+1);
}
affine(p) {
for (let i=0; i<p.length; i++) {
p[i] = this.F.affine(p[i]);
}
return p;
}
equals(a, b) {
const pa = this.reduce(this.affine(a));
const pb = this.reduce(this.affine(b));
if (pa.length != pb.length) return false;
for (let i=0; i<pb.length; i++) {
if (!this.F.equals(pa[i], pb[i])) return false;
}
return true;
}
ruffini(p, r) {
const res = new Array(p.length-1);
res[res.length-1] = p[p.length-1];
for (let i = res.length-2; i>=0; i--) {
res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]);
}
return res;
}
_next2Power(v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
toString(p) {
const ap = this.affine(p);
let S = "";
for (let i=ap.length-1; i>=0; i--) {
if (!this.F.isZero(p[i])) {
if (S!="") S += " + ";
S = S + p[i].toString(10);
if (i>0) {
S = S + "x";
if (i>1) {
S = S + "^" +i;
}
}
}
}
return S;
}
_reciprocal(p, bits) {
const k = 1 << bits;
if (k==1) {
return [ this.F.inverse(p[0]) ];
}
const np = this.scaleX(p, -k/2);
const q = this._reciprocal(np, bits-1);
const a = this.scaleX(this.double(q), 3*k/2-2);
const b = this.mul( this.square(q), p);
return this.scaleX(this.sub(a,b), -(k-2));
}
// divides x^m / v
_div2(m, v) {
const kbits = log2(v.length-1)+1;
const k = 1 << kbits;
const scaleV = k - v.length;
// rec = x^(k - 2) / v* x^scaleV =>
// rec = x^(k-2-scaleV)/ v
//
// res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v =>
// res = rec * x^(m - (2*k-2 - scaleV)) =>
// res = rec * x^(m - 2*k + 2 + scaleV)
const rec = this._reciprocal(this.scaleX(v, scaleV), kbits);
const res = this.scaleX(rec, m - 2*k + 2 + scaleV);
return res;
}
div(_u, _v) {
if (_u.length < _v.length) return [];
const kbits = log2(_v.length-1)+1;
const k = 1 << kbits;
const u = this.scaleX(_u, k-_v.length);
const v = this.scaleX(_v, k-_v.length);
const n = v.length-1;
let m = u.length-1;
const s = this._reciprocal(v, kbits);
let t;
if (m>2*n) {
t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v));
}
let q = [];
let rem = u;
let us, ut;
let finish = false;
while (!finish) {
us = this.mul(rem, s);
q = this.add(q, this.scaleX(us, -2*n));
if ( m > 2*n ) {
ut = this.mul(rem, t);
rem = this.scaleX(ut, -2*n);
m = rem.length-1;
} else {
finish = true;
}
}
return q;
}
// returns the ith nth-root of one
oneRoot(n, i) {
let nbits = log2(n-1)+1;
let res = this.F.one;
let r = i;
if(i>=n) {
throw new Error("Given 'i' should be lower than 'n'");
}
else if (1<<nbits !== n) {
throw new Error(`Internal errlr: ${n} should equal ${1<<nbits}`);
}
while (r>0) {
if (r & 1 == 1) {
res = this.F.mul(res, this.w[nbits]);
}
r = r >> 1;
nbits --;
}
return res;
}
computeVanishingPolinomial(bits, t) {
const m = 1 << bits;
return this.F.sub(this.F.exp(t, bigInt(m)), this.F.one);
}
evaluateLagrangePolynomials(bits, t) {
const m= 1 << bits;
const tm = this.F.exp(t, bigInt(m));
const u= new Array(m).fill(this.F.zero);
this._setRoots(bits);
const omega = this.w[bits];
if (this.F.equals(tm, this.F.one)) {
for (let i = 0; i < m; i++) {
if (this.F.equals(this.roots[bits][0],t)) { // i.e., t equals omega^i
u[i] = this.F.one;
return u;
}
}
}
const z = this.F.sub(tm, this.F.one);
// let l = this.F.mul(z, this.F.exp(this.F.twoinv, m));
let l = this.F.mul(z, this.F.inverse(bigInt(m)));
for (let i = 0; i < m; i++) {
u[i] = this.F.mul(l, this.F.inverse(this.F.sub(t,this.roots[bits][i])));
l = this.F.mul(l, omega);
}
return u;
}
log2(V) {
return log2(V);
}
}
function log2( V )
{
return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) );
}
function __fft(PF, pall, bits, offset, step) {
const n = 1 << bits;
if (n==1) {
return [ pall[offset] ];
} else if (n==2) {
return [
PF.F.add(pall[offset], pall[offset + step]),
PF.F.sub(pall[offset], pall[offset + step])];
}
const ndiv2 = n >> 1;
const p1 = __fft(PF, pall, bits-1, offset, step*2);
const p2 = __fft(PF, pall, bits-1, offset+step, step*2);
const out = new Array(n);
for (let i=0; i<ndiv2; i++) {
out[i] = PF.F.add(p1[i], PF.F.mul(PF.roots[bits][i], p2[i]));
out[i+ndiv2] = PF.F.sub(p1[i], PF.F.mul(PF.roots[bits][i], p2[i]));
}
return out;
}
module.exports = PolField;

141
src/prover_groth.js Normal file
View File

@ -0,0 +1,141 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
const BN128 = require("./bn128.js");
const PolField = require("./polfield.js");
const ZqField = require("./zqfield.js");
const bn128 = new BN128();
const PolF = new PolField(new ZqField(bn128.r));
const G1 = bn128.G1;
const G2 = bn128.G2;
module.exports = function genProof(vk_proof, witness) {
const proof = {};
const r = PolF.F.random();
const s = PolF.F.random();
/* Uncomment to generate a deterministic proof to debug
const r = PolF.F.zero;
const s = PolF.F.zero;
*/
proof.pi_a = G1.zero;
proof.pi_b = G2.zero;
proof.pi_c = G1.zero;
let pib1 = G1.zero;
// Skip public entries and the "1" signal that are forced by the verifier
for (let s= 0; s< vk_proof.nVars; s++) {
// pi_a = pi_a + A[s] * witness[s];
proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
// pi_b = pi_b + B[s] * witness[s];
proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B2[s], witness[s]));
pib1 = G1.add( pib1, G1.mulScalar( vk_proof.B1[s], witness[s]));
}
for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
// pi_a = pi_a + A[s] * witness[s];
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
}
proof.pi_a = G1.add( proof.pi_a, vk_proof.vk_alfa_1 );
proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.vk_delta_1, r ));
proof.pi_b = G2.add( proof.pi_b, vk_proof.vk_beta_2 );
proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.vk_delta_2, s ));
pib1 = G1.add( pib1, vk_proof.vk_beta_1 );
pib1 = G1.add( pib1, G1.mulScalar( vk_proof.vk_delta_1, s ));
const h = calculateH(vk_proof, witness);
// proof.pi_c = G1.affine(proof.pi_c);
// console.log("pi_onlyc", proof.pi_c);
for (let i = 0; i < h.length; i++) {
// console.log(i + "->" + h[i].toString());
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.hExps[i], h[i]));
}
// proof.pi_c = G1.affine(proof.pi_c);
// console.log("pi_candh", proof.pi_c);
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( proof.pi_a, s ));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( pib1, r ));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.vk_delta_1, PolF.F.affine(PolF.F.neg(PolF.F.mul(r,s) ))));
const publicSignals = witness.slice(1, vk_proof.nPublic+1);
proof.pi_a = G1.affine(proof.pi_a);
proof.pi_b = G2.affine(proof.pi_b);
proof.pi_c = G1.affine(proof.pi_c);
proof.protocol = "groth";
return {proof, publicSignals};
};
function calculateH(vk_proof, witness) {
const F = PolF.F;
const m = vk_proof.domainSize;
const polA_T = new Array(m).fill(PolF.F.zero);
const polB_T = new Array(m).fill(PolF.F.zero);
const polC_T = new Array(m).fill(PolF.F.zero);
for (let s=0; s<vk_proof.nVars; s++) {
for (let c in vk_proof.polsA[s]) {
polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
}
for (let c in vk_proof.polsB[s]) {
polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
}
for (let c in vk_proof.polsC[s]) {
polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
}
}
const polA_S = PolF.ifft(polA_T);
const polB_S = PolF.ifft(polB_T);
const polAB_S = PolF.mul(polA_S, polB_S);
const polC_S = PolF.ifft(polC_T);
const polABC_S = PolF.sub(polAB_S, polC_S);
const H_S = polABC_S.slice(m);
return H_S;
}

177
src/prover_kimleeoh.js Normal file
View File

@ -0,0 +1,177 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
const BN128 = require("./bn128.js");
const PolField = require("./polfield.js");
const ZqField = require("./zqfield.js");
const createKeccakHash = require("keccak");
const bigInt = require("./bigint");
const bn128 = new BN128();
const PolF = new PolField(new ZqField(bn128.r));
const G1 = bn128.G1;
const G2 = bn128.G2;
module.exports = function genProof(vk_proof, witness) {
const proof = {};
const r = PolF.F.random();
const s = PolF.F.random();
// const r = PolF.F.zero;
// const s = PolF.F.zero;
/* Uncomment to generate a deterministic proof to debug
const r = PolF.F.zero;
const s = PolF.F.zero;
*/
proof.pi_a = G1.zero;
proof.pi_b = G2.zero;
proof.pi_c = G1.zero;
let pib1 = G1.zero;
let piadelta = G1.zero;
// Skip public entries and the "1" signal that are forced by the verifier
for (let s= 0; s< vk_proof.nVars; s++) {
// pi_a = pi_a + A[s] * witness[s];
proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
// pi_b = pi_b + B[s] * witness[s];
proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B2[s], witness[s]));
piadelta = G1.add( piadelta, G1.mulScalar( vk_proof.Adelta[s], witness[s]));
pib1 = G1.add( pib1, G1.mulScalar( vk_proof.B1[s], witness[s]));
}
for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
// pi_a = pi_a + A[s] * witness[s];
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
}
proof.pi_a = G1.add( proof.pi_a, vk_proof.vk_alfa_1 );
proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( G1.g, r ));
piadelta = G1.add( piadelta, vk_proof.vk_alfadelta_1);
piadelta = G1.add( piadelta, G1.mulScalar( vk_proof.vk_delta_1, r ));
proof.pi_b = G2.add( proof.pi_b, vk_proof.vk_beta_2 );
proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( G2.g, s ));
pib1 = G1.add( pib1, vk_proof.vk_beta_1 );
pib1 = G1.add( pib1, G1.mulScalar( G1.g, s ));
proof.pi_a = G1.affine(proof.pi_a);
proof.pi_b = G2.affine(proof.pi_b);
const buff = Buffer.concat([
proof.pi_a[0].beInt2Buff(32),
proof.pi_a[1].beInt2Buff(32),
proof.pi_b[0][0].beInt2Buff(32),
proof.pi_b[0][1].beInt2Buff(32),
proof.pi_b[1][0].beInt2Buff(32),
proof.pi_b[1][1].beInt2Buff(32)
]);
const h1buff = createKeccakHash("keccak256").update(buff).digest();
const h2buff = createKeccakHash("keccak256").update(h1buff).digest();
const h1 = bigInt.beBuff2int(h1buff);
const h2 = bigInt.beBuff2int(h2buff);
// const h1 = PolF.F.zero;
// const h2 = PolF.F.zero;
console.log(h1.toString());
console.log(h2.toString());
const h = calculateH(vk_proof, witness);
// proof.pi_c = G1.affine(proof.pi_c);
// console.log("pi_onlyc", proof.pi_c);
for (let i = 0; i < h.length; i++) {
// console.log(i + "->" + h[i].toString());
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.hExps[i], h[i]));
}
// proof.pi_c = G1.affine(proof.pi_c);
// console.log("pi_candh", proof.pi_c);
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( proof.pi_a, s ));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( pib1, r ));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( G1.g, PolF.F.affine(PolF.F.neg(PolF.F.mul(r,s) ))));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( piadelta, h2 ));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( pib1, h1 ));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.vk_delta_1, PolF.F.mul(h1,h2)));
const publicSignals = witness.slice(1, vk_proof.nPublic+1);
proof.pi_c = G1.affine(proof.pi_c);
proof.protocol = "kimleeoh";
return {proof, publicSignals};
};
function calculateH(vk_proof, witness) {
const F = PolF.F;
const m = vk_proof.domainSize;
const polA_T = new Array(m).fill(PolF.F.zero);
const polB_T = new Array(m).fill(PolF.F.zero);
const polC_T = new Array(m).fill(PolF.F.zero);
for (let s=0; s<vk_proof.nVars; s++) {
for (let c in vk_proof.polsA[s]) {
polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
}
for (let c in vk_proof.polsB[s]) {
polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
}
for (let c in vk_proof.polsC[s]) {
polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
}
}
const polA_S = PolF.ifft(polA_T);
const polB_S = PolF.ifft(polB_T);
const polAB_S = PolF.mul(polA_S, polB_S);
const polC_S = PolF.ifft(polC_T);
const polABC_S = PolF.sub(polAB_S, polC_S);
const H_S = polABC_S.slice(m);
return H_S;
}

210
src/prover_original.js Normal file
View File

@ -0,0 +1,210 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const BN128 = require("./bn128.js");
const PolField = require("./polfield.js");
const ZqField = require("./zqfield.js");
const bn128 = new BN128();
const PolF = new PolField(new ZqField(bn128.r));
const G1 = bn128.G1;
const G2 = bn128.G2;
module.exports = function genProof(vk_proof, witness) {
const proof = {};
const d1 = PolF.F.random();
const d2 = PolF.F.random();
const d3 = PolF.F.random();
proof.pi_a = G1.zero;
proof.pi_ap = G1.zero;
proof.pi_b = G2.zero;
proof.pi_bp = G1.zero;
proof.pi_c = G1.zero;
proof.pi_cp = G1.zero;
proof.pi_kp = G1.zero;
proof.pi_h = G1.zero;
// Skip public entries and the "1" signal that are forced by the verifier
for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
// pi_a = pi_a + A[s] * witness[s];
proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
// pi_ap = pi_ap + Ap[s] * witness[s];
proof.pi_ap = G1.add( proof.pi_ap, G1.mulScalar( vk_proof.Ap[s], witness[s]));
}
for (let s= 0; s< vk_proof.nVars; s++) {
// pi_a = pi_a + A[s] * witness[s];
proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B[s], witness[s]));
// pi_ap = pi_ap + Ap[s] * witness[s];
proof.pi_bp = G1.add( proof.pi_bp, G1.mulScalar( vk_proof.Bp[s], witness[s]));
// pi_a = pi_a + A[s] * witness[s];
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
// pi_ap = pi_ap + Ap[s] * witness[s];
proof.pi_cp = G1.add( proof.pi_cp, G1.mulScalar( vk_proof.Cp[s], witness[s]));
// pi_ap = pi_ap + Ap[s] * witness[s];
proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[s], witness[s]));
}
proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[vk_proof.nVars], d1));
proof.pi_ap = G1.add( proof.pi_ap, G1.mulScalar( vk_proof.Ap[vk_proof.nVars], d1));
proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B[vk_proof.nVars], d2));
proof.pi_bp = G1.add( proof.pi_bp, G1.mulScalar( vk_proof.Bp[vk_proof.nVars], d2));
proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[vk_proof.nVars], d3));
proof.pi_cp = G1.add( proof.pi_cp, G1.mulScalar( vk_proof.Cp[vk_proof.nVars], d3));
proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars ], d1));
proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars+1], d2));
proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars+2], d3));
/*
let polA = [];
let polB = [];
let polC = [];
for (let s= 0; s< vk_proof.nVars; s++) {
polA = PolF.add(
polA,
PolF.mul(
vk_proof.polsA[s],
[witness[s]] ));
polB = PolF.add(
polB,
PolF.mul(
vk_proof.polsB[s],
[witness[s]] ));
polC = PolF.add(
polC,
PolF.mul(
vk_proof.polsC[s],
[witness[s]] ));
}
let polFull = PolF.sub(PolF.mul( polA, polB), polC);
const h = PolF.div(polFull, vk_proof.polZ );
*/
const h = calculateH(vk_proof, witness, d1, d2, d3);
// console.log(h.length + "/" + vk_proof.hExps.length);
for (let i = 0; i < h.length; i++) {
proof.pi_h = G1.add( proof.pi_h, G1.mulScalar( vk_proof.hExps[i], h[i]));
}
proof.pi_a = G1.affine(proof.pi_a);
proof.pi_b = G2.affine(proof.pi_b);
proof.pi_c = G1.affine(proof.pi_c);
proof.pi_ap = G1.affine(proof.pi_ap);
proof.pi_bp = G1.affine(proof.pi_bp);
proof.pi_cp = G1.affine(proof.pi_cp);
proof.pi_kp = G1.affine(proof.pi_kp);
proof.pi_h = G1.affine(proof.pi_h);
// proof.h=h;
proof.protocol = "original";
const publicSignals = witness.slice(1, vk_proof.nPublic+1);
return {proof, publicSignals};
};
function calculateH(vk_proof, witness, d1, d2, d3) {
const F = PolF.F;
const m = vk_proof.domainSize;
const polA_T = new Array(m).fill(PolF.F.zero);
const polB_T = new Array(m).fill(PolF.F.zero);
const polC_T = new Array(m).fill(PolF.F.zero);
for (let s=0; s<vk_proof.nVars; s++) {
for (let c in vk_proof.polsA[s]) {
polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
}
for (let c in vk_proof.polsB[s]) {
polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
}
for (let c in vk_proof.polsC[s]) {
polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
}
}
const polA_S = PolF.ifft(polA_T);
const polB_S = PolF.ifft(polB_T);
const polAB_S = PolF.mul(polA_S, polB_S);
const polC_S = PolF.ifft(polC_T);
const polABC_S = PolF.sub(polAB_S, polC_S);
const polZ_S = new Array(m+1).fill(F.zero);
polZ_S[m] = F.one;
polZ_S[0] = F.neg(F.one);
let H_S = PolF.div(polABC_S, polZ_S);
/*
const H2S = PolF.mul(H_S, polZ_S);
if (PolF.equals(H2S, polABC_S)) {
console.log("Is Divisible!");
} else {
console.log("ERROR: Not divisible!");
}
*/
/* add coefficients of the polynomial (d2*A + d1*B - d3) + d1*d2*Z */
H_S = PolF.extend(H_S, m+1);
for (let i=0; i<m; i++) {
const d2A = PolF.F.mul(d2, polA_S[i]);
const d1B = PolF.F.mul(d1, polB_S[i]);
H_S[i] = PolF.F.add(H_S[i], PolF.F.add(d2A, d1B));
}
H_S[0] = PolF.F.sub(H_S[0], d3);
// Z = x^m -1
const d1d2 = PolF.F.mul(d1, d2);
H_S[m] = PolF.F.add(H_S[m], d1d2);
H_S[0] = PolF.F.sub(H_S[0], d1d2);
H_S = PolF.reduce(PolF.affine(H_S));
return H_S;
}

127
src/ratfield.js Normal file
View File

@ -0,0 +1,127 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const fUtils = require("./futils.js");
class RatField {
constructor(F) {
this.F = F;
this.zero = [F.zero, F.one];
this.one = [F.one, F.one];
this.two = [F.two, F.one];
this.twoinv = [F.one, F.two];
this.q = F.q;
}
add(a,b) {
return [
this.F.add(
this.F.mul(a[0], b[1]),
this.F.mul(a[1], b[0])),
this.F.mul(a[1], b[1])];
}
double(a) {
return [this.F.add(a[0], a[0]), a[1]];
}
sub(a,b) {
return [
this.F.sub(
this.F.mul(a[0], b[1]),
this.F.mul(a[1], b[0])),
this.F.mul(a[1], b[1])];
}
neg(a) {
return [this.F.neg(a[0]), a[1]];
}
mul(a,b) {
return [
this.F.mul(a[0], b[0]),
this.F.mul(a[1], b[1]),
];
}
copy(a) {
return [a[0], a[1]];
}
div(a, b) {
return [
this.F.mul(a[0], b[1]),
this.F.mul(a[1], b[0]),
];
}
inverse(a) {
return [a[1], a[0]];
}
square(a) {
return [
this.F.square(a[0]),
this.F.square(a[1])
];
}
mulScalar(base, e) {
return [this.F.mulScalar(base[0], e) , base[1]];
}
exp(base, e) {
return fUtils.exp(this, base, e);
}
equals(a, b) {
return this.F.equals(
this.F.mul(a[0], b[1]),
this.F.mul(a[1], b[0])
);
}
isZero(a) {
return this.F.isZero(a[0]);
}
affine(a) {
return [this.F.div(a[0], a[1]), this.F.one];
}
toString(a) {
const ca = this.affine(a);
return `"0x${ca[0].toString(16)}"`;
}
random() {
return [this.F.random(), this.F.one];
}
fromF(a) {
return [a, this.F.one];
}
toF(a) {
return this.affine(a)[0];
}
}
module.exports = RatField;

212
src/setup_groth.js Normal file
View File

@ -0,0 +1,212 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
const bigInt = require("./bigint.js");
const BN128 = require("./bn128.js");
const PolField = require("./polfield.js");
const ZqField = require("./zqfield.js");
const bn128 = new BN128();
const G1 = bn128.G1;
const G2 = bn128.G2;
const PolF = new PolField(new ZqField(bn128.r));
const F = new ZqField(bn128.r);
module.exports = function setup(circuit) {
const setup = {
vk_proof : {
protocol: "groth",
nVars: circuit.nVars,
nPublic: circuit.nPubInputs + circuit.nOutputs
},
vk_verifier: {
protocol: "groth",
nPublic: circuit.nPubInputs + circuit.nOutputs
},
toxic: {}
};
setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
calculatePolinomials(setup, circuit);
setup.toxic.t = F.random();
calculateEncriptedValuesAtT(setup, circuit);
return setup;
};
function calculatePolinomials(setup, circuit) {
setup.vk_proof.polsA = new Array(circuit.nVars);
setup.vk_proof.polsB = new Array(circuit.nVars);
setup.vk_proof.polsC = new Array(circuit.nVars);
for (let i=0; i<circuit.nVars; i++) {
setup.vk_proof.polsA[i] = {};
setup.vk_proof.polsB[i] = {};
setup.vk_proof.polsC[i] = {};
}
for (let c=0; c<circuit.nConstraints; c++) {
for (let s in circuit.constraints[c][0]) {
setup.vk_proof.polsA[s][c] = bigInt(circuit.constraints[c][0][s]);
}
for (let s in circuit.constraints[c][1]) {
setup.vk_proof.polsB[s][c] = bigInt(circuit.constraints[c][1][s]);
}
for (let s in circuit.constraints[c][2]) {
setup.vk_proof.polsC[s][c] = bigInt(circuit.constraints[c][2][s]);
}
}
/**
* add and process the constraints
* input_i * 0 = 0
* to ensure soundness of input consistency
*/
for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
{
setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
}
}
function calculateValuesAtT(setup, circuit) {
const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
const a_t = new Array(circuit.nVars).fill(F.zero);
const b_t = new Array(circuit.nVars).fill(F.zero);
const c_t = new Array(circuit.nVars).fill(F.zero);
// TODO: substitute setup.polsA for coeficients
for (let s=0; s<circuit.nVars; s++) {
for (let c in setup.vk_proof.polsA[s]) {
a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
}
for (let c in setup.vk_proof.polsB[s]) {
b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
}
for (let c in setup.vk_proof.polsC[s]) {
c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
}
}
return {a_t, b_t, c_t, z_t};
}
function calculateEncriptedValuesAtT(setup, circuit) {
const v = calculateValuesAtT(setup, circuit);
setup.vk_proof.A = new Array(circuit.nVars);
setup.vk_proof.B1 = new Array(circuit.nVars);
setup.vk_proof.B2 = new Array(circuit.nVars);
setup.vk_proof.C = new Array(circuit.nVars);
setup.vk_verifier.IC = new Array(circuit.nPublic);
setup.toxic.kalfa = F.random();
setup.toxic.kbeta = F.random();
setup.toxic.kgamma = F.random();
setup.toxic.kdelta = F.random();
let invDelta = F.inverse(setup.toxic.kdelta);
let invGamma = F.inverse(setup.toxic.kgamma);
setup.vk_proof.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
setup.vk_proof.vk_beta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kbeta));
setup.vk_proof.vk_delta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kdelta));
setup.vk_proof.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
setup.vk_proof.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
setup.vk_verifier.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
setup.vk_verifier.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
setup.vk_verifier.vk_gamma_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
setup.vk_verifier.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
setup.vk_verifier.vk_alfabeta_12 = bn128.F12.affine(bn128.pairing( setup.vk_verifier.vk_alfa_1 , setup.vk_verifier.vk_beta_2 ));
for (let s=0; s<circuit.nVars; s++) {
const A = G1.affine(G1.mulScalar(G1.g, v.a_t[s]));
setup.vk_proof.A[s] = A;
const B1 = G1.affine(G1.mulScalar(G1.g, v.b_t[s]));
setup.vk_proof.B1[s] = B1;
const B2 = G2.affine(G2.mulScalar(G2.g, v.b_t[s]));
setup.vk_proof.B2[s] = B2;
}
for (let s=0; s<=setup.vk_proof.nPublic; s++) {
let ps =
F.mul(
invGamma,
F.add(
F.add(
F.mul(v.a_t[s], setup.toxic.kbeta),
F.mul(v.b_t[s], setup.toxic.kalfa)),
v.c_t[s]));
const IC = G1.affine(G1.mulScalar(G1.g, ps));
setup.vk_verifier.IC[s]=IC;
}
for (let s=setup.vk_proof.nPublic+1; s<circuit.nVars; s++) {
let ps =
F.mul(
invDelta,
F.add(
F.add(
F.mul(v.a_t[s], setup.toxic.kbeta),
F.mul(v.b_t[s], setup.toxic.kalfa)),
v.c_t[s]));
const C = G1.affine(G1.mulScalar(G1.g, ps));
setup.vk_proof.C[s]=C;
}
// Calculate HExps
const maxH = setup.vk_proof.domainSize+1;
setup.vk_proof.hExps = new Array(maxH);
const zod = F.mul(invDelta, v.z_t);
setup.vk_proof.hExps[0] = G1.affine(G1.mulScalar(G1.g, zod));
let eT = setup.toxic.t;
for (let i=1; i<maxH; i++) {
setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, F.mul(eT, zod)));
eT = F.mul(eT, setup.toxic.t);
}
}

233
src/setup_kimleeoh.js Normal file
View File

@ -0,0 +1,233 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
const bigInt = require("./bigint.js");
const BN128 = require("./bn128.js");
const PolField = require("./polfield.js");
const ZqField = require("./zqfield.js");
const bn128 = new BN128();
const G1 = bn128.G1;
const G2 = bn128.G2;
const PolF = new PolField(new ZqField(bn128.r));
const F = new ZqField(bn128.r);
module.exports = function setup(circuit) {
const setup = {
vk_proof : {
protocol: "groth",
nVars: circuit.nVars,
nPublic: circuit.nPubInputs + circuit.nOutputs
},
vk_verifier: {
protocol: "groth",
nPublic: circuit.nPubInputs + circuit.nOutputs
},
toxic: {}
};
setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
calculatePolinomials(setup, circuit);
setup.toxic.t = F.random();
calculateEncriptedValuesAtT(setup, circuit);
return setup;
};
function calculatePolinomials(setup, circuit) {
setup.vk_proof.polsA = new Array(circuit.nVars);
setup.vk_proof.polsB = new Array(circuit.nVars);
setup.vk_proof.polsC = new Array(circuit.nVars);
for (let i=0; i<circuit.nVars; i++) {
setup.vk_proof.polsA[i] = {};
setup.vk_proof.polsB[i] = {};
setup.vk_proof.polsC[i] = {};
}
for (let c=0; c<circuit.nConstraints; c++) {
for (let s in circuit.constraints[c][0]) {
setup.vk_proof.polsA[s][c] = bigInt(circuit.constraints[c][0][s]);
}
for (let s in circuit.constraints[c][1]) {
setup.vk_proof.polsB[s][c] = bigInt(circuit.constraints[c][1][s]);
}
for (let s in circuit.constraints[c][2]) {
setup.vk_proof.polsC[s][c] = bigInt(circuit.constraints[c][2][s]);
}
}
/**
* add and process the constraints
* input_i * 0 = 0
* to ensure soundness of input consistency
*/
for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
{
setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
}
}
function calculateValuesAtT(setup, circuit) {
const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
const a_t = new Array(circuit.nVars).fill(F.zero);
const b_t = new Array(circuit.nVars).fill(F.zero);
const c_t = new Array(circuit.nVars).fill(F.zero);
// TODO: substitute setup.polsA for coeficients
for (let s=0; s<circuit.nVars; s++) {
for (let c in setup.vk_proof.polsA[s]) {
a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
}
for (let c in setup.vk_proof.polsB[s]) {
b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
}
for (let c in setup.vk_proof.polsC[s]) {
c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
}
}
return {a_t, b_t, c_t, z_t};
}
function calculateEncriptedValuesAtT(setup, circuit) {
const v = calculateValuesAtT(setup, circuit);
setup.vk_proof.A = new Array(circuit.nVars);
setup.vk_proof.Adelta = new Array(circuit.nVars);
setup.vk_proof.B1 = new Array(circuit.nVars);
setup.vk_proof.B2 = new Array(circuit.nVars);
setup.vk_proof.C = new Array(circuit.nVars);
setup.vk_verifier.IC = new Array(circuit.nPublic);
setup.toxic.kalfa = F.random();
setup.toxic.kbeta = F.random();
setup.toxic.kgamma = F.random();
setup.toxic.kdelta = F.random();
const gammaSquare = F.mul(setup.toxic.kgamma, setup.toxic.kgamma);
setup.vk_proof.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
setup.vk_proof.vk_beta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kbeta));
setup.vk_proof.vk_delta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kdelta));
setup.vk_proof.vk_alfadelta_1 = G1.affine(G1.mulScalar( G1.g, F.mul(setup.toxic.kalfa, setup.toxic.kdelta)));
setup.vk_proof.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
setup.vk_verifier.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
setup.vk_verifier.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
setup.vk_verifier.vk_gamma_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
setup.vk_verifier.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
setup.vk_verifier.vk_alfabeta_12 = bn128.F12.affine(bn128.pairing( setup.vk_verifier.vk_alfa_1 , setup.vk_verifier.vk_beta_2 ));
for (let s=0; s<circuit.nVars; s++) {
const A = G1.affine(G1.mulScalar(G1.g, F.mul(setup.toxic.kgamma, v.a_t[s])));
setup.vk_proof.A[s] = A;
setup.vk_proof.Adelta[s] = G1.affine(G1.mulScalar(A, setup.toxic.kdelta));
const B1 = G1.affine(G1.mulScalar(G1.g, F.mul(setup.toxic.kgamma, v.b_t[s])));
setup.vk_proof.B1[s] = B1;
const B2 = G2.affine(G2.mulScalar(G2.g, F.mul(setup.toxic.kgamma, v.b_t[s])));
setup.vk_proof.B2[s] = B2;
}
for (let s=0; s<=setup.vk_proof.nPublic; s++) {
let ps =
F.add(
F.mul(
setup.toxic.kgamma,
v.c_t[s]
),
F.add(
F.mul(
setup.toxic.kbeta,
v.a_t[s]
),
F.mul(
setup.toxic.kalfa,
v.b_t[s]
)
)
);
const IC = G1.affine(G1.mulScalar(G1.g, ps));
setup.vk_verifier.IC[s]=IC;
}
for (let s=setup.vk_proof.nPublic+1; s<circuit.nVars; s++) {
let ps =
F.add(
F.mul(
gammaSquare,
v.c_t[s]
),
F.add(
F.mul(
F.mul(setup.toxic.kbeta, setup.toxic.kgamma),
v.a_t[s]
),
F.mul(
F.mul(setup.toxic.kalfa, setup.toxic.kgamma),
v.b_t[s]
)
)
);
const C = G1.affine(G1.mulScalar(G1.g, ps));
setup.vk_proof.C[s]=C;
}
// Calculate HExps
const maxH = setup.vk_proof.domainSize+1;
setup.vk_proof.hExps = new Array(maxH);
const zod = F.mul(gammaSquare, v.z_t);
setup.vk_proof.hExps[0] = G1.affine(G1.mulScalar(G1.g, zod));
let eT = setup.toxic.t;
for (let i=1; i<maxH; i++) {
setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, F.mul(eT, zod)));
eT = F.mul(eT, setup.toxic.t);
}
}

238
src/setup_original.js Normal file
View File

@ -0,0 +1,238 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint.js");
const BN128 = require("./bn128.js");
const PolField = require("./polfield.js");
const ZqField = require("./zqfield.js");
const bn128 = new BN128();
const G1 = bn128.G1;
const G2 = bn128.G2;
const PolF = new PolField(new ZqField(bn128.r));
const F = new ZqField(bn128.r);
module.exports = function setup(circuit) {
const setup = {
vk_proof : {
protocol: "original",
nVars: circuit.nVars,
nPublic: circuit.nPubInputs + circuit.nOutputs
},
vk_verifier: {
protocol: "original",
nPublic: circuit.nPubInputs + circuit.nOutputs
},
toxic: {}
};
setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
calculatePolinomials(setup, circuit);
setup.toxic.t = F.random();
calculateEncriptedValuesAtT(setup, circuit);
calculateHexps(setup, circuit);
return setup;
};
function calculatePolinomials(setup, circuit) {
setup.vk_proof.polsA = new Array(circuit.nVars);
setup.vk_proof.polsB = new Array(circuit.nVars);
setup.vk_proof.polsC = new Array(circuit.nVars);
for (let i=0; i<circuit.nVars; i++) {
setup.vk_proof.polsA[i] = {};
setup.vk_proof.polsB[i] = {};
setup.vk_proof.polsC[i] = {};
}
for (let c=0; c<circuit.nConstraints; c++) {
for (let s in circuit.constraints[c][0]) {
setup.vk_proof.polsA[s][c] = bigInt(circuit.constraints[c][0][s]);
}
for (let s in circuit.constraints[c][1]) {
setup.vk_proof.polsB[s][c] = bigInt(circuit.constraints[c][1][s]);
}
for (let s in circuit.constraints[c][2]) {
setup.vk_proof.polsC[s][c] = bigInt(circuit.constraints[c][2][s]);
}
}
/**
* add and process the constraints
* input_i * 0 = 0
* to ensure soundness of input consistency
*/
for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
{
setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
}
}
function calculateValuesAtT(setup, circuit) {
const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
const a_t = new Array(circuit.nVars).fill(F.zero);
const b_t = new Array(circuit.nVars).fill(F.zero);
const c_t = new Array(circuit.nVars).fill(F.zero);
// TODO: substitute setup.polsA for coeficients
for (let s=0; s<circuit.nVars; s++) {
for (let c in setup.vk_proof.polsA[s]) {
a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
}
for (let c in setup.vk_proof.polsB[s]) {
b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
}
for (let c in setup.vk_proof.polsC[s]) {
c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
}
}
return {a_t, b_t, c_t, z_t};
}
function calculateEncriptedValuesAtT(setup, circuit) {
const v = calculateValuesAtT(setup, circuit);
setup.vk_proof.A = new Array(circuit.nVars+1);
setup.vk_proof.B = new Array(circuit.nVars+1);
setup.vk_proof.C = new Array(circuit.nVars+1);
setup.vk_proof.Ap = new Array(circuit.nVars+1);
setup.vk_proof.Bp = new Array(circuit.nVars+1);
setup.vk_proof.Cp = new Array(circuit.nVars+1);
setup.vk_proof.Kp = new Array(circuit.nVars+3);
setup.vk_verifier.IC = new Array(circuit.nPublic);
setup.toxic.ka = F.random();
setup.toxic.kb = F.random();
setup.toxic.kc = F.random();
setup.toxic.ra = F.random();
setup.toxic.rb = F.random();
setup.toxic.rc = F.mul(setup.toxic.ra, setup.toxic.rb);
setup.toxic.kbeta = F.random();
setup.toxic.kgamma = F.random();
const gb = F.mul(setup.toxic.kbeta, setup.toxic.kgamma);
setup.vk_verifier.vk_a = G2.affine(G2.mulScalar( G2.g, setup.toxic.ka));
setup.vk_verifier.vk_b = G1.affine(G1.mulScalar( G1.g, setup.toxic.kb));
setup.vk_verifier.vk_c = G2.affine(G2.mulScalar( G2.g, setup.toxic.kc));
setup.vk_verifier.vk_gb_1 = G1.affine(G1.mulScalar( G1.g, gb));
setup.vk_verifier.vk_gb_2 = G2.affine(G2.mulScalar( G2.g, gb));
setup.vk_verifier.vk_g = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
for (let s=0; s<circuit.nVars; s++) {
// A[i] = G1 * polA(t)
const raat = F.mul(setup.toxic.ra, v.a_t[s]);
const A = G1.affine(G1.mulScalar(G1.g, raat));
setup.vk_proof.A[s] = A;
if (s <= setup.vk_proof.nPublic) {
setup.vk_verifier.IC[s]=A;
}
// B1[i] = G1 * polB(t)
const rbbt = F.mul(setup.toxic.rb, v.b_t[s]);
const B1 = G1.affine(G1.mulScalar(G1.g, rbbt));
// B2[i] = G2 * polB(t)
const B2 = G2.affine(G2.mulScalar(G2.g, rbbt));
setup.vk_proof.B[s]=B2;
// C[i] = G1 * polC(t)
const rcct = F.mul(setup.toxic.rc, v.c_t[s]);
const C = G1.affine(G1.mulScalar( G1.g, rcct));
setup.vk_proof.C[s] =C;
// K = G1 * (A+B+C)
const kt = F.affine(F.add(F.add(raat, rbbt), rcct));
const K = G1.affine(G1.mulScalar( G1.g, kt));
/*
// Comment this lines to improve the process
const Ktest = G1.affine(G1.add(G1.add(A, B1), C));
if (!G1.equals(K, Ktest)) {
console.log ("=====FAIL======");
}
*/
if (s > setup.vk_proof.nPublic) {
setup.vk_proof.Ap[s] = G1.affine(G1.mulScalar(A, setup.toxic.ka));
}
setup.vk_proof.Bp[s] = G1.affine(G1.mulScalar(B1, setup.toxic.kb));
setup.vk_proof.Cp[s] = G1.affine(G1.mulScalar(C, setup.toxic.kc));
setup.vk_proof.Kp[s] = G1.affine(G1.mulScalar(K, setup.toxic.kbeta));
}
// Extra coeficients
const A = G1.mulScalar( G1.g, F.mul(setup.toxic.ra, v.z_t));
setup.vk_proof.A[circuit.nVars] = G1.affine(A);
setup.vk_proof.Ap[circuit.nVars] = G1.affine(G1.mulScalar(A, setup.toxic.ka));
const B1 = G1.mulScalar( G1.g, F.mul(setup.toxic.rb, v.z_t));
const B2 = G2.mulScalar( G2.g, F.mul(setup.toxic.rb, v.z_t));
setup.vk_proof.B[circuit.nVars] = G2.affine(B2);
setup.vk_proof.Bp[circuit.nVars] = G1.affine(G1.mulScalar(B1, setup.toxic.kb));
const C = G1.mulScalar( G1.g, F.mul(setup.toxic.rc, v.z_t));
setup.vk_proof.C[circuit.nVars] = G1.affine(C);
setup.vk_proof.Cp[circuit.nVars] = G1.affine(G1.mulScalar(C, setup.toxic.kc));
setup.vk_proof.Kp[circuit.nVars ] = G1.affine(G1.mulScalar(A, setup.toxic.kbeta));
setup.vk_proof.Kp[circuit.nVars+1] = G1.affine(G1.mulScalar(B1, setup.toxic.kbeta));
setup.vk_proof.Kp[circuit.nVars+2] = G1.affine(G1.mulScalar(C, setup.toxic.kbeta));
// setup.vk_verifier.A[0] = G1.affine(G1.add(setup.vk_verifier.A[0], setup.vk_proof.A[circuit.nVars]));
// vk_z
setup.vk_verifier.vk_z = G2.affine(G2.mulScalar(
G2.g,
F.mul(setup.toxic.rc, v.z_t)));
}
function calculateHexps(setup) {
const maxH = setup.vk_proof.domainSize+1;
setup.vk_proof.hExps = new Array(maxH);
setup.vk_proof.hExps[0] = G1.g;
let eT = setup.toxic.t;
for (let i=1; i<maxH; i++) {
setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, eT));
eT = F.mul(eT, setup.toxic.t);
}
}

55
src/stringifybigint.js Normal file
View File

@ -0,0 +1,55 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint.js");
module.exports.stringifyBigInts = stringifyBigInts;
module.exports.unstringifyBigInts = unstringifyBigInts;
function stringifyBigInts(o) {
if ((typeof(o) == "bigint") || o.isZero !== undefined) {
return o.toString(10);
} else if (Array.isArray(o)) {
return o.map(stringifyBigInts);
} else if (typeof o == "object") {
const res = {};
for (let k in o) {
res[k] = stringifyBigInts(o[k]);
}
return res;
} else {
return o;
}
}
function unstringifyBigInts(o) {
if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
return bigInt(o);
} else if (Array.isArray(o)) {
return o.map(unstringifyBigInts);
} else if (typeof o == "object") {
const res = {};
for (let k in o) {
res[k] = unstringifyBigInts(o[k]);
}
return res;
} else {
return o;
}
}

67
src/verifier.js Normal file
View File

@ -0,0 +1,67 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const BN128 = require("./bn128.js");
const bn128 = new BN128();
const G1 = bn128.G1;
const G2 = bn128.G2;
module.exports = function isValid(vk_verifier, proof, publicSignals) {
let full_pi_a = vk_verifier.A[0];
for (let s= 0; s< vk_verifier.nPublic; s++) {
full_pi_a = G1.add( full_pi_a, G1.mulScalar( vk_verifier.A[s+1], publicSignals[s]));
}
full_pi_a = G1.add( full_pi_a, proof.pi_a);
if (! bn128.F12.equals(
bn128.pairing( proof.pi_a , vk_verifier.vk_a ),
bn128.pairing( proof.pi_ap , G2.g )))
return false;
if (! bn128.F12.equals(
bn128.pairing( vk_verifier.vk_b, proof.pi_b ),
bn128.pairing( proof.pi_bp , G2.g )))
return false;
if (! bn128.F12.equals(
bn128.pairing( proof.pi_c , vk_verifier.vk_c ),
bn128.pairing( proof.pi_cp , G2.g )))
return false;
if (! bn128.F12.equals(
bn128.F12.mul(
bn128.pairing( G1.add(full_pi_a, proof.pi_c) , vk_verifier.vk_gb_2 ),
bn128.pairing( vk_verifier.vk_gb_1 , proof.pi_b ),
),
bn128.pairing( proof.pi_kp , vk_verifier.vk_g )))
return false;
if (! bn128.F12.equals(
bn128.pairing( full_pi_a , proof.pi_b ),
bn128.F12.mul(
bn128.pairing( proof.pi_h , vk_verifier.vk_z ),
bn128.pairing( proof.pi_c , G2.g ),
)))
return false;
return true;
};

46
src/verifier_groth.js Normal file
View File

@ -0,0 +1,46 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
const BN128 = require("./bn128.js");
const bn128 = new BN128();
const G1 = bn128.G1;
module.exports = function isValid(vk_verifier, proof, publicSignals) {
let cpub = vk_verifier.IC[0];
for (let s= 0; s< vk_verifier.nPublic; s++) {
cpub = G1.add( cpub, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
}
if (! bn128.F12.equals(
bn128.pairing( proof.pi_a , proof.pi_b ),
bn128.F12.mul(
vk_verifier.vk_alfabeta_12,
bn128.F12.mul(
bn128.pairing( cpub , vk_verifier.vk_gamma_2 ),
bn128.pairing( proof.pi_c , vk_verifier.vk_delta_2 )
))))
return false;
return true;
};

75
src/verifier_kimleeoh.js Normal file
View File

@ -0,0 +1,75 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
const BN128 = require("./bn128.js");
const createKeccakHash = require("keccak");
const bigInt = require("./bigint");
const bn128 = new BN128();
const G1 = bn128.G1;
const G2 = bn128.G2;
module.exports = function isValid(vk_verifier, proof, publicSignals) {
let cpub = vk_verifier.IC[0];
for (let s= 0; s< vk_verifier.nPublic; s++) {
cpub = G1.add( cpub, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
}
const buff = Buffer.concat([
proof.pi_a[0].beInt2Buff(32),
proof.pi_a[1].beInt2Buff(32),
proof.pi_b[0][0].beInt2Buff(32),
proof.pi_b[0][1].beInt2Buff(32),
proof.pi_b[1][0].beInt2Buff(32),
proof.pi_b[1][1].beInt2Buff(32)
]);
const h1buff = createKeccakHash("keccak256").update(buff).digest();
const h2buff = createKeccakHash("keccak256").update(h1buff).digest();
const h1 = bigInt.beBuff2int(h1buff);
const h2 = bigInt.beBuff2int(h2buff);
// const h1 = bigInt.zero;
// const h2 = bigInt.zero;
console.log(h1.toString());
console.log(h2.toString());
if (! bn128.F12.equals(
bn128.pairing(
G1.add(proof.pi_a, G1.mulScalar(G1.g, h1)),
G2.add(proof.pi_b, G2.mulScalar(vk_verifier.vk_delta_2, h2))
),
bn128.F12.mul(
vk_verifier.vk_alfabeta_12,
bn128.F12.mul(
bn128.pairing( cpub , vk_verifier.vk_gamma_2 ),
bn128.pairing( proof.pi_c , G2.g )
))))
return false;
return true;
};

67
src/verifier_original.js Normal file
View File

@ -0,0 +1,67 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const BN128 = require("./bn128.js");
const bn128 = new BN128();
const G1 = bn128.G1;
const G2 = bn128.G2;
module.exports = function isValid(vk_verifier, proof, publicSignals) {
let full_pi_a = vk_verifier.IC[0];
for (let s= 0; s< vk_verifier.nPublic; s++) {
full_pi_a = G1.add( full_pi_a, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
}
full_pi_a = G1.add( full_pi_a, proof.pi_a);
if (! bn128.F12.equals(
bn128.pairing( proof.pi_a , vk_verifier.vk_a ),
bn128.pairing( proof.pi_ap , G2.g )))
return false;
if (! bn128.F12.equals(
bn128.pairing( vk_verifier.vk_b, proof.pi_b ),
bn128.pairing( proof.pi_bp , G2.g )))
return false;
if (! bn128.F12.equals(
bn128.pairing( proof.pi_c , vk_verifier.vk_c ),
bn128.pairing( proof.pi_cp , G2.g )))
return false;
if (! bn128.F12.equals(
bn128.F12.mul(
bn128.pairing( G1.add(full_pi_a, proof.pi_c) , vk_verifier.vk_gb_2 ),
bn128.pairing( vk_verifier.vk_gb_1 , proof.pi_b )
),
bn128.pairing( proof.pi_kp , vk_verifier.vk_g )))
return false;
if (! bn128.F12.equals(
bn128.pairing( full_pi_a , proof.pi_b ),
bn128.F12.mul(
bn128.pairing( proof.pi_h , vk_verifier.vk_z ),
bn128.pairing( proof.pi_c , G2.g )
)))
return false;
return true;
};

151
src/zqfield.js Normal file
View File

@ -0,0 +1,151 @@
/*
Copyright 2018 0kims association.
This file is part of snarkjs.
snarkjs is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
snarkjs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const bigInt = require("./bigint");
const fUtils = require("./futils.js");
function getRandomByte() {
if (typeof window !== "undefined") { // Browser
if (typeof window.crypto !== "undefined") { // Supported
let array = new Uint8Array(1);
window.crypto.getRandomValues(array);
return array[0];
}
else { // fallback
return Math.floor(Math.random() * 256);
}
}
else { // NodeJS
return module.require("crypto").randomBytes(1)[0];
}
}
class ZqField {
constructor(q) {
this.q = bigInt(q);
this.zero = bigInt.zero;
this.one = bigInt.one;
this.minusone = this.q.sub(this.one);
this.add = bigInt.genAdd();
this.double = bigInt.genDouble();
this.sub = bigInt.genSub();
this.neg = bigInt.genNeg();
this.mul = bigInt.genMul(q);
this.inverse = bigInt.genInverse(q);
this.square = bigInt.genSquare(q);
this.equals = bigInt.genEquals(q);
this.affine = bigInt.genAffine(q);
this.isZero = bigInt.genIsZero(q);
this.two = this.add(this.one, this.one);
this.twoinv = this.inverse(this.two);
const e = this.minusone.shr(this.one);
this.nqr = this.two;
let r = this.exp(this.nqr, e);
while (!r.equals(this.minusone)) {
this.nqr = this.nqr.add(this.one);
r = this.exp(this.nqr, e);
}
this.s = this.zero;
this.t = this.minusone;
while (!this.t.isOdd()) {
this.s = this.s.add(this.one);
this.t = this.t.shr(this.one);
}
this.nqr_to_t = this.exp(this.nqr, this.t);
}
copy(a) {
return bigInt(a);
}
div(a, b) {
return this.mul(a, this.inverse(b));
}
mulScalar(base, e) {
return this.mul(base, bigInt(e));
}
exp(base, e) {
return fUtils.exp(this, base, e);
}
toString(a) {
const ca = this.affine(a);
return `"0x${ca.toString(16)}"`;
}
random() {
let res = bigInt(0);
let n = bigInt(this.q);
while (!n.isZero()) {
res = res.shl(8).add(bigInt(getRandomByte()));
n = n.shr(8);
}
return res;
}
sqrt(n) {
n = this.affine(n);
if (n.equals(this.zero)) return this.zero;
// Test that have solution
const res = this.exp(n, this.minusone.shr(this.one));
if (!res.equals(this.one)) return null;
let m = parseInt(this.s);
let c = this.nqr_to_t;
let t = this.exp(n, this.t);
let r = this.exp(n, this.add(this.t, this.one).shr(this.one) );
while (!t.equals(this.one)) {
let sq = this.square(t);
let i = 1;
while (!sq.equals(this.one)) {
i++;
sq = this.square(sq);
}
// b = c ^ m-i-1
let b = c;
for (let j=0; j< m-i-1; j ++) b = this.square(b);
m = i;
c = this.square(b);
t = this.mul(t, c);
r = this.mul(r, b);
}
if (r.greater(this.q.shr(this.one))) {
r = this.neg(r);
}
return r;
}
}
module.exports = ZqField;

View File

@ -0,0 +1,228 @@
//
// Copyright 2017 Christian Reitwiessner
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// 2019 OKIMS
// ported to solidity 0.5
// fixed linter warnings
// added requiere error messages
//
pragma solidity ^0.5.0;
library Pairing {
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() internal pure returns (G2Point memory) {
// Original code point
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
/*
// Changed by Jordi point
return G2Point(
[10857046999023057135944570762232829481370756359578518086990519993285655852781,
11559732032986387107991004021392285783925812861821192530917403151452391805634],
[8495653923123431417604973247489272438418190587263600148770280649306958101930,
4082367875863433681332203403145435568316851327593401208105741076214120093531]
);
*/
}
/// @return the negation of p, i.e. p.addition(p.negate()) should be zero.
function negate(G1Point memory p) internal pure returns (G1Point memory) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
// solium-disable-next-line security/no-inline-assembly
assembly {
success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success,"pairing-add-failed");
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
function scalar_mul(G1Point memory p, uint s) internal view returns (G1Point memory r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
// solium-disable-next-line security/no-inline-assembly
assembly {
success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require (success,"pairing-mul-failed");
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length,"pairing-lengths-failed");
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
// solium-disable-next-line security/no-inline-assembly
assembly {
success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success,"pairing-opcode-failed");
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for three pairs.
function pairingProd3(
G1Point memory a1, G2Point memory a2,
G1Point memory b1, G2Point memory b2,
G1Point memory c1, G2Point memory c2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](3);
G2Point[] memory p2 = new G2Point[](3);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for four pairs.
function pairingProd4(
G1Point memory a1, G2Point memory a2,
G1Point memory b1, G2Point memory b2,
G1Point memory c1, G2Point memory c2,
G1Point memory d1, G2Point memory d2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](4);
G2Point[] memory p2 = new G2Point[](4);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p1[3] = d1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
p2[3] = d2;
return pairing(p1, p2);
}
}
contract Verifier {
using Pairing for *;
struct VerifyingKey {
Pairing.G1Point alfa1;
Pairing.G2Point beta2;
Pairing.G2Point gamma2;
Pairing.G2Point delta2;
Pairing.G1Point[] IC;
}
struct Proof {
Pairing.G1Point A;
Pairing.G2Point B;
Pairing.G1Point C;
}
function verifyingKey() internal pure returns (VerifyingKey memory vk) {
vk.alfa1 = Pairing.G1Point(<%vk_alfa1%>);
vk.beta2 = Pairing.G2Point(<%vk_beta2%>);
vk.gamma2 = Pairing.G2Point(<%vk_gamma2%>);
vk.delta2 = Pairing.G2Point(<%vk_delta2%>);
vk.IC = new Pairing.G1Point[](<%vk_ic_length%>);
<%vk_ic_pts%>
}
function verify(uint[] memory input, Proof memory proof) internal view returns (uint) {
uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.IC.length,"verifier-bad-input");
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++) {
require(input[i] < snark_scalar_field,"verifier-gte-snark-scalar-field");
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
}
vk_x = Pairing.addition(vk_x, vk.IC[0]);
if (!Pairing.pairingProd4(
Pairing.negate(proof.A), proof.B,
vk.alfa1, vk.beta2,
vk_x, vk.gamma2,
proof.C, vk.delta2
)) return 1;
return 0;
}
function verifyProof(
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[<%vk_input_length%>] memory input
) public view returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.C = Pairing.G1Point(c[0], c[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
return true;
} else {
return false;
}
}
function verifyProof(bytes calldata proof, uint[<%vk_input_length%>] calldata inputs) external view returns (bool r) {
// solidity does not support decoding uint[2][2] yet
(uint[2] memory a, uint[2] memory b1, uint[2] memory b2, uint[2] memory c) = abi.decode(proof, (uint[2], uint[2], uint[2], uint[2]));
return verifyProof(a, [b1, b2], c, inputs);
}
}

View File

@ -0,0 +1,219 @@
//
// Copyright 2017 Christian Reitwiessner
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.4.17;
library Pairing {
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() pure internal returns (G1Point) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() pure internal returns (G2Point) {
// Original code point
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
/*
// Changed by Jordi point
return G2Point(
[10857046999023057135944570762232829481370756359578518086990519993285655852781,
11559732032986387107991004021392285783925812861821192530917403151452391805634],
[8495653923123431417604973247489272438418190587263600148770280649306958101930,
4082367875863433681332203403145435568316851327593401208105741076214120093531]
);
*/
}
/// @return the negation of p, i.e. p.addition(p.negate()) should be zero.
function negate(G1Point p) pure internal returns (G1Point) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function addition(G1Point p1, G1Point p2) view internal returns (G1Point r) {
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
assembly {
success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
function scalar_mul(G1Point p, uint s) view internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require (success);
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] p1, G2Point[] p2) view internal returns (bool) {
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) view internal returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for three pairs.
function pairingProd3(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2
) view internal returns (bool) {
G1Point[] memory p1 = new G1Point[](3);
G2Point[] memory p2 = new G2Point[](3);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for four pairs.
function pairingProd4(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2,
G1Point d1, G2Point d2
) view internal returns (bool) {
G1Point[] memory p1 = new G1Point[](4);
G2Point[] memory p2 = new G2Point[](4);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p1[3] = d1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
p2[3] = d2;
return pairing(p1, p2);
}
}
contract Verifier {
using Pairing for *;
struct VerifyingKey {
Pairing.G1Point alfa1;
Pairing.G2Point beta2;
Pairing.G2Point gamma2;
Pairing.G2Point delta2;
Pairing.G1Point[] IC;
}
struct Proof {
Pairing.G1Point A;
Pairing.G2Point B;
Pairing.G1Point C;
}
function verifyingKey() pure internal returns (VerifyingKey vk) {
vk.alfa1 = Pairing.G1Point(<%vk_alfa1%>);
vk.beta2 = Pairing.G2Point(<%vk_beta2%>);
vk.gamma2 = Pairing.G2Point(<%vk_gamma2%>);
vk.delta2 = Pairing.G2Point(<%vk_delta2%>);
vk.IC = new Pairing.G1Point[](<%vk_ic_length%>);
<%vk_ic_pts%>
}
function verify(uint[] input, Proof proof) view internal returns (uint) {
uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.IC.length);
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++) {
require(input[i] < snark_scalar_field,"verifier-gte-snark-scalar-field");
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
}
vk_x = Pairing.addition(vk_x, vk.IC[0]);
if (!Pairing.pairingProd4(
Pairing.negate(proof.A), proof.B,
vk.alfa1, vk.beta2,
vk_x, vk.gamma2,
proof.C, vk.delta2
)) return 1;
return 0;
}
function verifyProof(
uint[2] a,
uint[2][2] b,
uint[2] c,
uint[<%vk_input_length%>] input
) view public returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.C = Pairing.G1Point(c[0], c[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
return true;
} else {
return false;
}
}
function verifyProof(bytes calldata proof, uint[<%vk_input_length%>] calldata inputs) external view returns (bool r) {
// solidity does not support decoding uint[2][2] yet
(uint[2] memory a, uint[2] memory b1, uint[2] memory b2, uint[2] memory c) = abi.decode(proof, (uint[2], uint[2], uint[2], uint[2]));
return verifyProof(a, [b1, b2], c, inputs);
}
}

View File

@ -0,0 +1,260 @@
//
// Copyright 2017 Christian Reitwiessner
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// 2019 OKIMS
// ported to solidity 0.5
// fixed linter warnings
// added requiere error messages
//
pragma solidity ^0.5.0;
library Pairing {
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() internal pure returns (G2Point memory) {
// Original code point
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
}
/// @return the negation of p, i.e. p.addition(p.negate()) should be zero.
function negate(G1Point memory p) internal pure returns (G1Point memory) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
// solium-disable-next-line security/no-inline-assembly
assembly {
success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success,"pairing-add-failed");
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
function scalar_mul(G1Point memory p, uint s) internal view returns (G1Point memory r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
// solium-disable-next-line security/no-inline-assembly
assembly {
success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require (success,"pairing-mul-failed");
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length,"pairing-lengths-failed");
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
// solium-disable-next-line security/no-inline-assembly
assembly {
success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success,"pairing-opcode-failed");
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for three pairs.
function pairingProd3(
G1Point memory a1, G2Point memory a2,
G1Point memory b1, G2Point memory b2,
G1Point memory c1, G2Point memory c2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](3);
G2Point[] memory p2 = new G2Point[](3);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for four pairs.
function pairingProd4(
G1Point memory a1, G2Point memory a2,
G1Point memory b1, G2Point memory b2,
G1Point memory c1, G2Point memory c2,
G1Point memory d1, G2Point memory d2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](4);
G2Point[] memory p2 = new G2Point[](4);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p1[3] = d1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
p2[3] = d2;
return pairing(p1, p2);
}
}
contract Verifier {
using Pairing for *;
struct VerifyingKey {
Pairing.G2Point A;
Pairing.G1Point B;
Pairing.G2Point C;
Pairing.G2Point gamma;
Pairing.G1Point gammaBeta1;
Pairing.G2Point gammaBeta2;
Pairing.G2Point Z;
Pairing.G1Point[] IC;
}
struct Proof {
Pairing.G1Point A;
Pairing.G1Point A_p;
Pairing.G2Point B;
Pairing.G1Point B_p;
Pairing.G1Point C;
Pairing.G1Point C_p;
Pairing.G1Point K;
Pairing.G1Point H;
}
function verifyingKey() internal pure returns (VerifyingKey memory vk) {
vk.A = Pairing.G2Point(<%vk_a%>);
vk.B = Pairing.G1Point(<%vk_b%>);
vk.C = Pairing.G2Point(<%vk_c%>);
vk.gamma = Pairing.G2Point(<%vk_g%>);
vk.gammaBeta1 = Pairing.G1Point(<%vk_gb1%>);
vk.gammaBeta2 = Pairing.G2Point(<%vk_gb2%>);
vk.Z = Pairing.G2Point(<%vk_z%>);
vk.IC = new Pairing.G1Point[](<%vk_ic_length%>);
<%vk_ic_pts%>
}
function verify(uint[] memory input, Proof memory proof) internal view returns (uint) {
uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.IC.length,"verifier-bad-input");
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++) {
require(input[i] < snark_scalar_field,"verifier-gte-snark-scalar-field");
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
}
vk_x = Pairing.addition(vk_x, vk.IC[0]);
if (!Pairing.pairingProd2(proof.A, vk.A, Pairing.negate(proof.A_p), Pairing.P2())) return 1;
if (!Pairing.pairingProd2(vk.B, proof.B, Pairing.negate(proof.B_p), Pairing.P2())) return 2;
if (!Pairing.pairingProd2(proof.C, vk.C, Pairing.negate(proof.C_p), Pairing.P2())) return 3;
if (!Pairing.pairingProd3(
proof.K, vk.gamma,
Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.A, proof.C))), vk.gammaBeta2,
Pairing.negate(vk.gammaBeta1), proof.B
)) return 4;
if (!Pairing.pairingProd3(
Pairing.addition(vk_x, proof.A), proof.B,
Pairing.negate(proof.H), vk.Z,
Pairing.negate(proof.C), Pairing.P2()
)) return 5;
return 0;
}
function verifyProof(
uint[2] memory a,
uint[2] memory a_p,
uint[2][2] memory b,
uint[2] memory b_p,
uint[2] memory c,
uint[2] memory c_p,
uint[2] memory h,
uint[2] memory k,
uint[<%vk_input_length%>] memory input
) view public returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.A_p = Pairing.G1Point(a_p[0], a_p[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.B_p = Pairing.G1Point(b_p[0], b_p[1]);
proof.C = Pairing.G1Point(c[0], c[1]);
proof.C_p = Pairing.G1Point(c_p[0], c_p[1]);
proof.H = Pairing.G1Point(h[0], h[1]);
proof.K = Pairing.G1Point(k[0], k[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
return true;
} else {
return false;
}
}
function verifyProof(bytes calldata proof, uint[<%vk_input_length%>] calldata inputs) external view returns (bool r) {
// solidity does not support decoding uint[2][2] yet
(
uint[2] memory a,
uint[2] memory a_p,
uint[2] memory b1,
uint[2] memory b2,
uint[2] memory b_p,
uint[2] memory c,
uint[2] memory c_p,
uint[2] memory h,
uint[2] memory k
) = abi.decode(proof, (uint[2], uint[2], uint[2], uint[2], uint[2], uint[2], uint[2], uint[2], uint[2]));
return verifyProof(a, a_p, [b1, b2], b_p, c, c_p, h, k, inputs);
}
}

254
test/algebra.js Normal file
View File

@ -0,0 +1,254 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const bigInt = require("../src/bigint.js");
const BN128 = require("../src/bn128.js");
const F1Field = require("../src/zqfield.js");
const assert = chai.assert;
describe("F1 testing", () => {
it("Should compute euclidean", () => {
const F = new F1Field(bigInt(7));
const res = F.inverse(bigInt(4));
assert(F.equals(res, bigInt(2)));
});
it("Should multiply and divide in F1", () => {
const bn128 = new BN128();
const a = bigInt("1");
const b = bn128.F1.affine(bigInt("-3"));
const c = bn128.F1.mul(a,b);
const d = bn128.F1.div(c,b);
assert(bn128.F1.equals(a, d));
});
it("Should compute sqrts", () => {
const bn128 = new BN128();
const F = new F1Field(bn128.r);
const a = bigInt("4");
let b = F.sqrt(a);
assert(F.equals(bigInt(0), F.sqrt(bigInt("0"))));
assert(F.equals(b, bigInt("2")));
assert(F.sqrt(F.nqr) === null);
});
it("Should compute sqrt of 100 random numbers", () => {
const bn128 = new BN128();
const F = new F1Field(bn128.r);
for (let j=0;j<100; j++) {
let a = F.random();
let s = F.sqrt(a);
if (s != null) {
assert(F.equals(F.square(s), a));
}
}
});
});
describe("Curve G1 Test", () => {
it("r*one == 0", () => {
const bn128 = new BN128();
const res = bn128.G1.mulScalar(bn128.G1.g, bn128.r);
assert(bn128.G1.equals(res, bn128.G1.zero), "G1 does not have range r");
});
it("Should add match in various in G1", () => {
const bn128 = new BN128();
const r1 = bigInt(33);
const r2 = bigInt(44);
const gr1 = bn128.G1.mulScalar(bn128.G1.g, r1);
const gr2 = bn128.G1.mulScalar(bn128.G1.g, r2);
const grsum1 = bn128.G1.add(gr1, gr2);
const grsum2 = bn128.G1.mulScalar(bn128.G1.g, r1.add(r2));
assert(bn128.G1.equals(grsum1, grsum2));
});
});
describe("Curve G2 Test", () => {
it ("r*one == 0", () => {
const bn128 = new BN128();
const res = bn128.G2.mulScalar(bn128.G2.g, bn128.r);
assert(bn128.G2.equals(res, bn128.G2.zero), "G2 does not have range r");
});
it("Should add match in various in G2", () => {
const bn128 = new BN128();
const r1 = bigInt(33);
const r2 = bigInt(44);
const gr1 = bn128.G2.mulScalar(bn128.G2.g, r1);
const gr2 = bn128.G2.mulScalar(bn128.G2.g, r2);
const grsum1 = bn128.G2.add(gr1, gr2);
const grsum2 = bn128.G2.mulScalar(bn128.G2.g, r1.add(r2));
/*
console.log(G2.toString(grsum1));
console.log(G2.toString(grsum2));
*/
assert(bn128.G2.equals(grsum1, grsum2));
});
});
describe("F6 testing", () => {
it("Should multiply and divide in F6", () => {
const bn128 = new BN128();
const a =
[
[bigInt("1"), bigInt("2")],
[bigInt("3"), bigInt("4")],
[bigInt("5"), bigInt("6")]
];
const b =
[
[bigInt("12"), bigInt("11")],
[bigInt("10"), bigInt("9")],
[bigInt("8"), bigInt("7")]
];
const c = bn128.F6.mul(a,b);
const d = bn128.F6.div(c,b);
assert(bn128.F6.equals(a, d));
});
});
describe("F12 testing", () => {
it("Should multiply and divide in F12", () => {
const bn128 = new BN128();
const a =
[
[
[bigInt("1"), bigInt("2")],
[bigInt("3"), bigInt("4")],
[bigInt("5"), bigInt("6")]
],
[
[bigInt("7"), bigInt("8")],
[bigInt("9"), bigInt("10")],
[bigInt("11"), bigInt("12")]
]
];
const b =
[
[
[bigInt("12"), bigInt("11")],
[bigInt("10"), bigInt("9")],
[bigInt("8"), bigInt("7")]
],
[
[bigInt("6"), bigInt("5")],
[bigInt("4"), bigInt("3")],
[bigInt("2"), bigInt("1")]
]
];
const c = bn128.F12.mul(a,b);
const d = bn128.F12.div(c,b);
assert(bn128.F12.equals(a, d));
});
});
describe("Pairing", () => {
/*
it("Should match pairing", () => {
for (let i=0; i<1; i++) {
const bn128 = new BN128();
const g1a = bn128.G1.mulScalar(bn128.G1.g, 25);
const g2a = bn128.G2.mulScalar(bn128.G2.g, 30);
const g1b = bn128.G1.mulScalar(bn128.G1.g, 30);
const g2b = bn128.G2.mulScalar(bn128.G2.g, 25);
const pre1a = bn128.precomputeG1(g1a);
const pre2a = bn128.precomputeG2(g2a);
const pre1b = bn128.precomputeG1(g1b);
const pre2b = bn128.precomputeG2(g2b);
const r1 = bn128.millerLoop(pre1a, pre2a);
const r2 = bn128.millerLoop(pre1b, pre2b);
const rbe = bn128.F12.mul(r1, bn128.F12.inverse(r2));
const res = bn128.finalExponentiation(rbe);
assert(bn128.F12.equals(res, bn128.F12.one));
}
}).timeout(10000);
*/
it("Should generate another pairing pairing", () => {
for (let i=0; i<1; i++) {
const bn128 = new BN128();
const g1a = bn128.G1.mulScalar(bn128.G1.g, 10);
const g2a = bn128.G2.mulScalar(bn128.G2.g, 1);
const g1b = bn128.G1.mulScalar(bn128.G1.g, 1);
const g2b = bn128.G2.mulScalar(bn128.G2.g, 10);
const pre1a = bn128.precomputeG1(g1a);
const pre2a = bn128.precomputeG2(g2a);
const pre1b = bn128.precomputeG1(g1b);
const pre2b = bn128.precomputeG2(g2b);
const r1 = bn128.millerLoop(pre1a, pre2a);
const r2 = bn128.finalExponentiation(r1);
const r3 = bn128.millerLoop(pre1b, pre2b);
const r4 = bn128.finalExponentiation(r3);
console.log("ML1: " ,r1[0][0][0].affine(bn128.q).toString(16));
console.log("FE1: " ,r2[0][0][0].affine(bn128.q).toString(16));
console.log("ML2: " ,r3[0][0][0].affine(bn128.q).toString(16));
console.log("FE2: " ,r4[0][0][0].affine(bn128.q).toString(16));
assert(bn128.F12.equals(r2, r4));
/* const r2 = bn128.millerLoop(pre1b, pre2b);
const rbe = bn128.F12.mul(r1, bn128.F12.inverse(r2));
const res = bn128.finalExponentiation(rbe);
assert(bn128.F12.equals(res, bn128.F12.one)); */
}
}).timeout(10000);
});

40
test/calculatewitness.js Normal file
View File

@ -0,0 +1,40 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const fs = require("fs");
const path = require("path");
const Circuit = require("../src/circuit.js");
const BN128 = require("../src/bn128.js");
const F1Field = require("../src/zqfield.js");
const assert = chai.assert;
describe("Calculate witness", () => {
it("Should calculate the witness of a sum circuit", () => {
const cirDef = JSON.parse(fs.readFileSync(path.join(__dirname, "circuit", "sum.json"), "utf8"));
const cir = new Circuit(cirDef);
const witness = cir.calculateWitness({"a": "33", "b": "34"});
assert.equal(witness[cir.getSignalIdx("main.out")].toString(), "67");
});
});

2371
test/circuit/sum.json Normal file

File diff suppressed because it is too large Load Diff

217
test/pols.js Normal file
View File

@ -0,0 +1,217 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const bigInt = require("../src/bigint.js");
const PolField = require("../src/polfield.js");
const ZqField = require("../src/zqfield");
const assert = chai.assert;
const r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
describe("Polynomial field", () => {
it("Should compute a multiplication", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(1), bigInt(2), bigInt(3)];
const b = [bigInt(1), bigInt(2), bigInt(3)];
const res = PF.mul(a,b);
assert(PF.equals(res, [bigInt(1), bigInt(4), bigInt(10), bigInt(12), bigInt(9)]));
});
it("Should compute a multiplication 2", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(5), bigInt(1)];
const b = [bigInt(-5), bigInt(1)];
const res = PF.mul(a,b);
assert(PF.equals(res, [bigInt(-25), bigInt(0), bigInt(1)]));
});
it("Should compute an addition", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(5), bigInt(1)];
const b = [bigInt(-5), bigInt(1)];
const res = PF.add(a,b);
assert(PF.equals(res, [bigInt(0), bigInt(2)]));
});
it("Should compute a substraction", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(5), bigInt(3), bigInt(4)];
const b = [bigInt(5), bigInt(1)];
const res = PF.sub(a,b);
assert(PF.equals(res, [bigInt(0), bigInt(2), bigInt(4)]));
});
it("Should compute reciprocal", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(4), bigInt(1), bigInt(-3), bigInt(-1), bigInt(2),bigInt(1), bigInt(-1), bigInt(1)];
const res = PF._reciprocal(a, 3, 0);
assert(PF.equals(res, [bigInt(12), bigInt(15), bigInt(3), bigInt(-4), bigInt(-3), bigInt(0), bigInt(1), bigInt(1)]));
});
it("Should div2", () => {
const PF = new PolField(new ZqField(r));
// x^6
const a = [bigInt(0), bigInt(0), bigInt(0), bigInt(0), bigInt(0),bigInt(0), bigInt(1)];
// x^5
const b = [bigInt(0), bigInt(0), bigInt(0), bigInt(0), bigInt(0), bigInt(1)];
const res = PF._div2(6, b);
assert(PF.equals(res, [bigInt(0), bigInt(1)]));
const res2 = PF.div(a,b);
assert(PF.equals(res2, [bigInt(0), bigInt(1)]));
});
it("Should div", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(1), bigInt(2), bigInt(3), bigInt(4), bigInt(5),bigInt(6), bigInt(7)];
const b = [bigInt(8), bigInt(9), bigInt(10), bigInt(11), bigInt(12), bigInt(13)];
const c = PF.mul(a,b);
const d = PF.div(c,b);
assert(PF.equals(a, d));
});
it("Should div big/small", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(1), bigInt(2), bigInt(3), bigInt(4), bigInt(5),bigInt(6), bigInt(7)];
const b = [bigInt(8), bigInt(9)];
const c = PF.mul(a,b);
const d = PF.div(c,b);
assert(PF.equals(a, d));
});
it("Should div random big", () => {
const PF = new PolField(new ZqField(r));
const a = [];
const b = [];
for (let i=0; i<1000; i++) a.push(bigInt(Math.floor(Math.random()*100000) -500000));
for (let i=0; i<900; i++) b.push(bigInt(Math.floor(Math.random()*100000) -500000));
const c = PF.mul(a,b);
const d = PF.div(c,b);
assert(PF.equals(a, d));
}).timeout(10000);
it("Should evaluate and zero", () => {
const PF = new PolField(new ZqField(r));
const p = [PF.F.neg(bigInt(2)), bigInt(1)];
const v = PF.eval(p, bigInt(2));
assert(PF.F.equals(v, bigInt(0)));
});
it("Should evaluate bigger number", () => {
const PF = new PolField(new ZqField(r));
const p = [bigInt(1), bigInt(2), bigInt(3)];
const v = PF.eval(p, bigInt(2));
assert(PF.F.equals(v, bigInt(17)));
});
it("Should create lagrange polynomial minmal", () => {
const PF = new PolField(new ZqField(r));
const points=[];
points.push([bigInt(1), bigInt(1)]);
points.push([bigInt(2), bigInt(2)]);
points.push([bigInt(3), bigInt(5)]);
const p=PF.lagrange(points);
for (let i=0; i<points.length; i++) {
const v = PF.eval(p, points[i][0]);
assert(PF.F.equals(v, points[i][1]));
}
});
it("Should create lagrange polynomial", () => {
const PF = new PolField(new ZqField(r));
const points=[];
points.push([bigInt(1), bigInt(2)]);
points.push([bigInt(2), bigInt(-2)]);
points.push([bigInt(3), bigInt(0)]);
points.push([bigInt(4), bigInt(453345)]);
const p=PF.lagrange(points);
for (let i=0; i<points.length; i++) {
const v = PF.eval(p, points[i][0]);
assert(PF.F.equals(v, points[i][1]));
}
});
it("Should test ruffini", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(1), bigInt(2), bigInt(3), bigInt(4), bigInt(5),bigInt(6), bigInt(7)];
const b = PF.mul(a, [bigInt(-7), bigInt(1)]);
const c = PF.ruffini(b, bigInt(7));
assert(PF.equals(a, c));
});
it("Should test roots", () => {
const PF = new PolField(new ZqField(r));
let rt;
rt = PF.oneRoot(256, 16);
for (let i=0; i<8; i++) {
rt = PF.F.mul(rt, rt);
}
assert(rt.equals(PF.F.one));
rt = PF.oneRoot(256, 15);
for (let i=0; i<8; i++) {
rt = PF.F.mul(rt, rt);
}
assert(rt.equals(PF.F.one));
rt = PF.oneRoot(8, 3);
for (let i=0; i<3; i++) {
rt = PF.F.mul(rt, rt);
}
assert(rt.equals(PF.F.one));
rt = PF.oneRoot(8, 0);
assert(rt.equals(PF.F.one));
});
it("Should create a polynomial with values at roots with fft", () => {
const PF = new PolField(new ZqField(r));
const a = [bigInt(1), bigInt(2), bigInt(3), bigInt(4), bigInt(5),bigInt(6), bigInt(7)];
const p = PF.ifft(a);
for (let i=0; i<a.length; i++) {
const s = PF.F.affine(PF.eval(p, PF.oneRoot(8,i)));
assert(s.equals(a[i]));
}
});
});

89
test/ratzqfield.js Normal file
View File

@ -0,0 +1,89 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const bigInt = require("../src/bigint.js");
const ZqField = require("../src/zqfield.js");
const RatField = require("../src/ratfield.js");
const q = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const Z = new ZqField(q);
const R = new RatField(Z);
const assert = chai.assert;
function r(a,b) {
return [bigInt(a), bigInt(b)];
}
describe("Rational zq Field", () => {
it("Should compare correctly", () => {
assert( R.equals(r(3,5), r(6,10)));
assert(!R.equals(r(3,5), r(6,11)));
});
it("Should add correctly", () => {
const a = r(7,4);
const b = r(5,12);
assert(R.equals( R.add(a,b), r(13, 6)));
});
it("Should substract", () => {
const a = r(7,4);
const b = r(5,12);
assert(R.equals( R.sub(a,b), r(4, 3)));
});
it("Should multiply", () => {
const a = r(7,4);
const b = r(5,12);
assert(R.equals( R.mul(a,b), r(35, 48)));
});
it("Should div", () => {
const a = r(7,4);
const b = r(5,12);
assert(R.equals( R.div(a,b), r(7*12, 5*4)));
});
it("Should square", () => {
const a = r(7,4);
assert(R.equals( R.square(a), r(49, 16)));
});
it("Should affine", () => {
const a = r(12,4);
const aa = R.affine(a);
assert(Z.equals( aa[0], bigInt(3)));
assert(Z.equals( aa[1], Z.one));
});
it("Should convert from Z to R", () => {
const vz = bigInt(34);
const vr = R.fromF(vz);
assert(R.equals( vr, r(34,1)));
});
it("Should convert from R to Z", () => {
const vr = r(32, 2);
const vz = R.toF(vr);
assert(Z.equals( vz, bigInt(16)));
});
});

196
test/zksnark.js Normal file
View File

@ -0,0 +1,196 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const fs = require("fs");
const path = require("path");
const bigInt = require("../src/bigint.js");
const Circuit = require("../src/circuit.js");
const zkSnark = require("../index.js").original;
const BN128 = require("../src/bn128.js");
const PolField = require("../src/polfield.js");
const ZqField = require("../src/zqfield.js");
const {stringifyBigInts, unstringifyBigInts} = require("../src/stringifybigint.js");
const bn128 = new BN128();
const PolF = new PolField(new ZqField(bn128.r));
const G1 = bn128.G1;
const G2 = bn128.G2;
const assert = chai.assert;
describe("zkSnark original", () => {
it("Load a circuit, create trusted setup, create a proof and validate it", () => {
const cirDef = JSON.parse(fs.readFileSync(path.join(__dirname, "circuit", "sum.json"), "utf8"));
const cir = new Circuit(cirDef);
const setup = zkSnark.setup(cir);
const strSetup = stringifyBigInts(setup);
fs.writeFileSync("vk_proof.json", JSON.stringify(strSetup.vk_proof), "utf-8");
fs.writeFileSync("vk_verifier.json", JSON.stringify(strSetup.vk_verifier), "utf-8");
function polT2S(p) {
const p_T = new Array(setup.vk_proof.domainSize).fill(bigInt(0));
for (let c in p) {
p_T[c] = p[c];
}
return PolF.ifft(p_T);
}
/*
const setup = {};
setup.vk_proof = unstringifyBigInts(JSON.parse(fs.readFileSync("vk_proof.json", "utf8")));
setup.vk_verifier = unstringifyBigInts(JSON.parse(fs.readFileSync("vk_verifier.json", "utf8")));
*/
const witness = cir.calculateWitness({"a": "33", "b": "34"});
const {proof, publicSignals} = zkSnark.genProof(setup.vk_proof, witness);
/*
const polA = new Array(cir.nVars);
const polB = new Array(cir.nVars);
const polC = new Array(cir.nVars);
for (let i=0; i<cir.nVars; i++) {
polA[i] = polT2S(setup.vk_proof.polsA[i]);
polB[i] = polT2S(setup.vk_proof.polsB[i]);
polC[i] = polT2S(setup.vk_proof.polsC[i]);
}
PolF._setRoots(setup.vk_proof.domainBits);
for (let c=0; c<setup.vk_proof.domainSize; c++) {
let A = bigInt(0);
let B = bigInt(0);
let C = bigInt(0);
for (let s=0; s<cir.nVars; s++) {
A = PolF.F.add(A, PolF.F.mul(PolF.eval(polA[s], PolF.roots[setup.vk_proof.domainBits][c]), witness[s]));
B = PolF.F.add(B, PolF.F.mul(PolF.eval(polB[s], PolF.roots[setup.vk_proof.domainBits][c]), witness[s]));
C = PolF.F.add(C, PolF.F.mul(PolF.eval(polC[s], PolF.roots[setup.vk_proof.domainBits][c]), witness[s]));
}
assert(PolF.F.equals(PolF.F.mul(A,B), C));
}
let A = bigInt(0);
let B = bigInt(0);
let C = bigInt(0);
for (let s=0; s<cir.nVars; s++) {
A = PolF.F.add(A, PolF.F.mul(PolF.eval(polA[s], setup.toxic.t), witness[s]));
B = PolF.F.add(B, PolF.F.mul(PolF.eval(polB[s], setup.toxic.t), witness[s]));
C = PolF.F.add(C, PolF.F.mul(PolF.eval(polC[s], setup.toxic.t), witness[s]));
}
let A2 = bigInt(0);
let B2 = bigInt(0);
let C2 = bigInt(0);
const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
for (let s=0; s<cir.nVars; s++) {
let at = PolF.F.zero;
for (let c in setup.vk_proof.polsA[s]) {
at = PolF.F.add(at, PolF.F.mul(u[c], setup.vk_proof.polsA[s][c]));
}
A2 = PolF.F.add(A2, PolF.F.mul(at, witness[s]));
let bt = PolF.F.zero;
for (let c in setup.vk_proof.polsB[s]) {
bt = PolF.F.add(bt, PolF.F.mul(u[c], setup.vk_proof.polsB[s][c]));
}
B2 = PolF.F.add(B2, PolF.F.mul(bt, witness[s]));
let ct = PolF.F.zero;
for (let c in setup.vk_proof.polsC[s]) {
ct = PolF.F.add(ct, PolF.F.mul(u[c], setup.vk_proof.polsC[s][c]));
}
C2 = PolF.F.add(C2, PolF.F.mul(ct, witness[s]));
}
A=PolF.F.affine(A);
B=PolF.F.affine(B);
C=PolF.F.affine(C);
A2=PolF.F.affine(A2);
B2=PolF.F.affine(B2);
C2=PolF.F.affine(C2);
assert(PolF.F.equals(C,C2));
assert(PolF.F.equals(B,B2));
assert(PolF.F.equals(A,A2));
const ABC = PolF.F.affine(PolF.F.sub(PolF.F.mul(A,B), C));
assert.equal(witness[cir.getSignalIdx("main.out")].toString(), "67");
const H = PolF.eval(proof.h, setup.toxic.t).affine();
const Z = PolF.F.sub(PolF.F.exp(setup.toxic.t, setup.vk_proof.domainSize), bigInt(1));
const HZ = PolF.F.affine(PolF.F.mul(H,Z));
assert(PolF.F.equals(ABC, HZ));
const gH = G1.affine(G1.mulScalar( G1.g, H));
const gZ = G2.affine(G2.mulScalar( G2.g, Z));
const gA = G1.affine(G1.mulScalar( G1.g, A));
const gB = G2.affine(G2.mulScalar( G2.g, B));
const gC = G1.affine(G1.mulScalar( G1.g, C));
assert(G1.equals(gH, proof.pi_h));
assert(G2.equals(gZ, setup.vk_verifier.vk_z));
assert(G2.equals(gB, proof.pi_b));
assert(G1.equals(gC, proof.pi_c));
// assert(G1.equals(gA, proof.pi_a));
*/
assert( zkSnark.isValid(setup.vk_verifier, proof, publicSignals));
}).timeout(10000000);
/*
it("validate sha256_2", () => {
const cirDef = JSON.parse(fs.readFileSync(path.join(__dirname, "circuit", "sha256_2.json"), "utf8"));
const cir = new Circuit(cirDef);
console.log("Start setup: "+Date().toString());
const setup = zkSnark.setup(cir);
const strSetup = stringifyBigInts(setup);
fs.writeFileSync("sha256_2_vk_proof.json", JSON.stringify(strSetup.vk_proof), "utf-8");
fs.writeFileSync("sha256_2_vk_verifier.json", JSON.stringify(strSetup.vk_verifier), "utf-8");
// const setup = {};
// setup.vk_proof = unstringifyBigInts(JSON.parse(fs.readFileSync("vk_proof.json", "utf8")));
// setup.vk_verifier = unstringifyBigInts(JSON.parse(fs.readFileSync("vk_verifier.json", "utf8")));
const witness = cir.calculateWitness({"a": "1", "b": "2"});
// assert.equal(witness[cir.getSignalIdx("main.out")].toString(), "67");
console.log("Start calculating the proof: "+Date().toString());
const {proof, publicSignals} = zkSnark.genProof(setup.vk_proof, witness);
console.log("Start verifiying: "+ Date().toString());
assert( zkSnark.isValid(setup.vk_verifier, proof, publicSignals));
}).timeout(10000000);
*/
});

44
test/zksnark_groth.js Normal file
View File

@ -0,0 +1,44 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const fs = require("fs");
const path = require("path");
const Circuit = require("../src/circuit.js");
const zkSnark = require("../index.js").groth;
const assert = chai.assert;
describe("zkSnark Groth", () => {
it("Load a circuit, create trusted setup, create a proof and validate it", () => {
const cirDef = JSON.parse(fs.readFileSync(path.join(__dirname, "circuit", "sum.json"), "utf8"));
const cir = new Circuit(cirDef);
const setup = zkSnark.setup(cir);
const witness = cir.calculateWitness({"a": "33", "b": "34"});
const {proof, publicSignals} = zkSnark.genProof(setup.vk_proof, witness);
assert( zkSnark.isValid(setup.vk_verifier, proof, publicSignals));
}).timeout(10000000);
});

44
test/zksnark_kimleeoh.js Normal file
View File

@ -0,0 +1,44 @@
/*
Copyright 2018 0kims association.
This file is part of zksnark JavaScript library.
zksnark JavaScript library is a free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
zksnark JavaScript library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
*/
const chai = require("chai");
const fs = require("fs");
const path = require("path");
const Circuit = require("../src/circuit.js");
const zkSnark = require("../index.js").kimleeoh;
const assert = chai.assert;
describe("zkSnark KimLeeOh", () => {
it("Load a circuit, create trusted setup, create a proof and validate it", () => {
const cirDef = JSON.parse(fs.readFileSync(path.join(__dirname, "circuit", "sum.json"), "utf8"));
const cir = new Circuit(cirDef);
const setup = zkSnark.setup(cir);
const witness = cir.calculateWitness({"a": "33", "b": "34"});
const {proof, publicSignals} = zkSnark.genProof(setup.vk_proof, witness);
assert( zkSnark.isValid(setup.vk_verifier, proof, publicSignals));
}).timeout(10000000);
});