Compare commits

...

41 Commits

Author SHA1 Message Date
arnaucube
93bf45c299 fix bbjj api: return err when hash fails while sign/verify 2023-08-23 14:47:33 +02:00
Ilya
3fb23d780c Merge pull request #55 from iden3/feature/PID-676-support-golang-interfaces
PID-676: support hash interface for poseidon; support golang crypto interfaces…
2023-05-30 13:43:25 +03:00
Ilya
068065257f fix comments 2023-05-23 22:20:45 +03:00
Ilya
f4e4eed9d5 move DecompressSig to bjj helpers 2023-05-23 17:19:05 +03:00
Ilya
85b692c937 add test for poseidon hash writer; rename methods 2023-05-23 17:10:48 +03:00
Ilya
6ff38d47db add frame size to poseidon hasher 2023-05-18 13:37:31 +03:00
Ilya
b015806983 support hash interface for poseidon; support golang crypto interfaces for bjj 2023-05-09 13:21:59 +03:00
Oleksandr Brezhniev
bd5255dea7 Switch to Apache 2.0 / MIT licenses (#54)
* Switch to Apache 2.0 / MIT licenses
2023-04-25 16:24:26 +03:00
Oleksandr Brezhniev
e5cf066b8b Poseidon Sponge Hash with different frame sizes (#52)
* Poseidon Sponge Hash with different frame sizes
* Update deps. Bump go version
* Update & fix linter.
* Refactor a bit.
* Reduce gc pressure
2023-03-08 20:18:55 +02:00
cool-developer
edc36bfa52 Merge pull request #49 from iden3/feature/neptune
Neptune Hash Implementation
2022-04-13 08:33:45 -04:00
Cool Developer
3c0a3adbbe remove the original hash function 2022-04-13 13:13:55 +01:00
Cool Developer
5ee5396d03 remove the bench 2022-04-11 15:35:18 +01:00
Cool Developer
49541f2ead fix the lint issues 2022-04-11 15:07:41 +01:00
Cool Developer
46665875c7 add the neptuen hash 2022-04-08 15:00:21 +01:00
cool-developer
d3e4218fe3 Merge pull request #46 from iden3/feature/golden
Golden poseidon hash implementation
2022-03-22 05:06:23 -04:00
cool-developer
5848bf2918 Update element.go 2022-03-18 14:06:18 -04:00
cool-developer
38240a6451 Remove unnecessary lines 2022-03-18 14:00:53 -04:00
cool-developer
0d6b33924a Update element_ops_amd64.s 2022-03-16 11:06:16 -04:00
cool-developer
52375f5e15 Update element_ops_amd64.s 2022-03-16 11:05:50 -04:00
Cool Developer
47b41d8ffc update the input params of hash 2022-03-15 07:33:14 -04:00
Cool Developer
1a046cf574 fix lint issues 2022-03-15 07:29:45 -04:00
Cool Developer
f0c462811a update the input params of hash 2022-03-15 07:27:18 -04:00
Cool Developer
26bfd1051a add the unit-test 2022-03-14 07:01:56 -04:00
Cool Developer
885e7c382e init commit for the golden poseidon 2022-03-11 07:26:42 -05:00
Oleksandr Brezhniev
f4972de131 Poseidon Sponge Hash implemented (#45)
* Poseidon Sponge Hash implemented
* Linter fixes and GHA go versions updated
2022-02-09 14:11:35 +02:00
Oleksandr Brezhniev
d53d6303be Added benchmark of Poseidon for 8 inputs 2022-02-01 19:17:04 +02:00
a_bennassar
b85be5b7f7 Add poseidon benchmark with 16 elements (#44)
Add poseidon benchmark with 16 elements
2022-02-01 17:22:47 +01:00
Oleksandr Brezhniev
69354ae29c Faster ff arithmetics (regenerated code with the newest goff) (#43) 2021-12-28 20:47:12 +02:00
Oleksandr Brezhniev
f597e20569 Fix Poseidon Hash check for inputs being in Finite Field (#42) 2021-11-21 02:58:03 +02:00
Oleksandr Brezhniev
64e757cc4a Better keccac256 (#41)
* Switch to keccac256 implementation from golang.org/x/crypto instead of go-ethereum
2021-11-19 17:00:10 +02:00
Mikhail Wall
9c2ca9ca7c made optimizaitions for consts init (#40) 2021-10-07 11:10:00 +03:00
Oleksandr Brezhniev
c544ba0f3c Extend Poseidon to 16 inputs (#39) 2021-10-06 16:09:20 +03:00
Oleksandr Brezhniev
ef9f86210a Extend Poseidon to 16 inputs (#37)
* Extend poseidon to 16 inputs. Better initialization of Poseidon constants
* Update deps
* Fix linter warnings
* Test vectors for poseidon with 14 inputs
2021-10-06 13:11:09 +03:00
Mikhail Wall
933c28a8d7 implemented optimized poseidon (#38)
* implemented optimized poseidon

* added comment to poseidon hash function

* deleted poseidonslow
2021-10-06 12:25:10 +03:00
Eduard S
8f85683b2c Merge pull request #36 from iden3/feature/poseidon-update-reference-impl
Update Poseidon last changes of the reference impl
2021-03-08 15:23:48 +01:00
arnaucube
590573a0af Update Poseidon last changes of the reference impl
Update Poseidon to last changes of the reference implementation from
26ddaa91db

Compatible with update at circomlib
(cf853c1cc9)
2021-03-08 14:59:42 +01:00
Eduard S
58e589b6eb Merge pull request #35 from iden3/feature/comp-point-test
Update and add test for PackSignY & UnpackSignY
2020-12-21 17:03:44 +01:00
arnaucube
2318fd7044 Update and add test for PackSignY & UnpackSignY
- Update PackSignY & UnpackSignY interface and description
- Add test for UnpackSignY & PackPoint
2020-12-21 16:58:13 +01:00
Eduard S
a0722b9e8f Merge pull request #34 from iden3/feature/exp-comppoint-signy
Abstract & expose CompressedPointToSignAndY
2020-12-21 16:21:27 +01:00
arnaucube
71dbddb5f1 Abstract & expose CompressedPointToSignAndY 2020-12-21 16:12:49 +01:00
Eduard S
0a5c6acba3 Merge pull request #33 from iden3/feature/pkcomp-scanvalue
Add scanner/valuer interface to babyjub.PublicKeyComp
2020-12-21 10:31:37 +01:00
52 changed files with 34779 additions and 5299 deletions

View File

@@ -1,16 +1,18 @@
name: Lint
on: [ push, pull_request ]
on:
push:
branches:
- main
pull_request:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Install Go
uses: actions/setup-go@v1
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version: 1.14.x
- name: Checkout code
uses: actions/checkout@v2
- name: Lint
run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.30.0
$(go env GOPATH)/bin/golangci-lint run --timeout=5m -c .golangci.yml
go-version: 1.20.x
- uses: golangci/golangci-lint-action@v3
with:
version: v1.51.1

View File

@@ -4,7 +4,7 @@ jobs:
test:
strategy:
matrix:
go-version: [ 1.13.x, 1.14.x ]
go-version: [ 1.18.x, 1.19.x, 1.20.x ]
goarch: [ "amd64", "386" ]
runs-on: ubuntu-latest
steps:

View File

@@ -1,17 +1,77 @@
issues:
max-same-issues: 0
exclude-use-default: false
linters:
enable:
- whitespace
- gosec
- gci
- misspell
- gomnd
- gofmt
- goimports
- lll
- golint
service:
golangci-lint-version: 1.51.x
run:
timeout: 2m
skip-dirs:
- vendor
linters-settings:
lll:
line-length: 100
govet:
check-shadowing: true
revive:
min-confidence: 0.1
rules:
- name: package-comments
disabled: true
maligned:
suggest-new: true
goconst:
min-len: 2
min-occurrences: 2
misspell:
locale: US
lll:
line-length: 140
gocritic:
enabled-tags:
- performance
- style
- experimental
disabled-checks:
- hugeParam
linters:
enable:
- bodyclose
- megacheck
- revive
- govet
- unconvert
- megacheck
- gas
- gocyclo
- dupl
- misspell
- unparam
- typecheck
- ineffassign
- stylecheck
- exportloopref
- nakedret
- gosimple
- prealloc
- unused
## format - fill free to fix
# - errcheck
# - gofmt
# - goimports
fast: false
disable-all: true
issues:
exclude-rules:
# - Fix and remove
- text: "at least one file in a package should have a package comment"
linters:
- stylecheck
# - Fix and remove
- text: "should have a package comment, unless it's in another file for this package"
linters:
- revive
- path: _test\.go
linters:
- gosec
- dupl
exclude-use-default: false

674
LICENSE
View File

@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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:
<program> Copyright (C) <year> <name of author>
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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

201
LICENSE-APACHE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2023 0kims Association
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21
LICENSE-MIT Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright 2023 0kims Association.
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.

View File

@@ -1,4 +1,25 @@
# go-iden3-crypto [![Go Report Card](https://goreportcard.com/badge/github.com/iden3/go-iden3-crypto)](https://goreportcard.com/report/github.com/iden3/go-iden3-crypto) [![Test Status](https://github.com/iden3/go-iden3-crypto/workflows/Test/badge.svg)](https://github.com/iden3/go-iden3-crypto/actions?query=workflow%3ATest) [![Lint Status](https://github.com/iden3/go-iden3-crypto/workflows/Lint/badge.svg)](https://github.com/iden3/go-iden3-crypto/actions?query=workflow%3ALint) [![GoDoc](https://godoc.org/github.com/iden3/go-iden3-crypto?status.svg)](https://godoc.org/github.com/iden3/go-iden3-crypto)
Go implementation of some cryptographic primitives (that fit inside the SNARK field) used in iden3
Go implementation of some cryptographic primitives (that fit inside the SNARK field) used in iden3:
* BabyJubJub curve arithmetics & EdDSA on it
* Goldilocks curve arithmetics
* Poseidon hash for BN254
* Poseidon hash for Goldilocks
* MIMC7
## Contributing
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as below, without any additional terms or conditions.
## License
&copy; 2023 0kims Association
This project is licensed under either of
- [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) ([`LICENSE-APACHE`](LICENSE-APACHE))
- [MIT license](https://opensource.org/licenses/MIT) ([`LICENSE-MIT`](LICENSE-MIT))
at your option.

View File

@@ -41,7 +41,7 @@ func init() {
Order = utils.NewIntFromString(
"21888242871839275222246405745257275088614511777268538073601725287587578984328")
SubOrder = new(big.Int).Rsh(Order, 3)
SubOrder = new(big.Int).Rsh(Order, 3) //nolint:gomnd
B8 = NewPoint()
B8.X = utils.NewIntFromString(
@@ -87,7 +87,7 @@ func (p *PointProjective) Affine() *Point {
// Add computes the addition of two points in projective coordinates
// representation
func (p *PointProjective) Add(q *PointProjective, o *PointProjective) *PointProjective {
func (p *PointProjective) Add(q, o *PointProjective) *PointProjective {
// add-2008-bbjlp
// https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp
a := ff.NewElement().Mul(q.Z, o.Z)
@@ -95,20 +95,20 @@ func (p *PointProjective) Add(q *PointProjective, o *PointProjective) *PointProj
c := ff.NewElement().Mul(q.X, o.X)
d := ff.NewElement().Mul(q.Y, o.Y)
e := ff.NewElement().Mul(Dff, c)
e.MulAssign(d)
e.Mul(e, d)
f := ff.NewElement().Sub(b, e)
g := ff.NewElement().Add(b, e)
x1y1 := ff.NewElement().Add(q.X, q.Y)
x2y2 := ff.NewElement().Add(o.X, o.Y)
x3 := ff.NewElement().Mul(x1y1, x2y2)
x3.SubAssign(c)
x3.SubAssign(d)
x3.MulAssign(a)
x3.MulAssign(f)
x3.Sub(x3, c)
x3.Sub(x3, d)
x3.Mul(x3, a)
x3.Mul(x3, f)
ac := ff.NewElement().Mul(Aff, c)
y3 := ff.NewElement().Sub(d, ac)
y3.MulAssign(a)
y3.MulAssign(g)
y3.Mul(y3, a)
y3.Mul(y3, g)
z3 := ff.NewElement().Mul(f, g)
p.X = x3
@@ -203,31 +203,46 @@ func PointCoordSign(c *big.Int) bool {
return c.Cmp(new(big.Int).Rsh(constants.Q, 1)) == 1
}
// PackPoint packs a point into a 32 byte array
func PackPoint(ay *big.Int, sign bool) [32]byte {
leBuf := utils.BigIntLEBytes(ay)
// PackSignY packs the given sign and the coordinate Y of a point into a 32
// byte array. This method does not check that the values belong to a valid
// Point in the curve.
func PackSignY(sign bool, y *big.Int) [32]byte {
leBuf := utils.BigIntLEBytes(y)
if sign {
leBuf[31] = leBuf[31] | 0x80 //nolint:gomnd
leBuf[31] |= 0x80 //nolint:gomnd
}
return leBuf
}
// UnpackSignY returns the sign and coordinate Y from a given compressed point.
// This method does not check that the Point belongs to the BabyJubJub curve,
// thus does not return error in such case. This method is intended to obtain
// the sign and the Y coordinate without checking if the point belongs to the
// curve, if the objective is to uncompress a point, Decompress method should
// be used instead.
func UnpackSignY(leBuf [32]byte) (bool, *big.Int) {
sign := false
y := big.NewInt(0)
if (leBuf[31] & 0x80) != 0x00 { //nolint:gomnd
sign = true
leBuf[31] &= 0x7F //nolint:gomnd
}
utils.SetBigIntFromLEBytes(y, leBuf[:])
return sign, y
}
// Compress the point into a 32 byte array that contains the y coordinate in
// little endian and the sign of the x coordinate.
func (p *Point) Compress() [32]byte {
sign := PointCoordSign(p.X)
return PackPoint(p.Y, sign)
return PackSignY(sign, p.Y)
}
// Decompress a compressed Point into p, and also returns the decompressed
// Point. Returns error if the compressed Point is invalid.
func (p *Point) Decompress(leBuf [32]byte) (*Point, error) {
sign := false
if (leBuf[31] & 0x80) != 0x00 { //nolint:gomnd
sign = true
leBuf[31] = leBuf[31] & 0x7F //nolint:gomnd
}
utils.SetBigIntFromLEBytes(p.Y, leBuf[:])
var sign bool
sign, p.Y = UnpackSignY(leBuf)
return PointFromSignAndY(sign, p.Y)
}

View File

@@ -218,6 +218,26 @@ func TestPointFromSignAndy(t *testing.T) {
assert.Equal(t, p.Y.String(), p2.Y.String())
}
func TestPackAndUnpackSignY(t *testing.T) {
x := utils.NewIntFromString(
"17777552123799933955779906779655732241715742912184938656739573121738514868268")
y := utils.NewIntFromString(
"2626589144620713026669568689430873010625803728049924121243784502389097019475")
p := &Point{X: x, Y: y}
pComp := p.Compress()
s, y := UnpackSignY(pComp)
pComp2 := PackSignY(s, y)
assert.Equal(t, pComp, pComp2)
emptyPointComp := [32]byte{}
s, y = UnpackSignY(emptyPointComp)
pComp2 = PackSignY(s, y)
assert.Equal(t, emptyPointComp, pComp2)
}
func TestCompressDecompress1(t *testing.T) {
x := utils.NewIntFromString(
"17777552123799933955779906779655732241715742912184938656739573121738514868268")

View File

@@ -0,0 +1,84 @@
package babyjub
import (
"bytes"
"crypto"
"io"
"math/big"
)
// BjjWrappedPublicKey is a wrapper for PublicKey.
type BjjWrappedPublicKey struct {
pubKey *PublicKey
}
// Equal returns true if the public keys are equal.
func (pub *BjjWrappedPublicKey) Equal(x crypto.PublicKey) bool {
var xk *BjjWrappedPublicKey
switch x := x.(type) {
case BjjWrappedPublicKey:
xk = &x
case *BjjWrappedPublicKey:
xk = x
default:
return false
}
return pub.pubKey.X.Cmp(xk.pubKey.X) == 0 &&
pub.pubKey.Y.Cmp(xk.pubKey.Y) == 0
}
// BjjWrappedPrivateKey is a wrapper for PrivateKey.
type BjjWrappedPrivateKey struct {
privKey *PrivateKey
}
// NewBjjWrappedKey creates a new BjjWrappedPrivateKey.
func NewBjjWrappedKey(privKey *PrivateKey) *BjjWrappedPrivateKey {
return &BjjWrappedPrivateKey{privKey}
}
// RandomBjjWrappedKey creates a new BjjWrappedPrivateKey with a random private key.
func RandomBjjWrappedKey() *BjjWrappedPrivateKey {
privKey := NewRandPrivKey()
return NewBjjWrappedKey(&privKey)
}
// Public returns the public key of the private key.
func (w *BjjWrappedPrivateKey) Public() crypto.PublicKey {
return &BjjWrappedPublicKey{w.privKey.Public()}
}
// Sign signs the digest with the private key.
func (w *BjjWrappedPrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
hash := opts.HashFunc()
switch hash {
// alredy hashed
case crypto.Hash(0):
default:
hasher := hash.New()
hasher.Write(digest)
digest = hasher.Sum(nil)
}
digestBI := big.NewInt(0).SetBytes(digest)
sig, err := w.privKey.SignPoseidon(digestBI)
if err != nil {
return nil, err
}
return sig.Compress().MarshalText()
}
// Equal returns true if the private keys are equal.
func (w *BjjWrappedPrivateKey) Equal(x crypto.PrivateKey) bool {
var xk *BjjWrappedPrivateKey
switch x := x.(type) {
case BjjWrappedPrivateKey:
xk = &x
case *BjjWrappedPrivateKey:
xk = x
default:
return false
}
return bytes.Equal(w.privKey[:], xk.privKey[:])
}

View File

@@ -0,0 +1,65 @@
package babyjub
import (
"crypto"
"crypto/rand"
"math/big"
"testing"
"github.com/iden3/go-iden3-crypto/poseidon"
"github.com/stretchr/testify/require"
)
// https://pkg.go.dev/crypto#PrivateKey
type shadowPrivateKey interface {
Public() crypto.PublicKey
Equal(x crypto.PrivateKey) bool
}
// https://pkg.go.dev/crypto#PublicKey
type shadowPublicKey interface {
Equal(x crypto.PublicKey) bool
}
func TestBjjWrappedPrivateKeyInterfaceImpl(t *testing.T) {
require.Implements(t, (*crypto.Signer)(nil), new(BjjWrappedPrivateKey))
require.Implements(t, (*shadowPrivateKey)(nil), new(BjjWrappedPrivateKey))
}
func TestBjjWrappedPrivateKey(t *testing.T) {
pk := RandomBjjWrappedKey()
hasher, err := poseidon.New(16)
require.NoError(t, err)
hasher.Write([]byte("test"))
digest := hasher.Sum(nil)
sig, err := pk.Sign(rand.Reader, digest, crypto.Hash(0))
require.NoError(t, err)
pub, ok := pk.Public().(*BjjWrappedPublicKey)
require.True(t, ok)
decomrpessSig, err := DecompressSig(sig)
require.NoError(t, err)
digestBI := big.NewInt(0).SetBytes(digest)
pub.pubKey.VerifyPoseidon(digestBI, decomrpessSig)
}
func TestBjjWrappedPrivateKeyEqual(t *testing.T) {
x1 := RandomBjjWrappedKey()
require.True(t, x1.Equal(x1))
x2 := RandomBjjWrappedKey()
require.False(t, x1.Equal(x2))
}
func TestBjjWrappedPublicKeyInterfaceImpl(t *testing.T) {
require.Implements(t, (*shadowPublicKey)(nil), new(BjjWrappedPublicKey))
}
func TestBjjWrappedPublicKeyEqual(t *testing.T) {
x1 := RandomBjjWrappedKey().Public().(*BjjWrappedPublicKey)
require.True(t, x1.Equal(x1))
x2 := RandomBjjWrappedKey().Public()
require.False(t, x1.Equal(x2))
}

View File

@@ -1,4 +1,5 @@
// Package babyjub eddsa implements the EdDSA over the BabyJubJub curve
//
//nolint:gomnd
package babyjub
@@ -16,9 +17,9 @@ import (
// pruneBuffer prunes the buffer during key generation according to RFC 8032.
// https://tools.ietf.org/html/rfc8032#page-13
func pruneBuffer(buf *[32]byte) *[32]byte {
buf[0] = buf[0] & 0xF8
buf[31] = buf[31] & 0x7F
buf[31] = buf[31] | 0x40
buf[0] &= 0xF8
buf[31] &= 0x7F
buf[31] |= 0x40
return buf
}
@@ -210,7 +211,7 @@ func (sComp *SignatureComp) Scan(src interface{}) error {
if len(srcB) != 64 {
return fmt.Errorf("can't scan []byte of len %d into Signature, want %d", len(srcB), 64)
}
copy(sComp[:], srcB[:])
copy(sComp[:], srcB)
return nil
}
@@ -229,7 +230,7 @@ func (s *Signature) Scan(src interface{}) error {
return fmt.Errorf("can't scan []byte of len %d into Signature, want %d", len(srcB), 64)
}
buf := [64]byte{}
copy(buf[:], srcB[:])
copy(buf[:], srcB)
_, err := s.Decompress(buf)
return err
}
@@ -242,7 +243,7 @@ func (s Signature) Value() (driver.Value, error) {
// SignMimc7 signs a message encoded as a big.Int in Zq using blake-512 hash
// for buffer hashing and mimc7 for big.Int hashing.
func (k *PrivateKey) SignMimc7(msg *big.Int) *Signature {
func (k *PrivateKey) SignMimc7(msg *big.Int) (*Signature, error) {
h1 := Blake512(k[:])
msgBuf := utils.BigIntLEBytes(msg)
msgBuf32 := [32]byte{}
@@ -255,23 +256,23 @@ func (k *PrivateKey) SignMimc7(msg *big.Int) *Signature {
hmInput := []*big.Int{R8.X, R8.Y, A.X, A.Y, msg}
hm, err := mimc7.Hash(hmInput, nil) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
panic(err)
return nil, err
}
S := new(big.Int).Lsh(k.Scalar().BigInt(), 3)
S = S.Mul(hm, S)
S.Add(r, S)
S.Mod(S, SubOrder) // S = r + hm * 8 * s
return &Signature{R8: R8, S: S}
return &Signature{R8: R8, S: S}, nil
}
// VerifyMimc7 verifies the signature of a message encoded as a big.Int in Zq
// using blake-512 hash for buffer hashing and mimc7 for big.Int hashing.
func (pk *PublicKey) VerifyMimc7(msg *big.Int, sig *Signature) bool {
func (pk *PublicKey) VerifyMimc7(msg *big.Int, sig *Signature) error {
hmInput := []*big.Int{sig.R8.X, sig.R8.Y, pk.X, pk.Y, msg}
hm, err := mimc7.Hash(hmInput, nil) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
return false
return err
}
left := NewPoint().Mul(sig.S, B8) // left = s * 8 * B
@@ -281,12 +282,15 @@ func (pk *PublicKey) VerifyMimc7(msg *big.Int, sig *Signature) bool {
rightProj := right.Projective()
rightProj.Add(sig.R8.Projective(), rightProj) // right = 8 * R + 8 * hm * A
right = rightProj.Affine()
return (left.X.Cmp(right.X) == 0) && (left.Y.Cmp(right.Y) == 0)
if (left.X.Cmp(right.X) == 0) && (left.Y.Cmp(right.Y) == 0) {
return nil
}
return fmt.Errorf("verifyMimc7 failed")
}
// SignPoseidon signs a message encoded as a big.Int in Zq using blake-512 hash
// for buffer hashing and Poseidon for big.Int hashing.
func (k *PrivateKey) SignPoseidon(msg *big.Int) *Signature {
func (k *PrivateKey) SignPoseidon(msg *big.Int) (*Signature, error) {
h1 := Blake512(k[:])
msgBuf := utils.BigIntLEBytes(msg)
msgBuf32 := [32]byte{}
@@ -300,7 +304,7 @@ func (k *PrivateKey) SignPoseidon(msg *big.Int) *Signature {
hmInput := []*big.Int{R8.X, R8.Y, A.X, A.Y, msg}
hm, err := poseidon.Hash(hmInput) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
panic(err)
return nil, err
}
S := new(big.Int).Lsh(k.Scalar().BigInt(), 3)
@@ -308,16 +312,16 @@ func (k *PrivateKey) SignPoseidon(msg *big.Int) *Signature {
S.Add(r, S)
S.Mod(S, SubOrder) // S = r + hm * 8 * s
return &Signature{R8: R8, S: S}
return &Signature{R8: R8, S: S}, nil
}
// VerifyPoseidon verifies the signature of a message encoded as a big.Int in Zq
// using blake-512 hash for buffer hashing and Poseidon for big.Int hashing.
func (pk *PublicKey) VerifyPoseidon(msg *big.Int, sig *Signature) bool {
func (pk *PublicKey) VerifyPoseidon(msg *big.Int, sig *Signature) error {
hmInput := []*big.Int{sig.R8.X, sig.R8.Y, pk.X, pk.Y, msg}
hm, err := poseidon.Hash(hmInput) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
return false
return err
}
left := NewPoint().Mul(sig.S, B8) // left = s * 8 * B
@@ -327,7 +331,10 @@ func (pk *PublicKey) VerifyPoseidon(msg *big.Int, sig *Signature) bool {
rightProj := right.Projective()
rightProj.Add(sig.R8.Projective(), rightProj) // right = 8 * R + 8 * hm * A
right = rightProj.Affine()
return (left.X.Cmp(right.X) == 0) && (left.Y.Cmp(right.Y) == 0)
if (left.X.Cmp(right.X) == 0) && (left.Y.Cmp(right.Y) == 0) {
return nil
}
return fmt.Errorf("verifyPoseidon failed")
}
// Scan implements Scanner for database/sql.

View File

@@ -43,7 +43,8 @@ func TestSignVerifyMimc7(t *testing.T) {
"13622229784656158136036771217484571176836296686641868549125388198837476602820",
pk.Y.String())
sig := k.SignMimc7(msg)
sig, err := k.SignMimc7(msg)
assert.NoError(t, err)
assert.Equal(t,
"11384336176656855268977457483345535180380036354188103142384839473266348197733",
sig.R8.X.String())
@@ -54,20 +55,20 @@ func TestSignVerifyMimc7(t *testing.T) {
"2523202440825208709475937830811065542425109372212752003460238913256192595070",
sig.S.String())
ok := pk.VerifyMimc7(msg, sig)
assert.Equal(t, true, ok)
err = pk.VerifyMimc7(msg, sig)
assert.NoError(t, err)
sigBuf := sig.Compress()
sig2, err := new(Signature).Decompress(sigBuf)
assert.Equal(t, nil, err)
assert.NoError(t, err)
assert.Equal(t, ""+
"dfedb4315d3f2eb4de2d3c510d7a987dcab67089c8ace06308827bf5bcbe02a2"+
"7ed40dab29bf993c928e789d007387998901a24913d44fddb64b1f21fc149405",
hex.EncodeToString(sigBuf[:]))
ok = pk.VerifyMimc7(msg, sig2)
assert.Equal(t, true, ok)
err = pk.VerifyMimc7(msg, sig2)
assert.NoError(t, err)
}
func TestSignVerifyPoseidon(t *testing.T) {
@@ -89,7 +90,8 @@ func TestSignVerifyPoseidon(t *testing.T) {
"13622229784656158136036771217484571176836296686641868549125388198837476602820",
pk.Y.String())
sig := k.SignPoseidon(msg)
sig, err := k.SignPoseidon(msg)
assert.NoError(t, err)
assert.Equal(t,
"11384336176656855268977457483345535180380036354188103142384839473266348197733",
sig.R8.X.String())
@@ -97,23 +99,23 @@ func TestSignVerifyPoseidon(t *testing.T) {
"15383486972088797283337779941324724402501462225528836549661220478783371668959",
sig.R8.Y.String())
assert.Equal(t,
"1398758333392199195742243841591064350253744445503462896781493968760929513778",
"1672775540645840396591609181675628451599263765380031905495115170613215233181",
sig.S.String())
ok := pk.VerifyPoseidon(msg, sig)
assert.Equal(t, true, ok)
err = pk.VerifyPoseidon(msg, sig)
assert.NoError(t, err)
sigBuf := sig.Compress()
sig2, err := new(Signature).Decompress(sigBuf)
assert.Equal(t, nil, err)
assert.NoError(t, err)
assert.Equal(t, ""+
"dfedb4315d3f2eb4de2d3c510d7a987dcab67089c8ace06308827bf5bcbe02a2"+
"32f16b0f2f4c4e1169aa59685637e1429b6581a9531d058d65f4ab224eab1703",
"9d043ece562a8f82bfc0adb640c0107a7d3a27c1c7c1a6179a0da73de5c1b203",
hex.EncodeToString(sigBuf[:]))
ok = pk.VerifyPoseidon(msg, sig2)
assert.Equal(t, true, ok)
err = pk.VerifyPoseidon(msg, sig2)
assert.NoError(t, err)
}
func TestCompressDecompress(t *testing.T) {
@@ -128,22 +130,28 @@ func TestCompressDecompress(t *testing.T) {
panic(err)
}
msg := utils.SetBigIntFromLEBytes(new(big.Int), msgBuf)
sig := k.SignMimc7(msg)
sig, err := k.SignMimc7(msg)
assert.NoError(t, err)
sigBuf := sig.Compress()
sig2, err := new(Signature).Decompress(sigBuf)
assert.Equal(t, nil, err)
ok := pk.VerifyMimc7(msg, sig2)
assert.Equal(t, true, ok)
assert.NoError(t, err)
err = pk.VerifyMimc7(msg, sig2)
assert.NoError(t, err)
}
}
func TestSignatureCompScannerValuer(t *testing.T) {
privK := NewRandPrivKey()
var value driver.Valuer //nolint:gosimple this is done to ensure interface compability
value = privK.SignPoseidon(big.NewInt(674238462)).Compress()
scan := privK.SignPoseidon(big.NewInt(1)).Compress()
var err error
sig, err := privK.SignPoseidon(big.NewInt(674238462))
assert.NoError(t, err)
var value driver.Valuer //nolint:gosimple // this is done to ensure interface compatibility
value = sig.Compress()
sig, err = privK.SignPoseidon(big.NewInt(1))
assert.NoError(t, err)
scan := sig.Compress()
fromDB, err := value.Value()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Nil(t, scan.Scan(fromDB))
assert.Equal(t, value, scan)
}
@@ -152,10 +160,13 @@ func TestSignatureScannerValuer(t *testing.T) {
privK := NewRandPrivKey()
var value driver.Valuer
var scan sql.Scanner
value = privK.SignPoseidon(big.NewInt(674238462))
scan = privK.SignPoseidon(big.NewInt(1))
var err error
value, err = privK.SignPoseidon(big.NewInt(674238462))
assert.NoError(t, err)
scan, err = privK.SignPoseidon(big.NewInt(1))
assert.NoError(t, err)
fromDB, err := value.Value()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Nil(t, scan.Scan(fromDB))
assert.Equal(t, value, scan)
}
@@ -217,12 +228,12 @@ func BenchmarkBabyjubEddsa(b *testing.B) {
})
for i := 0; i < n; i++ {
sigs[i%n] = k.SignMimc7(msgs[i%n])
sigs[i%n], _ = k.SignMimc7(msgs[i%n])
}
b.Run("VerifyMimc7", func(b *testing.B) {
for i := 0; i < b.N; i++ {
pk.VerifyMimc7(msgs[i%n], sigs[i%n])
_ = pk.VerifyMimc7(msgs[i%n], sigs[i%n])
}
})
@@ -233,12 +244,12 @@ func BenchmarkBabyjubEddsa(b *testing.B) {
})
for i := 0; i < n; i++ {
sigs[i%n] = k.SignPoseidon(msgs[i%n])
sigs[i%n], _ = k.SignPoseidon(msgs[i%n])
}
b.Run("VerifyPoseidon", func(b *testing.B) {
for i := 0; i < b.N; i++ {
pk.VerifyPoseidon(msgs[i%n], sigs[i%n])
_ = pk.VerifyPoseidon(msgs[i%n], sigs[i%n])
}
})
}

View File

@@ -12,9 +12,22 @@ import (
// the original blake from the SHA3 competition and not the new blake2 version.
func Blake512(m []byte) []byte {
h := blake512.New()
_, err := h.Write(m[:])
_, err := h.Write(m)
if err != nil {
panic(err)
}
return h.Sum(nil)
}
// DecompressSig decompresses a compressed signature.
func DecompressSig(commpresedSig []byte) (*Signature, error) {
poseidonComSig := &SignatureComp{}
if err := poseidonComSig.UnmarshalText(commpresedSig); err != nil {
return nil, err
}
poseidonDecSig, err := poseidonComSig.Decompress()
if err != nil {
return nil, err
}
return poseidonDecSig, nil
}

View File

@@ -1,31 +1,19 @@
package constants
import (
"fmt"
"math/big"
)
const qString = "21888242871839275222246405745257275088548364400416034343698204186575808495617"
// Q is the order of the integer field (Zq) that fits inside the SNARK.
var Q *big.Int
var Q, _ = new(big.Int).SetString(qString, 10)
// Zero is 0.
var Zero *big.Int
var Zero = big.NewInt(0)
// One is 1.
var One *big.Int
var One = big.NewInt(1)
// MinusOne is -1.
var MinusOne *big.Int
func init() {
Zero = big.NewInt(0)
One = big.NewInt(1)
MinusOne = big.NewInt(-1)
qString := "21888242871839275222246405745257275088548364400416034343698204186575808495617"
var ok bool
Q, ok = new(big.Int).SetString(qString, 10)
if !ok {
panic(fmt.Sprintf("Bad base 10 string %s", qString))
}
}
var MinusOne = big.NewInt(-1)

View File

@@ -1,4 +1,4 @@
// Copyright 2020 ConsenSys AG
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by goff DO NOT EDIT
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ff
@@ -20,15 +20,6 @@ import (
"math/bits"
)
func madd(a, b, t, u, v uint64) (uint64, uint64, uint64) {
var carry uint64
hi, lo := bits.Mul64(a, b)
v, carry = bits.Add64(lo, v, 0)
u, carry = bits.Add64(hi, u, carry)
t, _ = bits.Add64(t, 0, carry)
return t, u, v
}
// madd0 hi = a*b + c (discards lo bits)
func madd0(a, b, c uint64) (hi uint64) {
var carry, lo uint64
@@ -58,59 +49,6 @@ func madd2(a, b, c, d uint64) (hi uint64, lo uint64) {
return
}
// madd2s superhi, hi, lo = 2*a*b + c + d + e
func madd2s(a, b, c, d, e uint64) (superhi, hi, lo uint64) {
var carry, sum uint64
hi, lo = bits.Mul64(a, b)
lo, carry = bits.Add64(lo, lo, 0)
hi, superhi = bits.Add64(hi, hi, carry)
sum, carry = bits.Add64(c, e, 0)
hi, _ = bits.Add64(hi, 0, carry)
lo, carry = bits.Add64(lo, sum, 0)
hi, _ = bits.Add64(hi, 0, carry)
hi, _ = bits.Add64(hi, 0, d)
return
}
func madd1s(a, b, d, e uint64) (superhi, hi, lo uint64) {
var carry uint64
hi, lo = bits.Mul64(a, b)
lo, carry = bits.Add64(lo, lo, 0)
hi, superhi = bits.Add64(hi, hi, carry)
lo, carry = bits.Add64(lo, e, 0)
hi, _ = bits.Add64(hi, 0, carry)
hi, _ = bits.Add64(hi, 0, d)
return
}
func madd2sb(a, b, c, e uint64) (superhi, hi, lo uint64) {
var carry, sum uint64
hi, lo = bits.Mul64(a, b)
lo, carry = bits.Add64(lo, lo, 0)
hi, superhi = bits.Add64(hi, hi, carry)
sum, carry = bits.Add64(c, e, 0)
hi, _ = bits.Add64(hi, 0, carry)
lo, carry = bits.Add64(lo, sum, 0)
hi, _ = bits.Add64(hi, 0, carry)
return
}
func madd1sb(a, b, e uint64) (superhi, hi, lo uint64) {
var carry uint64
hi, lo = bits.Mul64(a, b)
lo, carry = bits.Add64(lo, lo, 0)
hi, superhi = bits.Add64(hi, hi, carry)
lo, carry = bits.Add64(lo, e, 0)
hi, _ = bits.Add64(hi, 0, carry)
return
}
func madd3(a, b, c, d, e uint64) (hi uint64, lo uint64) {
var carry uint64
hi, lo = bits.Mul64(a, b)

24
ff/asm.go Normal file
View File

@@ -0,0 +1,24 @@
//go:build !noadx
// +build !noadx
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ff
import "golang.org/x/sys/cpu"
var supportAdx = cpu.X86.HasADX && cpu.X86.HasBMI2

25
ff/asm_noadx.go Normal file
View File

@@ -0,0 +1,25 @@
//go:build noadx
// +build noadx
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ff
// note: this is needed for test purposes, as dynamically changing supportAdx doesn't flag
// certain errors (like fatal error: missing stackmap)
// this ensures we test all asm path.
var supportAdx = false

43
ff/doc.go Normal file
View File

@@ -0,0 +1,43 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
// Package ff contains field arithmetic operations for modulus = 0x30644e...000001.
//
// The API is similar to math/big (big.Int), but the operations are significantly faster (up to 20x for the modular multiplication on amd64, see also https://hackmd.io/@zkteam/modular_multiplication)
//
// The modulus is hardcoded in all the operations.
//
// Field elements are represented as an array, and assumed to be in Montgomery form in all methods:
// type Element [4]uint64
//
// Example API signature
// // Mul z = x * y mod q
// func (z *Element) Mul(x, y *Element) *Element
//
// and can be used like so:
// var a, b Element
// a.SetUint64(2)
// b.SetString("984896738")
// a.Mul(a, b)
// a.Sub(a, a)
// .Add(a, b)
// .Inv(a)
// b.Exp(b, new(big.Int).SetUint64(42))
//
// Modulus
// 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 // base 16
// 21888242871839275222246405745257275088548364400416034343698204186575808495617 // base 10
package ff

File diff suppressed because it is too large Load Diff

136
ff/element_fuzz.go Normal file
View File

@@ -0,0 +1,136 @@
//go:build gofuzz
// +build gofuzz
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ff
import (
"bytes"
"encoding/binary"
"io"
"math/big"
"math/bits"
)
const (
fuzzInteresting = 1
fuzzNormal = 0
fuzzDiscard = -1
)
// Fuzz arithmetic operations fuzzer
func Fuzz(data []byte) int {
r := bytes.NewReader(data)
var e1, e2 Element
e1.SetRawBytes(r)
e2.SetRawBytes(r)
{
// mul assembly
var c, _c Element
a, _a, b, _b := e1, e1, e2, e2
c.Mul(&a, &b)
_mulGeneric(&_c, &_a, &_b)
if !c.Equal(&_c) {
panic("mul asm != mul generic on Element")
}
}
{
// inverse
inv := e1
inv.Inverse(&inv)
var bInv, b1, b2 big.Int
e1.ToBigIntRegular(&b1)
bInv.ModInverse(&b1, Modulus())
inv.ToBigIntRegular(&b2)
if b2.Cmp(&bInv) != 0 {
panic("inverse operation doesn't match big int result")
}
}
{
// a + -a == 0
a, b := e1, e1
b.Neg(&b)
a.Add(&a, &b)
if !a.IsZero() {
panic("a + -a != 0")
}
}
return fuzzNormal
}
// SetRawBytes reads up to Bytes (bytes needed to represent Element) from reader
// and interpret it as big endian uint64
// used for fuzzing purposes only
func (z *Element) SetRawBytes(r io.Reader) {
buf := make([]byte, 8)
for i := 0; i < len(z); i++ {
if _, err := io.ReadFull(r, buf); err != nil {
goto eof
}
z[i] = binary.BigEndian.Uint64(buf[:])
}
eof:
z[3] %= qElement[3]
if z.BiggerModulus() {
var b uint64
z[0], b = bits.Sub64(z[0], qElement[0], 0)
z[1], b = bits.Sub64(z[1], qElement[1], b)
z[2], b = bits.Sub64(z[2], qElement[2], b)
z[3], b = bits.Sub64(z[3], qElement[3], b)
}
return
}
func (z *Element) BiggerModulus() bool {
if z[3] > qElement[3] {
return true
}
if z[3] < qElement[3] {
return false
}
if z[2] > qElement[2] {
return true
}
if z[2] < qElement[2] {
return false
}
if z[1] > qElement[1] {
return true
}
if z[1] < qElement[1] {
return false
}
return z[0] >= qElement[0]
}

466
ff/element_mul_adx_amd64.s Normal file
View File

@@ -0,0 +1,466 @@
// +build amd64_adx
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "textflag.h"
#include "funcdata.h"
// modulus q
DATA q<>+0(SB)/8, $0x43e1f593f0000001
DATA q<>+8(SB)/8, $0x2833e84879b97091
DATA q<>+16(SB)/8, $0xb85045b68181585d
DATA q<>+24(SB)/8, $0x30644e72e131a029
GLOBL q<>(SB), (RODATA+NOPTR), $32
// qInv0 q'[0]
DATA qInv0<>(SB)/8, $0xc2e1f593efffffff
GLOBL qInv0<>(SB), (RODATA+NOPTR), $8
#define REDUCE(ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3) \
MOVQ ra0, rb0; \
SUBQ q<>(SB), ra0; \
MOVQ ra1, rb1; \
SBBQ q<>+8(SB), ra1; \
MOVQ ra2, rb2; \
SBBQ q<>+16(SB), ra2; \
MOVQ ra3, rb3; \
SBBQ q<>+24(SB), ra3; \
CMOVQCS rb0, ra0; \
CMOVQCS rb1, ra1; \
CMOVQCS rb2, ra2; \
CMOVQCS rb3, ra3; \
// mul(res, x, y *Element)
TEXT ·mul(SB), NOSPLIT, $0-24
// the algorithm is described here
// https://hackmd.io/@zkteam/modular_multiplication
// however, to benefit from the ADCX and ADOX carry chains
// we split the inner loops in 2:
// for i=0 to N-1
// for j=0 to N-1
// (A,t[j]) := t[j] + x[j]*y[i] + A
// m := t[0]*q'[0] mod W
// C,_ := t[0] + m*q[0]
// for j=1 to N-1
// (C,t[j-1]) := t[j] + m*q[j] + C
// t[N-1] = C + A
MOVQ x+8(FP), SI
// x[0] -> DI
// x[1] -> R8
// x[2] -> R9
// x[3] -> R10
MOVQ 0(SI), DI
MOVQ 8(SI), R8
MOVQ 16(SI), R9
MOVQ 24(SI), R10
MOVQ y+16(FP), R11
// A -> BP
// t[0] -> R14
// t[1] -> R15
// t[2] -> CX
// t[3] -> BX
// clear the flags
XORQ AX, AX
MOVQ 0(R11), DX
// (A,t[0]) := x[0]*y[0] + A
MULXQ DI, R14, R15
// (A,t[1]) := x[1]*y[0] + A
MULXQ R8, AX, CX
ADOXQ AX, R15
// (A,t[2]) := x[2]*y[0] + A
MULXQ R9, AX, BX
ADOXQ AX, CX
// (A,t[3]) := x[3]*y[0] + A
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// clear the flags
XORQ AX, AX
MOVQ 8(R11), DX
// (A,t[0]) := t[0] + x[0]*y[1] + A
MULXQ DI, AX, BP
ADOXQ AX, R14
// (A,t[1]) := t[1] + x[1]*y[1] + A
ADCXQ BP, R15
MULXQ R8, AX, BP
ADOXQ AX, R15
// (A,t[2]) := t[2] + x[2]*y[1] + A
ADCXQ BP, CX
MULXQ R9, AX, BP
ADOXQ AX, CX
// (A,t[3]) := t[3] + x[3]*y[1] + A
ADCXQ BP, BX
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADCXQ AX, BP
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// clear the flags
XORQ AX, AX
MOVQ 16(R11), DX
// (A,t[0]) := t[0] + x[0]*y[2] + A
MULXQ DI, AX, BP
ADOXQ AX, R14
// (A,t[1]) := t[1] + x[1]*y[2] + A
ADCXQ BP, R15
MULXQ R8, AX, BP
ADOXQ AX, R15
// (A,t[2]) := t[2] + x[2]*y[2] + A
ADCXQ BP, CX
MULXQ R9, AX, BP
ADOXQ AX, CX
// (A,t[3]) := t[3] + x[3]*y[2] + A
ADCXQ BP, BX
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADCXQ AX, BP
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// clear the flags
XORQ AX, AX
MOVQ 24(R11), DX
// (A,t[0]) := t[0] + x[0]*y[3] + A
MULXQ DI, AX, BP
ADOXQ AX, R14
// (A,t[1]) := t[1] + x[1]*y[3] + A
ADCXQ BP, R15
MULXQ R8, AX, BP
ADOXQ AX, R15
// (A,t[2]) := t[2] + x[2]*y[3] + A
ADCXQ BP, CX
MULXQ R9, AX, BP
ADOXQ AX, CX
// (A,t[3]) := t[3] + x[3]*y[3] + A
ADCXQ BP, BX
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADCXQ AX, BP
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// reduce element(R14,R15,CX,BX) using temp registers (R13,SI,R12,R11)
REDUCE(R14,R15,CX,BX,R13,SI,R12,R11)
MOVQ res+0(FP), AX
MOVQ R14, 0(AX)
MOVQ R15, 8(AX)
MOVQ CX, 16(AX)
MOVQ BX, 24(AX)
RET
TEXT ·fromMont(SB), NOSPLIT, $0-8
// the algorithm is described here
// https://hackmd.io/@zkteam/modular_multiplication
// when y = 1 we have:
// for i=0 to N-1
// t[i] = x[i]
// for i=0 to N-1
// m := t[0]*q'[0] mod W
// C,_ := t[0] + m*q[0]
// for j=1 to N-1
// (C,t[j-1]) := t[j] + m*q[j] + C
// t[N-1] = C
MOVQ res+0(FP), DX
MOVQ 0(DX), R14
MOVQ 8(DX), R15
MOVQ 16(DX), CX
MOVQ 24(DX), BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
// reduce element(R14,R15,CX,BX) using temp registers (SI,DI,R8,R9)
REDUCE(R14,R15,CX,BX,SI,DI,R8,R9)
MOVQ res+0(FP), AX
MOVQ R14, 0(AX)
MOVQ R15, 8(AX)
MOVQ CX, 16(AX)
MOVQ BX, 24(AX)
RET

488
ff/element_mul_amd64.s Normal file
View File

@@ -0,0 +1,488 @@
// +build !amd64_adx
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "textflag.h"
#include "funcdata.h"
// modulus q
DATA q<>+0(SB)/8, $0x43e1f593f0000001
DATA q<>+8(SB)/8, $0x2833e84879b97091
DATA q<>+16(SB)/8, $0xb85045b68181585d
DATA q<>+24(SB)/8, $0x30644e72e131a029
GLOBL q<>(SB), (RODATA+NOPTR), $32
// qInv0 q'[0]
DATA qInv0<>(SB)/8, $0xc2e1f593efffffff
GLOBL qInv0<>(SB), (RODATA+NOPTR), $8
#define REDUCE(ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3) \
MOVQ ra0, rb0; \
SUBQ q<>(SB), ra0; \
MOVQ ra1, rb1; \
SBBQ q<>+8(SB), ra1; \
MOVQ ra2, rb2; \
SBBQ q<>+16(SB), ra2; \
MOVQ ra3, rb3; \
SBBQ q<>+24(SB), ra3; \
CMOVQCS rb0, ra0; \
CMOVQCS rb1, ra1; \
CMOVQCS rb2, ra2; \
CMOVQCS rb3, ra3; \
// mul(res, x, y *Element)
TEXT ·mul(SB), $24-24
// the algorithm is described here
// https://hackmd.io/@zkteam/modular_multiplication
// however, to benefit from the ADCX and ADOX carry chains
// we split the inner loops in 2:
// for i=0 to N-1
// for j=0 to N-1
// (A,t[j]) := t[j] + x[j]*y[i] + A
// m := t[0]*q'[0] mod W
// C,_ := t[0] + m*q[0]
// for j=1 to N-1
// (C,t[j-1]) := t[j] + m*q[j] + C
// t[N-1] = C + A
NO_LOCAL_POINTERS
CMPB ·supportAdx(SB), $1
JNE l1
MOVQ x+8(FP), SI
// x[0] -> DI
// x[1] -> R8
// x[2] -> R9
// x[3] -> R10
MOVQ 0(SI), DI
MOVQ 8(SI), R8
MOVQ 16(SI), R9
MOVQ 24(SI), R10
MOVQ y+16(FP), R11
// A -> BP
// t[0] -> R14
// t[1] -> R15
// t[2] -> CX
// t[3] -> BX
// clear the flags
XORQ AX, AX
MOVQ 0(R11), DX
// (A,t[0]) := x[0]*y[0] + A
MULXQ DI, R14, R15
// (A,t[1]) := x[1]*y[0] + A
MULXQ R8, AX, CX
ADOXQ AX, R15
// (A,t[2]) := x[2]*y[0] + A
MULXQ R9, AX, BX
ADOXQ AX, CX
// (A,t[3]) := x[3]*y[0] + A
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// clear the flags
XORQ AX, AX
MOVQ 8(R11), DX
// (A,t[0]) := t[0] + x[0]*y[1] + A
MULXQ DI, AX, BP
ADOXQ AX, R14
// (A,t[1]) := t[1] + x[1]*y[1] + A
ADCXQ BP, R15
MULXQ R8, AX, BP
ADOXQ AX, R15
// (A,t[2]) := t[2] + x[2]*y[1] + A
ADCXQ BP, CX
MULXQ R9, AX, BP
ADOXQ AX, CX
// (A,t[3]) := t[3] + x[3]*y[1] + A
ADCXQ BP, BX
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADCXQ AX, BP
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// clear the flags
XORQ AX, AX
MOVQ 16(R11), DX
// (A,t[0]) := t[0] + x[0]*y[2] + A
MULXQ DI, AX, BP
ADOXQ AX, R14
// (A,t[1]) := t[1] + x[1]*y[2] + A
ADCXQ BP, R15
MULXQ R8, AX, BP
ADOXQ AX, R15
// (A,t[2]) := t[2] + x[2]*y[2] + A
ADCXQ BP, CX
MULXQ R9, AX, BP
ADOXQ AX, CX
// (A,t[3]) := t[3] + x[3]*y[2] + A
ADCXQ BP, BX
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADCXQ AX, BP
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// clear the flags
XORQ AX, AX
MOVQ 24(R11), DX
// (A,t[0]) := t[0] + x[0]*y[3] + A
MULXQ DI, AX, BP
ADOXQ AX, R14
// (A,t[1]) := t[1] + x[1]*y[3] + A
ADCXQ BP, R15
MULXQ R8, AX, BP
ADOXQ AX, R15
// (A,t[2]) := t[2] + x[2]*y[3] + A
ADCXQ BP, CX
MULXQ R9, AX, BP
ADOXQ AX, CX
// (A,t[3]) := t[3] + x[3]*y[3] + A
ADCXQ BP, BX
MULXQ R10, AX, BP
ADOXQ AX, BX
// A += carries from ADCXQ and ADOXQ
MOVQ $0, AX
ADCXQ AX, BP
ADOXQ AX, BP
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
// clear the flags
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, R12
ADCXQ R14, AX
MOVQ R12, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
// t[3] = C + A
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ BP, BX
// reduce element(R14,R15,CX,BX) using temp registers (R13,SI,R12,R11)
REDUCE(R14,R15,CX,BX,R13,SI,R12,R11)
MOVQ res+0(FP), AX
MOVQ R14, 0(AX)
MOVQ R15, 8(AX)
MOVQ CX, 16(AX)
MOVQ BX, 24(AX)
RET
l1:
MOVQ res+0(FP), AX
MOVQ AX, (SP)
MOVQ x+8(FP), AX
MOVQ AX, 8(SP)
MOVQ y+16(FP), AX
MOVQ AX, 16(SP)
CALL ·_mulGeneric(SB)
RET
TEXT ·fromMont(SB), $8-8
NO_LOCAL_POINTERS
// the algorithm is described here
// https://hackmd.io/@zkteam/modular_multiplication
// when y = 1 we have:
// for i=0 to N-1
// t[i] = x[i]
// for i=0 to N-1
// m := t[0]*q'[0] mod W
// C,_ := t[0] + m*q[0]
// for j=1 to N-1
// (C,t[j-1]) := t[j] + m*q[j] + C
// t[N-1] = C
CMPB ·supportAdx(SB), $1
JNE l2
MOVQ res+0(FP), DX
MOVQ 0(DX), R14
MOVQ 8(DX), R15
MOVQ 16(DX), CX
MOVQ 24(DX), BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
XORQ DX, DX
// m := t[0]*q'[0] mod W
MOVQ qInv0<>(SB), DX
IMULQ R14, DX
XORQ AX, AX
// C,_ := t[0] + m*q[0]
MULXQ q<>+0(SB), AX, BP
ADCXQ R14, AX
MOVQ BP, R14
// (C,t[0]) := t[1] + m*q[1] + C
ADCXQ R15, R14
MULXQ q<>+8(SB), AX, R15
ADOXQ AX, R14
// (C,t[1]) := t[2] + m*q[2] + C
ADCXQ CX, R15
MULXQ q<>+16(SB), AX, CX
ADOXQ AX, R15
// (C,t[2]) := t[3] + m*q[3] + C
ADCXQ BX, CX
MULXQ q<>+24(SB), AX, BX
ADOXQ AX, CX
MOVQ $0, AX
ADCXQ AX, BX
ADOXQ AX, BX
// reduce element(R14,R15,CX,BX) using temp registers (SI,DI,R8,R9)
REDUCE(R14,R15,CX,BX,SI,DI,R8,R9)
MOVQ res+0(FP), AX
MOVQ R14, 0(AX)
MOVQ R15, 8(AX)
MOVQ CX, 16(AX)
MOVQ BX, 24(AX)
RET
l2:
MOVQ res+0(FP), AX
MOVQ AX, (SP)
CALL ·_fromMontGeneric(SB)
RET

50
ff/element_ops_amd64.go Normal file
View File

@@ -0,0 +1,50 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ff
//go:noescape
func MulBy3(x *Element)
//go:noescape
func MulBy5(x *Element)
//go:noescape
func MulBy13(x *Element)
//go:noescape
func add(res, x, y *Element)
//go:noescape
func sub(res, x, y *Element)
//go:noescape
func neg(res, x *Element)
//go:noescape
func double(res, x *Element)
//go:noescape
func mul(res, x, y *Element)
//go:noescape
func fromMont(res *Element)
//go:noescape
func reduce(res *Element)
//go:noescape
func Butterfly(a, b *Element)

340
ff/element_ops_amd64.s Normal file
View File

@@ -0,0 +1,340 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "textflag.h"
#include "funcdata.h"
// modulus q
DATA q<>+0(SB)/8, $0x43e1f593f0000001
DATA q<>+8(SB)/8, $0x2833e84879b97091
DATA q<>+16(SB)/8, $0xb85045b68181585d
DATA q<>+24(SB)/8, $0x30644e72e131a029
GLOBL q<>(SB), (RODATA+NOPTR), $32
// qInv0 q'[0]
DATA qInv0<>(SB)/8, $0xc2e1f593efffffff
GLOBL qInv0<>(SB), (RODATA+NOPTR), $8
#define REDUCE(ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3) \
MOVQ ra0, rb0; \
SUBQ q<>(SB), ra0; \
MOVQ ra1, rb1; \
SBBQ q<>+8(SB), ra1; \
MOVQ ra2, rb2; \
SBBQ q<>+16(SB), ra2; \
MOVQ ra3, rb3; \
SBBQ q<>+24(SB), ra3; \
CMOVQCS rb0, ra0; \
CMOVQCS rb1, ra1; \
CMOVQCS rb2, ra2; \
CMOVQCS rb3, ra3; \
// add(res, x, y *Element)
TEXT ·add(SB), NOSPLIT, $0-24
MOVQ x+8(FP), AX
MOVQ 0(AX), CX
MOVQ 8(AX), BX
MOVQ 16(AX), SI
MOVQ 24(AX), DI
MOVQ y+16(FP), DX
ADDQ 0(DX), CX
ADCQ 8(DX), BX
ADCQ 16(DX), SI
ADCQ 24(DX), DI
// reduce element(CX,BX,SI,DI) using temp registers (R8,R9,R10,R11)
REDUCE(CX,BX,SI,DI,R8,R9,R10,R11)
MOVQ res+0(FP), R12
MOVQ CX, 0(R12)
MOVQ BX, 8(R12)
MOVQ SI, 16(R12)
MOVQ DI, 24(R12)
RET
// sub(res, x, y *Element)
TEXT ·sub(SB), NOSPLIT, $0-24
XORQ DI, DI
MOVQ x+8(FP), SI
MOVQ 0(SI), AX
MOVQ 8(SI), DX
MOVQ 16(SI), CX
MOVQ 24(SI), BX
MOVQ y+16(FP), SI
SUBQ 0(SI), AX
SBBQ 8(SI), DX
SBBQ 16(SI), CX
SBBQ 24(SI), BX
MOVQ $0x43e1f593f0000001, R8
MOVQ $0x2833e84879b97091, R9
MOVQ $0xb85045b68181585d, R10
MOVQ $0x30644e72e131a029, R11
CMOVQCC DI, R8
CMOVQCC DI, R9
CMOVQCC DI, R10
CMOVQCC DI, R11
ADDQ R8, AX
ADCQ R9, DX
ADCQ R10, CX
ADCQ R11, BX
MOVQ res+0(FP), R12
MOVQ AX, 0(R12)
MOVQ DX, 8(R12)
MOVQ CX, 16(R12)
MOVQ BX, 24(R12)
RET
// double(res, x *Element)
TEXT ·double(SB), NOSPLIT, $0-16
MOVQ x+8(FP), AX
MOVQ 0(AX), DX
MOVQ 8(AX), CX
MOVQ 16(AX), BX
MOVQ 24(AX), SI
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
MOVQ res+0(FP), R11
MOVQ DX, 0(R11)
MOVQ CX, 8(R11)
MOVQ BX, 16(R11)
MOVQ SI, 24(R11)
RET
// neg(res, x *Element)
TEXT ·neg(SB), NOSPLIT, $0-16
MOVQ res+0(FP), DI
MOVQ x+8(FP), AX
MOVQ 0(AX), DX
MOVQ 8(AX), CX
MOVQ 16(AX), BX
MOVQ 24(AX), SI
MOVQ DX, AX
ORQ CX, AX
ORQ BX, AX
ORQ SI, AX
TESTQ AX, AX
JEQ l1
MOVQ $0x43e1f593f0000001, R8
SUBQ DX, R8
MOVQ R8, 0(DI)
MOVQ $0x2833e84879b97091, R8
SBBQ CX, R8
MOVQ R8, 8(DI)
MOVQ $0xb85045b68181585d, R8
SBBQ BX, R8
MOVQ R8, 16(DI)
MOVQ $0x30644e72e131a029, R8
SBBQ SI, R8
MOVQ R8, 24(DI)
RET
l1:
MOVQ AX, 0(DI)
MOVQ AX, 8(DI)
MOVQ AX, 16(DI)
MOVQ AX, 24(DI)
RET
TEXT ·reduce(SB), NOSPLIT, $0-8
MOVQ res+0(FP), AX
MOVQ 0(AX), DX
MOVQ 8(AX), CX
MOVQ 16(AX), BX
MOVQ 24(AX), SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
MOVQ DX, 0(AX)
MOVQ CX, 8(AX)
MOVQ BX, 16(AX)
MOVQ SI, 24(AX)
RET
// MulBy3(x *Element)
TEXT ·MulBy3(SB), NOSPLIT, $0-8
MOVQ x+0(FP), AX
MOVQ 0(AX), DX
MOVQ 8(AX), CX
MOVQ 16(AX), BX
MOVQ 24(AX), SI
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
ADDQ 0(AX), DX
ADCQ 8(AX), CX
ADCQ 16(AX), BX
ADCQ 24(AX), SI
// reduce element(DX,CX,BX,SI) using temp registers (R11,R12,R13,R14)
REDUCE(DX,CX,BX,SI,R11,R12,R13,R14)
MOVQ DX, 0(AX)
MOVQ CX, 8(AX)
MOVQ BX, 16(AX)
MOVQ SI, 24(AX)
RET
// MulBy5(x *Element)
TEXT ·MulBy5(SB), NOSPLIT, $0-8
MOVQ x+0(FP), AX
MOVQ 0(AX), DX
MOVQ 8(AX), CX
MOVQ 16(AX), BX
MOVQ 24(AX), SI
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (R11,R12,R13,R14)
REDUCE(DX,CX,BX,SI,R11,R12,R13,R14)
ADDQ 0(AX), DX
ADCQ 8(AX), CX
ADCQ 16(AX), BX
ADCQ 24(AX), SI
// reduce element(DX,CX,BX,SI) using temp registers (R15,DI,R8,R9)
REDUCE(DX,CX,BX,SI,R15,DI,R8,R9)
MOVQ DX, 0(AX)
MOVQ CX, 8(AX)
MOVQ BX, 16(AX)
MOVQ SI, 24(AX)
RET
// MulBy13(x *Element)
TEXT ·MulBy13(SB), NOSPLIT, $0-8
MOVQ x+0(FP), AX
MOVQ 0(AX), DX
MOVQ 8(AX), CX
MOVQ 16(AX), BX
MOVQ 24(AX), SI
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (R11,R12,R13,R14)
REDUCE(DX,CX,BX,SI,R11,R12,R13,R14)
MOVQ DX, R11
MOVQ CX, R12
MOVQ BX, R13
MOVQ SI, R14
ADDQ DX, DX
ADCQ CX, CX
ADCQ BX, BX
ADCQ SI, SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
ADDQ R11, DX
ADCQ R12, CX
ADCQ R13, BX
ADCQ R14, SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
ADDQ 0(AX), DX
ADCQ 8(AX), CX
ADCQ 16(AX), BX
ADCQ 24(AX), SI
// reduce element(DX,CX,BX,SI) using temp registers (DI,R8,R9,R10)
REDUCE(DX,CX,BX,SI,DI,R8,R9,R10)
MOVQ DX, 0(AX)
MOVQ CX, 8(AX)
MOVQ BX, 16(AX)
MOVQ SI, 24(AX)
RET
// Butterfly(a, b *Element) sets a = a + b; b = a - b
TEXT ·Butterfly(SB), NOSPLIT, $0-16
MOVQ a+0(FP), AX
MOVQ 0(AX), CX
MOVQ 8(AX), BX
MOVQ 16(AX), SI
MOVQ 24(AX), DI
MOVQ CX, R8
MOVQ BX, R9
MOVQ SI, R10
MOVQ DI, R11
XORQ AX, AX
MOVQ b+8(FP), DX
ADDQ 0(DX), CX
ADCQ 8(DX), BX
ADCQ 16(DX), SI
ADCQ 24(DX), DI
SUBQ 0(DX), R8
SBBQ 8(DX), R9
SBBQ 16(DX), R10
SBBQ 24(DX), R11
MOVQ $0x43e1f593f0000001, R12
MOVQ $0x2833e84879b97091, R13
MOVQ $0xb85045b68181585d, R14
MOVQ $0x30644e72e131a029, R15
CMOVQCC AX, R12
CMOVQCC AX, R13
CMOVQCC AX, R14
CMOVQCC AX, R15
ADDQ R12, R8
ADCQ R13, R9
ADCQ R14, R10
ADCQ R15, R11
MOVQ R8, 0(DX)
MOVQ R9, 8(DX)
MOVQ R10, 16(DX)
MOVQ R11, 24(DX)
// reduce element(CX,BX,SI,DI) using temp registers (R8,R9,R10,R11)
REDUCE(CX,BX,SI,DI,R8,R9,R10,R11)
MOVQ a+0(FP), AX
MOVQ CX, 0(AX)
MOVQ BX, 8(AX)
MOVQ SI, 16(AX)
MOVQ DI, 24(AX)
RET

78
ff/element_ops_noasm.go Normal file
View File

@@ -0,0 +1,78 @@
//go:build !amd64
// +build !amd64
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ff
// /!\ WARNING /!\
// this code has not been audited and is provided as-is. In particular,
// there is no security guarantees such as constant time implementation
// or side-channel attack resistance
// /!\ WARNING /!\
// MulBy3 x *= 3
func MulBy3(x *Element) {
mulByConstant(x, 3)
}
// MulBy5 x *= 5
func MulBy5(x *Element) {
mulByConstant(x, 5)
}
// MulBy13 x *= 13
func MulBy13(x *Element) {
mulByConstant(x, 13)
}
// Butterfly sets
// a = a + b
// b = a - b
func Butterfly(a, b *Element) {
_butterflyGeneric(a, b)
}
func mul(z, x, y *Element) {
_mulGeneric(z, x, y)
}
// FromMont converts z in place (i.e. mutates) from Montgomery to regular representation
// sets and returns z = z * 1
func fromMont(z *Element) {
_fromMontGeneric(z)
}
func add(z, x, y *Element) {
_addGeneric(z, x, y)
}
func double(z, x *Element) {
_doubleGeneric(z, x)
}
func sub(z, x, y *Element) {
_subGeneric(z, x, y)
}
func neg(z, x *Element) {
_negGeneric(z, x)
}
func reduce(z *Element) {
_reduceGeneric(z)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +0,0 @@
package ff
// NewElement returns a new empty *Element
func NewElement() *Element {
return &Element{}
}

30
ffg/arith.go Normal file
View File

@@ -0,0 +1,30 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg
import (
"math/bits"
)
// madd0 hi = a*b + c (discards lo bits)
func madd0(a, b, c uint64) (hi uint64) {
var carry, lo uint64
hi, lo = bits.Mul64(a, b)
_, carry = bits.Add64(lo, c, 0)
hi, _ = bits.Add64(hi, 0, carry)
return
}

24
ffg/asm.go Normal file
View File

@@ -0,0 +1,24 @@
//go:build !noadx
// +build !noadx
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg
import "golang.org/x/sys/cpu"
var supportAdx = cpu.X86.HasADX && cpu.X86.HasBMI2

25
ffg/asm_noadx.go Normal file
View File

@@ -0,0 +1,25 @@
//go:build noadx
// +build noadx
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg
// note: this is needed for test purposes, as dynamically changing supportAdx doesn't flag
// certain errors (like fatal error: missing stackmap)
// this ensures we test all asm path.
var supportAdx = false

43
ffg/doc.go Normal file
View File

@@ -0,0 +1,43 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
// Package ffg contains field arithmetic operations for modulus = 0xffffff...000001.
//
// The API is similar to math/big (big.Int), but the operations are significantly faster (up to 20x for the modular multiplication on amd64, see also https://hackmd.io/@zkteam/modular_multiplication)
//
// The modulus is hardcoded in all the operations.
//
// Field elements are represented as an array, and assumed to be in Montgomery form in all methods:
// type Element [1]uint64
//
// Example API signature
// // Mul z = x * y mod q
// func (z *Element) Mul(x, y *Element) *Element
//
// and can be used like so:
// var a, b Element
// a.SetUint64(2)
// b.SetString("984896738")
// a.Mul(a, b)
// a.Sub(a, a)
// .Add(a, b)
// .Inv(a)
// b.Exp(b, new(big.Int).SetUint64(42))
//
// Modulus
// 0xffffffff00000001 // base 16
// 18446744069414584321 // base 10
package ffg

759
ffg/element.go Normal file
View File

@@ -0,0 +1,759 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg
// /!\ WARNING /!\
// this code has not been audited and is provided as-is. In particular,
// there is no security guarantees such as constant time implementation
// or side-channel attack resistance
// /!\ WARNING /!\
import (
"crypto/rand"
"encoding/binary"
"errors"
"io"
"math/big"
"math/bits"
"reflect"
"strconv"
"sync"
)
// Element represents a field element stored on 1 words (uint64)
// Element are assumed to be in Montgomery form in all methods
// field modulus q =
//
// 18446744069414584321
type Element [1]uint64
// Limbs number of 64 bits words needed to represent Element
const Limbs = 1
// Bits number bits needed to represent Element
const Bits = 64
// Bytes number bytes needed to represent Element
const Bytes = Limbs * 8
// field modulus stored as big.Int
var _modulus big.Int
// Modulus returns q as a big.Int
// q =
//
// 18446744069414584321
func Modulus() *big.Int {
return new(big.Int).Set(&_modulus)
}
// q (modulus)
var qElement = Element{
18446744069414584321,
}
// rSquare
var rSquare = Element{
18446744065119617025,
}
var bigIntPool = sync.Pool{
New: func() interface{} {
return new(big.Int)
},
}
func init() {
_modulus.SetString("18446744069414584321", 10)
}
// NewElement returns a new Element
func NewElement() *Element {
return &Element{}
}
// NewElementFromUint64 returns a new Element from a uint64 value
//
// it is equivalent to
// var v NewElement
// v.SetUint64(...)
func NewElementFromUint64(v uint64) *Element {
z := Element{v}
z.Mul(&z, &rSquare)
return &z
}
// SetUint64 z = v, sets z LSB to v (non-Montgomery form) and convert z to Montgomery form
func (z *Element) SetUint64(v uint64) *Element {
*z = Element{v}
return z.Mul(z, &rSquare) // z.ToMont()
}
// Set z = x
func (z *Element) Set(x *Element) *Element {
z[0] = x[0]
return z
}
// SetInterface converts provided interface into Element
// returns an error if provided type is not supported
// supported types: Element, *Element, uint64, int, string (interpreted as base10 integer),
// *big.Int, big.Int, []byte
func (z *Element) SetInterface(i1 interface{}) (*Element, error) {
switch c1 := i1.(type) {
case Element:
return z.Set(&c1), nil
case *Element:
return z.Set(c1), nil
case uint64:
return z.SetUint64(c1), nil
case int:
return z.SetString(strconv.Itoa(c1)), nil
case string:
return z.SetString(c1), nil
case *big.Int:
return z.SetBigInt(c1), nil
case big.Int:
return z.SetBigInt(&c1), nil
case []byte:
return z.SetBytes(c1), nil
default:
return nil, errors.New("can't set ffg.Element from type " + reflect.TypeOf(i1).String())
}
}
// SetZero z = 0
func (z *Element) SetZero() *Element {
z[0] = 0
return z
}
// SetOne z = 1 (in Montgomery form)
func (z *Element) SetOne() *Element {
z[0] = 4294967295
return z
}
// Div z = x*y^-1 mod q
func (z *Element) Div(x, y *Element) *Element {
var yInv Element
yInv.Inverse(y)
z.Mul(x, &yInv)
return z
}
// Bit returns the i'th bit, with lsb == bit 0.
// It is the responsability of the caller to convert from Montgomery to Regular form if needed
func (z *Element) Bit(i uint64) uint64 {
j := i / 64
if j >= 1 {
return 0
}
return uint64(z[j] >> (i % 64) & 1)
}
// Equal returns z == x
func (z *Element) Equal(x *Element) bool {
return (z[0] == x[0])
}
// IsZero returns z == 0
func (z *Element) IsZero() bool {
return (z[0]) == 0
}
// IsUint64 returns true if z[0] >= 0 and all other words are 0
func (z *Element) IsUint64() bool {
return true
}
// Cmp compares (lexicographic order) z and x and returns:
//
// -1 if z < x
// 0 if z == x
// +1 if z > x
//
func (z *Element) Cmp(x *Element) int {
_z := *z
_x := *x
_z.FromMont()
_x.FromMont()
if _z[0] > _x[0] {
return 1
} else if _z[0] < _x[0] {
return -1
}
return 0
}
// LexicographicallyLargest returns true if this element is strictly lexicographically
// larger than its negation, false otherwise
func (z *Element) LexicographicallyLargest() bool {
// adapted from github.com/zkcrypto/bls12_381
// we check if the element is larger than (q-1) / 2
// if z - (((q -1) / 2) + 1) have no underflow, then z > (q-1) / 2
_z := *z
_z.FromMont()
var b uint64
_, b = bits.Sub64(_z[0], 9223372034707292161, 0)
return b == 0
}
// SetRandom sets z to a random element < q
func (z *Element) SetRandom() (*Element, error) {
var bytes [8]byte
if _, err := io.ReadFull(rand.Reader, bytes[:]); err != nil {
return nil, err
}
z[0] = binary.BigEndian.Uint64(bytes[0:8])
z[0] %= 18446744069414584321
// if z > q --> z -= q
// note: this is NOT constant time
if !(z[0] < 18446744069414584321) {
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
}
return z, nil
}
// One returns 1 (in montgommery form)
func One() Element {
var one Element
one.SetOne()
return one
}
// Halve sets z to z / 2 (mod p)
func (z *Element) Halve() {
var twoInv Element
twoInv.SetOne().Double(&twoInv).Inverse(&twoInv)
z.Mul(z, &twoInv)
}
// API with assembly impl
// Mul z = x * y mod q
// see https://hackmd.io/@zkteam/modular_multiplication
func (z *Element) Mul(x, y *Element) *Element {
mul(z, x, y)
return z
}
// Square z = x * x mod q
// see https://hackmd.io/@zkteam/modular_multiplication
func (z *Element) Square(x *Element) *Element {
mul(z, x, x)
return z
}
// FromMont converts z in place (i.e. mutates) from Montgomery to regular representation
// sets and returns z = z * 1
func (z *Element) FromMont() *Element {
fromMont(z)
return z
}
// Add z = x + y mod q
func (z *Element) Add(x, y *Element) *Element {
add(z, x, y)
return z
}
// Double z = x + x mod q, aka Lsh 1
func (z *Element) Double(x *Element) *Element {
double(z, x)
return z
}
// Sub z = x - y mod q
func (z *Element) Sub(x, y *Element) *Element {
sub(z, x, y)
return z
}
// Neg z = q - x
func (z *Element) Neg(x *Element) *Element {
neg(z, x)
return z
}
// Generic (no ADX instructions, no AMD64) versions of multiplication and squaring algorithms
func _mulGeneric(z, x, y *Element) {
var t [2]uint64
var D uint64
var m, C uint64
// -----------------------------------
// First loop
C, t[0] = bits.Mul64(y[0], x[0])
t[1], D = bits.Add64(t[1], C, 0)
// m = t[0]n'[0] mod W
m = t[0] * 18446744069414584319
// -----------------------------------
// Second loop
C = madd0(m, 18446744069414584321, t[0])
t[0], C = bits.Add64(t[1], C, 0)
t[1], _ = bits.Add64(0, D, C)
if t[1] != 0 {
// we need to reduce, we have a result on 2 words
z[0], _ = bits.Sub64(t[0], 18446744069414584321, 0)
return
}
// copy t into z
z[0] = t[0]
// if z > q --> z -= q
// note: this is NOT constant time
if !(z[0] < 18446744069414584321) {
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
}
}
func _fromMontGeneric(z *Element) {
// the following lines implement z = z * 1
// with a modified CIOS montgomery multiplication
{
// m = z[0]n'[0] mod W
m := z[0] * 18446744069414584319
C := madd0(m, 18446744069414584321, z[0])
z[0] = C
}
// if z > q --> z -= q
// note: this is NOT constant time
if !(z[0] < 18446744069414584321) {
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
}
}
func _addGeneric(z, x, y *Element) {
var carry uint64
z[0], carry = bits.Add64(x[0], y[0], 0)
// if we overflowed the last addition, z >= q
// if z >= q, z = z - q
if carry != 0 {
// we overflowed, so z >= q
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
return
}
// if z > q --> z -= q
// note: this is NOT constant time
if !(z[0] < 18446744069414584321) {
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
}
}
func _doubleGeneric(z, x *Element) {
var carry uint64
z[0], carry = bits.Add64(x[0], x[0], 0)
// if we overflowed the last addition, z >= q
// if z >= q, z = z - q
if carry != 0 {
// we overflowed, so z >= q
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
return
}
// if z > q --> z -= q
// note: this is NOT constant time
if !(z[0] < 18446744069414584321) {
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
}
}
func _subGeneric(z, x, y *Element) {
var b uint64
z[0], b = bits.Sub64(x[0], y[0], 0)
if b != 0 {
z[0], _ = bits.Add64(z[0], 18446744069414584321, 0)
}
}
func _negGeneric(z, x *Element) {
if x.IsZero() {
z.SetZero()
return
}
z[0], _ = bits.Sub64(18446744069414584321, x[0], 0)
}
func _reduceGeneric(z *Element) {
// if z > q --> z -= q
// note: this is NOT constant time
if !(z[0] < 18446744069414584321) {
z[0], _ = bits.Sub64(z[0], 18446744069414584321, 0)
}
}
func mulByConstant(z *Element, c uint8) {
switch c {
case 0:
z.SetZero()
return
case 1:
return
case 2:
z.Double(z)
return
case 3:
_z := *z
z.Double(z).Add(z, &_z)
case 5:
_z := *z
z.Double(z).Double(z).Add(z, &_z)
default:
var y Element
y.SetUint64(uint64(c))
z.Mul(z, &y)
}
}
// BatchInvert returns a new slice with every element inverted.
// Uses Montgomery batch inversion trick
func BatchInvert(a []Element) []Element {
res := make([]Element, len(a))
if len(a) == 0 {
return res
}
zeroes := make([]bool, len(a))
accumulator := One()
for i := 0; i < len(a); i++ {
if a[i].IsZero() {
zeroes[i] = true
continue
}
res[i] = accumulator
accumulator.Mul(&accumulator, &a[i])
}
accumulator.Inverse(&accumulator)
for i := len(a) - 1; i >= 0; i-- {
if zeroes[i] {
continue
}
res[i].Mul(&res[i], &accumulator)
accumulator.Mul(&accumulator, &a[i])
}
return res
}
func _butterflyGeneric(a, b *Element) {
t := *a
a.Add(a, b)
b.Sub(&t, b)
}
// BitLen returns the minimum number of bits needed to represent z
// returns 0 if z == 0
func (z *Element) BitLen() int {
return bits.Len64(z[0])
}
// Exp z = x^exponent mod q
func (z *Element) Exp(x Element, exponent *big.Int) *Element {
var bZero big.Int
if exponent.Cmp(&bZero) == 0 {
return z.SetOne()
}
z.Set(&x)
for i := exponent.BitLen() - 2; i >= 0; i-- {
z.Square(z)
if exponent.Bit(i) == 1 {
z.Mul(z, &x)
}
}
return z
}
// ToMont converts z to Montgomery form
// sets and returns z = z * r^2
func (z *Element) ToMont() *Element {
return z.Mul(z, &rSquare)
}
// ToRegular returns z in regular form (doesn't mutate z)
func (z Element) ToRegular() Element {
return *z.FromMont()
}
// String returns the string form of an Element in Montgomery form
func (z *Element) String() string {
zz := *z
zz.FromMont()
if zz.IsUint64() {
return strconv.FormatUint(zz[0], 10)
} else {
var zzNeg Element
zzNeg.Neg(z)
zzNeg.FromMont()
if zzNeg.IsUint64() {
return "-" + strconv.FormatUint(zzNeg[0], 10)
}
}
vv := bigIntPool.Get().(*big.Int)
defer bigIntPool.Put(vv)
return zz.ToBigInt(vv).String()
}
// ToBigInt returns z as a big.Int in Montgomery form
func (z *Element) ToBigInt(res *big.Int) *big.Int {
var b [Limbs * 8]byte
binary.BigEndian.PutUint64(b[0:8], z[0])
return res.SetBytes(b[:])
}
// ToBigIntRegular returns z as a big.Int in regular form
func (z Element) ToBigIntRegular(res *big.Int) *big.Int {
z.FromMont()
return z.ToBigInt(res)
}
// ToUint64Regular returns z as a uint64 in regular form
func (z Element) ToUint64Regular() uint64 {
z.FromMont()
return z[0]
}
// Bytes returns the regular (non montgomery) value
// of z as a big-endian byte array.
func (z *Element) Bytes() (res [Limbs * 8]byte) {
_z := z.ToRegular()
binary.BigEndian.PutUint64(res[0:8], _z[0])
return
}
// Marshal returns the regular (non montgomery) value
// of z as a big-endian byte slice.
func (z *Element) Marshal() []byte {
b := z.Bytes()
return b[:]
}
// SetBytes interprets e as the bytes of a big-endian unsigned integer,
// sets z to that value (in Montgomery form), and returns z.
func (z *Element) SetBytes(e []byte) *Element {
// get a big int from our pool
vv := bigIntPool.Get().(*big.Int)
vv.SetBytes(e)
// set big int
z.SetBigInt(vv)
// put temporary object back in pool
bigIntPool.Put(vv)
return z
}
// SetBigInt sets z to v (regular form) and returns z in Montgomery form
func (z *Element) SetBigInt(v *big.Int) *Element {
z.SetZero()
var zero big.Int
// fast path
c := v.Cmp(&_modulus)
if c == 0 {
// v == 0
return z
} else if c != 1 && v.Cmp(&zero) != -1 {
// 0 < v < q
return z.setBigInt(v)
}
// get temporary big int from the pool
vv := bigIntPool.Get().(*big.Int)
// copy input + modular reduction
vv.Set(v)
vv.Mod(v, &_modulus)
// set big int byte value
z.setBigInt(vv)
// release object into pool
bigIntPool.Put(vv)
return z
}
// setBigInt assumes 0 <= v < q
func (z *Element) setBigInt(v *big.Int) *Element {
vBits := v.Bits()
if bits.UintSize == 64 {
for i := 0; i < len(vBits); i++ {
z[i] = uint64(vBits[i])
}
} else {
for i := 0; i < len(vBits); i++ {
if i%2 == 0 {
z[i/2] = uint64(vBits[i])
} else {
z[i/2] |= uint64(vBits[i]) << 32
}
}
}
return z.ToMont()
}
// SetString creates a big.Int with s (in base 10) and calls SetBigInt on z
func (z *Element) SetString(s string) *Element {
// get temporary big int from the pool
vv := bigIntPool.Get().(*big.Int)
if _, ok := vv.SetString(s, 10); !ok {
panic("Element.SetString failed -> can't parse number in base10 into a big.Int")
}
z.SetBigInt(vv)
// release object into pool
bigIntPool.Put(vv)
return z
}
var (
_bLegendreExponentElement *big.Int
_bSqrtExponentElement *big.Int
)
func init() {
_bLegendreExponentElement, _ = new(big.Int).SetString("7fffffff80000000", 16)
const sqrtExponentElement = "7fffffff"
_bSqrtExponentElement, _ = new(big.Int).SetString(sqrtExponentElement, 16)
}
// Legendre returns the Legendre symbol of z (either +1, -1, or 0.)
func (z *Element) Legendre() int {
var l Element
// z^((q-1)/2)
l.Exp(*z, _bLegendreExponentElement)
if l.IsZero() {
return 0
}
// if l == 1
if l[0] == 4294967295 {
return 1
}
return -1
}
// Sqrt z = √x mod q
// if the square root doesn't exist (x is not a square mod q)
// Sqrt leaves z unchanged and returns nil
func (z *Element) Sqrt(x *Element) *Element {
// q ≡ 1 (mod 4)
// see modSqrtTonelliShanks in math/big/int.go
// using https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
var y, b, t, w Element
// w = x^((s-1)/2))
w.Exp(*x, _bSqrtExponentElement)
// y = x^((s+1)/2)) = w * x
y.Mul(x, &w)
// b = x^s = w * w * x = y * x
b.Mul(&w, &y)
// g = nonResidue ^ s
var g = Element{
15733474329512464024,
}
r := uint64(32)
// compute legendre symbol
// t = x^((q-1)/2) = r-1 squaring of x^s
t = b
for i := uint64(0); i < r-1; i++ {
t.Square(&t)
}
if t.IsZero() {
return z.SetZero()
}
if !(t[0] == 4294967295) {
// t != 1, we don't have a square root
return nil
}
for {
var m uint64
t = b
// for t != 1
for !(t[0] == 4294967295) {
t.Square(&t)
m++
}
if m == 0 {
return z.Set(&y)
}
// t = g^(2^(r-m-1)) mod q
ge := int(r - m - 1)
t = g
for ge > 0 {
t.Square(&t)
ge--
}
g.Square(&t)
y.Mul(&y, &t)
b.Mul(&b, &g)
r = m
}
}
// Inverse z = x^-1 mod q
// note: allocates a big.Int (math/big)
func (z *Element) Inverse(x *Element) *Element {
var _xNonMont big.Int
x.ToBigIntRegular(&_xNonMont)
_xNonMont.ModInverse(&_xNonMont, Modulus())
z.SetBigInt(&_xNonMont)
return z
}

113
ffg/element_fuzz.go Normal file
View File

@@ -0,0 +1,113 @@
//go:build gofuzz
// +build gofuzz
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg
import (
"bytes"
"encoding/binary"
"io"
"math/big"
"math/bits"
)
const (
fuzzInteresting = 1
fuzzNormal = 0
fuzzDiscard = -1
)
// Fuzz arithmetic operations fuzzer
func Fuzz(data []byte) int {
r := bytes.NewReader(data)
var e1, e2 Element
e1.SetRawBytes(r)
e2.SetRawBytes(r)
{
// mul assembly
var c, _c Element
a, _a, b, _b := e1, e1, e2, e2
c.Mul(&a, &b)
_mulGeneric(&_c, &_a, &_b)
if !c.Equal(&_c) {
panic("mul asm != mul generic on Element")
}
}
{
// inverse
inv := e1
inv.Inverse(&inv)
var bInv, b1, b2 big.Int
e1.ToBigIntRegular(&b1)
bInv.ModInverse(&b1, Modulus())
inv.ToBigIntRegular(&b2)
if b2.Cmp(&bInv) != 0 {
panic("inverse operation doesn't match big int result")
}
}
{
// a + -a == 0
a, b := e1, e1
b.Neg(&b)
a.Add(&a, &b)
if !a.IsZero() {
panic("a + -a != 0")
}
}
return fuzzNormal
}
// SetRawBytes reads up to Bytes (bytes needed to represent Element) from reader
// and interpret it as big endian uint64
// used for fuzzing purposes only
func (z *Element) SetRawBytes(r io.Reader) {
buf := make([]byte, 8)
for i := 0; i < len(z); i++ {
if _, err := io.ReadFull(r, buf); err != nil {
goto eof
}
z[i] = binary.BigEndian.Uint64(buf[:])
}
eof:
z[0] %= qElement[0]
if z.BiggerModulus() {
var b uint64
z[0], b = bits.Sub64(z[0], qElement[0], 0)
}
return
}
func (z *Element) BiggerModulus() bool {
return z[0] >= qElement[0]
}

17
ffg/element_ops_amd64.go Normal file
View File

@@ -0,0 +1,17 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg

75
ffg/element_ops_noasm.go Normal file
View File

@@ -0,0 +1,75 @@
// Copyright 2020 ConsenSys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package ffg
// /!\ WARNING /!\
// this code has not been audited and is provided as-is. In particular,
// there is no security guarantees such as constant time implementation
// or side-channel attack resistance
// /!\ WARNING /!\
// MulBy3 x *= 3
func MulBy3(x *Element) {
mulByConstant(x, 3)
}
// MulBy5 x *= 5
func MulBy5(x *Element) {
mulByConstant(x, 5)
}
// MulBy13 x *= 13
func MulBy13(x *Element) {
mulByConstant(x, 13)
}
// Butterfly sets
// a = a + b
// b = a - b
func Butterfly(a, b *Element) {
_butterflyGeneric(a, b)
}
func mul(z, x, y *Element) {
_mulGeneric(z, x, y)
}
// FromMont converts z in place (i.e. mutates) from Montgomery to regular representation
// sets and returns z = z * 1
func fromMont(z *Element) {
_fromMontGeneric(z)
}
func add(z, x, y *Element) {
_addGeneric(z, x, y)
}
func double(z, x *Element) {
_doubleGeneric(z, x)
}
func sub(z, x, y *Element) {
_subGeneric(z, x, y)
}
func neg(z, x *Element) {
_negGeneric(z, x)
}
func reduce(z *Element) {
_reduceGeneric(z)
}

1833
ffg/element_test.go Normal file

File diff suppressed because it is too large Load Diff

16
go.mod
View File

@@ -1,11 +1,17 @@
module github.com/iden3/go-iden3-crypto
go 1.12
go 1.18
require (
github.com/dchest/blake512 v1.0.0
github.com/ethereum/go-ethereum v1.9.12
github.com/stretchr/testify v1.4.0
golang.org/x/crypto v0.0.0-20200311171314-f7b00557c8c4
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd // indirect
github.com/leanovate/gopter v0.2.9
github.com/stretchr/testify v1.8.2
golang.org/x/crypto v0.7.0
golang.org/x/sys v0.6.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

180
go.sum
View File

@@ -1,173 +1,25 @@
github.com/Azure/azure-pipeline-go v0.2.1/go.mod h1:UGSo8XybXnIGZ3epmeBw7Jdz+HiUVpqIlpz/HKHylF4=
github.com/Azure/azure-pipeline-go v0.2.2/go.mod h1:4rQ/NZncSvGqNkkOsNpOU1tgoNuIlp9AfUH5G1tvCHc=
github.com/Azure/azure-storage-blob-go v0.7.0/go.mod h1:f9YQKtsG1nMisotuTPpO0tjNuEjKRYAcJU8/ydDI++4=
github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI=
github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0=
github.com/Azure/go-autorest/autorest/adal v0.8.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc=
github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA=
github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g=
github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0=
github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0=
github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM=
github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc=
github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/OneOfOne/xxhash v1.2.5/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 h1:fLjPD/aNc3UIOA6tDi6QXUemppXK3P9BI7mr2hd6gx8=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/VictoriaMetrics/fastcache v1.5.3 h1:2odJnXLbFZcoV9KYtQ+7TH1UOq3dn3AssMgieaezkR4=
github.com/VictoriaMetrics/fastcache v1.5.3/go.mod h1:+jv9Ckb+za/P1ZRg/sulP5Ni1v49daAVERr0H3CuscE=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM=
github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847 h1:rtI0fD4oG/8eVokGVPYJEW1F88p1ZNgXiEIs9thEE4A=
github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847/go.mod h1:D/tb0zPVXnP7fmsLZjtdUhSsumbK/ij54UXjjVgMGxQ=
github.com/aws/aws-sdk-go v1.25.48/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6 h1:Eey/GGQ/E5Xp1P2Lyx1qj007hLZfbi0+CoVeJruGCtI=
github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6/go.mod h1:Dmm/EzmjnCiweXmzRIAiUWCInVmPgjkzgv5k4tVyXiQ=
github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cespare/xxhash/v2 v2.0.1-0.20190104013014-3767db7a7e18/go.mod h1:HD5P3vAIAh+Y2GAxg0PrPN1P8WkepXGpjbUPDHJqqKM=
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/cloudflare-go v0.10.2-0.20190916151808-a80f83b9add9/go.mod h1:1MxXX1Ux4x6mqPmjkUgTP1CdXIBXKX7T+Jk9Gxrmx+U=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/blake512 v1.0.0 h1:oDFEQFIqFSeuA34xLtXZ/rWxCXdSjirjzPhey5EUvmA=
github.com/dchest/blake512 v1.0.0/go.mod h1:FV1x7xPPLWukZlpDpWQ88rF/SFwZ5qbskrzhLMB92JI=
github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/dop251/goja v0.0.0-20200219165308-d1232e640a87/go.mod h1:Mw6PkjjMXWbTj+nnj4s3QPXq1jaT0s5pC0iFD4+BOAA=
github.com/edsrzf/mmap-go v0.0.0-20160512033002-935e0e8a636c/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/elastic/gosigar v0.8.1-0.20180330100440-37f05ff46ffa h1:XKAhUk/dtp+CV0VO6mhG2V7jA9vbcGcnYF/Ay9NjZrY=
github.com/elastic/gosigar v0.8.1-0.20180330100440-37f05ff46ffa/go.mod h1:cdorVVzy1fhmEqmtgqkoE3bYtCfSCkVyjTyCIo22xvs=
github.com/ethereum/go-ethereum v1.9.12 h1:EPtimwsp/KGDSiXcNunzsI4kefdsMHZGJntKx3fvbaI=
github.com/ethereum/go-ethereum v1.9.12/go.mod h1:PvsVkQmhZFx92Y+h2ylythYlheEDt/uBgFbl61Js/jo=
github.com/fatih/color v1.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-ole/go-ole v1.2.1 h1:2lOsA72HgjxAuMlKpFiCbHTvu44PIVkZ5hqm3RSdI/E=
github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8=
github.com/go-sourcemap/sourcemap v2.1.2+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2-0.20190517061210-b285ee9cfc6c/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/graph-gophers/graphql-go v0.0.0-20191115155744-f33e81362277/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc=
github.com/hashicorp/golang-lru v0.0.0-20160813221303-0a025b7e63ad/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/huin/goupnp v0.0.0-20161224104101-679507af18f3/go.mod h1:MZ2ZmwcBpvOoJ22IJsc7va19ZwoheaBk43rKg12SKag=
github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY=
github.com/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/julienschmidt/httprouter v1.1.1-0.20170430222011-975b5c4c7c21/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/mattn/go-colorable v0.1.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-ieproxy v0.0.0-20190610004146-91bb50d98149/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc=
github.com/mattn/go-ieproxy v0.0.0-20190702010315-6dee0af9227d/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc=
github.com/mattn/go-isatty v0.0.5-0.20180830101745-3fb116b82035/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0=
github.com/naoina/toml v0.1.2-0.20170918210437-9fafd6967416/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
github.com/olekukonko/tablewriter v0.0.2-0.20190409134802-7e037d187b0c/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/pborman/uuid v0.0.0-20170112150404-1b00554d8222/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34=
github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/leanovate/gopter v0.2.9 h1:fQjYxZaynp97ozCzfOyOuAGOU4aU/z37zf/tOujFk7c=
github.com/leanovate/gopter v0.2.9/go.mod h1:U2L/78B+KVFIx2VmW6onHJQzXtFb+p5y3y2Sh+Jxxv8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/tsdb v0.6.2-0.20190402121629-4f204dcbc150/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho=
github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU=
github.com/rs/xhandler v0.0.0-20160618193221-ed27b6fd6521/go.mod h1:RvLn4FgxWubrpZHtQLnOf6EwhN2hEMusxZOhcW9H3UQ=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spaolacci/murmur3 v1.0.1-0.20190317074736-539464a789e9/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4/go.mod h1:RZLeN1LMWmRsyYjvAu+I6Dm9QmlDaIIt+Y+4Kd7Tp+Q=
github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570 h1:gIlAHnH1vJb5vwEjIp5kBj/eu99p/bl0Ay2goiPe5xE=
github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw=
github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 h1:njlZPzLwU639dk2kqnCPPv+wNjq7Xb6EfUxe/oX0/NM=
github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA=
github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208/go.mod h1:IotVbo4F+mw0EzQ08zFqg7pK3FebNXpaMsRy2RT+Ees=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200311171314-f7b00557c8c4 h1:QmwruyY+bKbDDL0BaglrbZABEali68eoMFhTZpCjYVA=
golang.org/x/crypto v0.0.0-20200311171314-f7b00557c8c4/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c=
gopkg.in/olebedev/go-duktape.v3 v3.0.0-20190213234257-ec84240a7772/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

856
goldenposeidon/constants.go Normal file
View File

@@ -0,0 +1,856 @@
package poseidon
import "github.com/iden3/go-iden3-crypto/ffg"
const (
// NROUNDSF const from original paper
NROUNDSF = 8
// NROUNDSP const from original paper
NROUNDSP = 22
// CAPLEN const
CAPLEN = 4
// mLen const
mLen = 12
)
var (
mcirc = []uint64{17, 15, 41, 16, 2, 28, 13, 13, 39, 18, 34, 20}
mdiag = []uint64{8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
c = []uint64{
0xb585f766f2144405,
0x7746a55f43921ad7,
0xb2fb0d31cee799b4,
0xf6760a4803427d7,
0xe10d666650f4e012,
0x8cae14cb07d09bf1,
0xd438539c95f63e9f,
0xef781c7ce35b4c3d,
0xcdc4a239b0c44426,
0x277fa208bf337bff,
0xe17653a29da578a1,
0xc54302f225db2c76,
0xac6c9c2b4418dd61,
0xe0888eb1e8a01286,
0x813dbe952b98904e,
0xcc3033609c9cf175,
0x72cebc82a59c0f82,
0x8150d8525753e741,
0xb1122c74b268d66e,
0x7c6ddd482375aa2,
0xa4dd6f1ef49fb6af,
0xd33b0d5b4f7ccfe5,
0xc523112247209124,
0x464804200134c32d,
0xcd09dea180de4f2c,
0xadb069225c93e4e6,
0xbf01209b8a7c8534,
0xb1eb37d319913823,
0xdadf943b8d3e5a0d,
0x6d15f3cb7a3520ba,
0xf07af62b134ef181,
0x568355076c6b0de6,
0x31ca4bf93cab68b8,
0xfbad37a125735ba,
0x9d3a9caaf1ac9e0a,
0x4f265810f020c095,
0x6a84c9524e81a8bc,
0x68ba410537925c79,
0x422604631b34b07a,
0x28e3a001f62f8290,
0x3adfdccb8f734d41,
0x73503e539baec66a,
0xe8c1fd0142d9849c,
0xe204ac13660546c5,
0x8e2bb3ea97a40c53,
0xac2800d1bf56548c,
0x9494dca005d180d0,
0xf36e1d066383ef53,
0x8aa35b97a0e03c04,
0xcf42a59addbd1f0c,
0xa43ace89f8fdbd79,
0x37585d8c243870c,
0x4ab94ee3e26596fe,
0xcee3abbb50d57b23,
0xac91a7101a5ec55b,
0x9173aa8462280d2d,
0xaec1ca46ccb95105,
0x57b2f2845db61e4a,
0x95704158500c90c6,
0x66e023b0e6c9df5f,
0x315f63f4fec360ba,
0xf3009795713abcf1,
0xf4decc3fb00765ee,
0x32620ac918682d50,
0x49717d63a5fc742e,
0x153516f22014ea2d,
0xcc316380a2761fe4,
0x2e49b3f7076d203d,
0x44ac3e9bf0a2dc89,
0x49d1e388d8e35c,
0x53ec867cb39989fa,
0xd2c9bcc8d65f5a62,
0xc0cc930ee8540455,
0x40651e0872505e8,
0x168973b2ebafbe6c,
0x9c7eecb3b40581c2,
0x389473bcdfca97a2,
0xb1cb0b3abe9753ad,
0x41afceccffdb18e6,
0x7bf841e237ccd6c9,
0x6082a3f101fb888,
0x8c1a39196f4163cc,
0xb56664760c1c9476,
0x2a02ac020d1eb5a3,
0x6a9d48e8aa83605d,
0x8a0d2f5c4c9c51b2,
0x75fc65575b284ad4,
0xadaedf7d1ce2a8dd,
0x235bc889cc83968e,
0xa8c30cf1781738f5,
0x546b2a846753bcf8,
0x9b68e8c06c04bd25,
0x3fdf80794ebb443b,
0x92ca132a9bec5a45,
0x76133eecfd9bd1ff,
0x3fb0fd5381054812,
0xf15925978dbd52ff,
0x2ee289ac37f0e879,
0xd8af8654e9a2e659,
0x8595bbd7f34c5e8a,
0x206ddbf781e47b2,
0xe101a767854a2f97,
0xf4d4f0a01072c996,
0x197aec2894aab642,
0x8d0c3911220db49b,
0xa62a8bad609227ca,
0x1e4813a7e7b9cbce,
0x6b547528731244eb,
0xd08e48512bfea84e,
0xb2920c88d3885857,
0x1f0cd5d7a309fcc2,
0x99a0ea0842fdb4fb,
0xc227210554b6c53d,
0x70e5269708f6f3a9,
0xbe8f71c8c98bb3bd,
0xf96fb39adc4baaf6,
0x7f9a7555c60fc6c7,
0xccaa5446d71fe6a5,
}
p = [][]uint64{
{
0x19,
0x78566230aa7cc5d0,
0xdbf23e50005e7f24,
0xb4a02c5c826d523e,
0x466d8f66a8f9fed5,
0x68da2264f65ec3e,
0xb59f9ff0ac6d5d78,
0xcfb03c902d447551,
0x2044ce14eaf8f5d9,
0xfb9373c8481e0f0d,
0x72af70cdcb99214f,
0xe3ef40eacc6ff78d,
},
{
0xf,
0x817bd8a7869ed1b5,
0x819f2c14a8366b1f,
0x7a5cf5b7b922e946,
0x727eca45c8d7bb71,
0x605a82c52b5ad2f1,
0x59ccc4d5184bc93a,
0x66c8bab2096cfd38,
0xeb4c0ce280c3e935,
0x17f9202c16676b2f,
0x9b6e5164ed35d878,
0x6fadc9347faeee81,
},
{
0x29,
0xd267254bea1097f4,
0x2dc10fce3233f443,
0xfa9db0de2d852e7a,
0xde2a0516f8c9d943,
0xe6fdf23648931b99,
0x3743057c07a5dbfa,
0xa6fdb8ebccc51667,
0x2c4916605e3dea58,
0xe95c10ae32e05085,
0x97f9b7d2cfc2ade5,
0x9b6e5164ed35d878,
},
{
0x10,
0x60c33ebd1e023f0a,
0xdb6945a20d277091,
0x383dd77e07998487,
0xe04ea1957ad8305c,
0xd499fcbf63fbd266,
0x462269e4b04620a5,
0x63c9679d8572a867,
0x81c44e9699915693,
0x62ecbe05e02433fc,
0xe95c10ae32e05085,
0x17f9202c16676b2f,
},
{
0x2,
0xa89ef32ae1462322,
0x77c1a153e73659e8,
0x2aec981be4b62ed5,
0xb70fb5f2b4f1f85f,
0x7c66d474cd2087cb,
0x39302966be7df654,
0xb827c807875511c0,
0xa4daffb3ffd0e78f,
0x81c44e9699915693,
0x2c4916605e3dea58,
0xeb4c0ce280c3e935,
},
{
0x1c,
0x6250f5f176d483e7,
0xaad1255d46e78f07,
0x8a00c7c83c762584,
0xc734f3829ed30b0c,
0xb1a0132288b1619b,
0x88685b4f0798dfd1,
0xfc02e869e21b72f8,
0xb827c807875511c0,
0x63c9679d8572a867,
0xa6fdb8ebccc51667,
0x66c8bab2096cfd38,
},
{
0xd,
0xe16a6c1dee3ba347,
0x13d316e45539aef4,
0x577e0472764f061d,
0x226a4dcf5db3316d,
0x3373035a3ca3dac6,
0x441f3a3747b5adb7,
0x88685b4f0798dfd1,
0x39302966be7df654,
0x462269e4b04620a5,
0x3743057c07a5dbfa,
0x59ccc4d5184bc93a,
},
{
0xd,
0xec9730136b7c2c05,
0xe1ecc5c21eec0646,
0x956d3c8b5528e064,
0x6df1d31fa84398f4,
0xf4898a1a3554ee49,
0x3373035a3ca3dac6,
0xb1a0132288b1619b,
0x7c66d474cd2087cb,
0xd499fcbf63fbd266,
0xe6fdf23648931b99,
0x605a82c52b5ad2f1,
},
{
0x27,
0x3cf7c3a39d94c236,
0x9e62c7d7b000cb0b,
0xe202be7ad7265af6,
0x82178371fa5fff69,
0x6df1d31fa84398f4,
0x226a4dcf5db3316d,
0xc734f3829ed30b0c,
0xb70fb5f2b4f1f85f,
0xe04ea1957ad8305c,
0xde2a0516f8c9d943,
0x727eca45c8d7bb71,
},
{
0x12,
0xb4707207455f57e3,
0x8e1de42b665c6706,
0xee7b04568203481,
0xe202be7ad7265af6,
0x956d3c8b5528e064,
0x577e0472764f061d,
0x8a00c7c83c762584,
0x2aec981be4b62ed5,
0x383dd77e07998487,
0xfa9db0de2d852e7a,
0x7a5cf5b7b922e946,
},
{
0x22,
0xaadb39e83e76a9e0,
0xcd9bf0bd292c5fda,
0x8e1de42b665c6706,
0x9e62c7d7b000cb0b,
0xe1ecc5c21eec0646,
0x13d316e45539aef4,
0xaad1255d46e78f07,
0x77c1a153e73659e8,
0xdb6945a20d277091,
0x2dc10fce3233f443,
0x819f2c14a8366b1f,
},
{
0x14,
0x32f8ae916e567d39,
0xaadb39e83e76a9e0,
0xb4707207455f57e3,
0x3cf7c3a39d94c236,
0xec9730136b7c2c05,
0xe16a6c1dee3ba347,
0x6250f5f176d483e7,
0xa89ef32ae1462322,
0x60c33ebd1e023f0a,
0xd267254bea1097f4,
0x817bd8a7869ed1b5,
},
}
s = []uint64{
0x19,
0x3d999c961b7c63b0,
0x814e82efcd172529,
0x2421e5d236704588,
0x887af7d4dd482328,
0xa5e9c291f6119b27,
0xbdc52b2676a4b4aa,
0x64832009d29bcf57,
0x9c4155174a552cc,
0x463f9ee03d290810,
0xc810936e64982542,
0x43b1c289f7bc3ac,
0x94877900674181c3,
0xc6c67cc37a2a2bbd,
0xd667c2055387940f,
0xba63a63e94b5ff0,
0x99460cc41b8f079f,
0x7ff02375ed524bb3,
0xea0870b47a8caf0e,
0xabcad82633b7bc9d,
0x3b8d135261052241,
0xfb4515f5e5b0d539,
0x3ee8011c2b37f77c,
0x19,
0x673655aae8be5a8b,
0xd510fe714f39fa10,
0x2c68a099b51c9e73,
0xa667bfa9aa96999d,
0x4d67e72f063e2108,
0xf84dde3e6acda179,
0x40f9cc8c08f80981,
0x5ead032050097142,
0x6591b02092d671bb,
0xe18c71963dd1b7,
0x8a21bcd24a14218a,
0xadef3740e71c726,
0xa37bf67c6f986559,
0xc6b16f7ed4fa1b00,
0x6a065da88d8bfc3c,
0x4cabc0916844b46f,
0x407faac0f02e78d1,
0x7a786d9cf0852cf,
0x42433fb6949a629a,
0x891682a147ce43b0,
0x26cfd58e7b003b55,
0x2bbf0ed7b657acb3,
0x19,
0x202800f4addbdc87,
0xe4b5bdb1cc3504ff,
0xbe32b32a825596e7,
0x8e0f68c5dc223b9a,
0x58022d9e1c256ce3,
0x584d29227aa073ac,
0x8b9352ad04bef9e7,
0xaead42a3f445ecbf,
0x3c667a1d833a3cca,
0xda6f61838efa1ffe,
0xe8f749470bd7c446,
0x481ac7746b159c67,
0xe367de32f108e278,
0x73f260087ad28bec,
0x5cfc82216bc1bdca,
0xcaccc870a2663a0e,
0xdb69cd7b4298c45d,
0x7bc9e0c57243e62d,
0x3cc51c5d368693ae,
0x366b4e8cc068895b,
0x2bd18715cdabbca4,
0xa752061c4f33b8cf,
0x19,
0xc5b85bab9e5b3869,
0x45245258aec51cf7,
0x16e6b8e68b931830,
0xe2ae0f051418112c,
0x470e26a0093a65b,
0x6bef71973a8146ed,
0x119265be51812daf,
0xb0be7356254bea2e,
0x8584defff7589bd7,
0x3c5fe4aeb1fb52ba,
0x9e7cd88acf543a5e,
0xb22d2432b72d5098,
0x9e18a487f44d2fe4,
0x4b39e14ce22abd3c,
0x9e77fde2eb315e0d,
0xca5e0385fe67014d,
0xc2cb99bf1b6bddb,
0x99ec1cd2a4460bfe,
0x8577a815a2ff843f,
0x7d80a6b4fd6518a5,
0xeb6c67123eab62cb,
0x8f7851650eca21a5,
0x19,
0x179be4bba87f0a8c,
0xacf63d95d8887355,
0x6696670196b0074f,
0xd99ddf1fe75085f9,
0xc2597881fef0283b,
0xcf48395ee6c54f14,
0x15226a8e4cd8d3b6,
0xc053297389af5d3b,
0x2c08893f0d1580e2,
0xed3cbcff6fcc5ba,
0xc82f510ecf81f6d0,
0x11ba9a1b81718c2a,
0x9f7d798a3323410c,
0xa821855c8c1cf5e5,
0x535e8d6fac0031b2,
0x404e7c751b634320,
0xa729353f6e55d354,
0x4db97d92e58bb831,
0xb53926c27897bf7d,
0x965040d52fe115c5,
0x9565fa41ebd31fd7,
0xaae4438c877ea8f4,
0x19,
0x94b06183acb715cc,
0x500392ed0d431137,
0x861cc95ad5c86323,
0x5830a443f86c4ac,
0x3b68225874a20a7c,
0x10b3309838e236fb,
0x9b77fc8bcd559e2c,
0xbdecf5e0cb9cb213,
0x30276f1221ace5fa,
0x7935dd342764a144,
0xeac6db520bb03708,
0x37f4e36af6073c6e,
0x4edc0918210800e9,
0xc44998e99eae4188,
0x9f4310d05d068338,
0x9ec7fe4350680f29,
0xc5b2c1fdc0b50874,
0xa01920c5ef8b2ebe,
0x59fa6f8bd91d58ba,
0x8bfc9eb89b515a82,
0xbe86a7a2555ae775,
0xcbb8bbaa3810babf,
0x19,
0x7186a80551025f8f,
0x622247557e9b5371,
0xc4cbe326d1ad9742,
0x55f1523ac6a23ea2,
0xa13dfe77a3d52f53,
0xe30750b6301c0452,
0x8bd488070a3a32b,
0xcd800caef5b72ae3,
0x83329c90f04233ce,
0xb5b99e6664a0a3ee,
0x6b0731849e200a7f,
0x577f9a9e7ee3f9c2,
0x88c522b949ace7b1,
0x82f07007c8b72106,
0x8283d37c6675b50e,
0x98b074d9bbac1123,
0x75c56fb7758317c1,
0xfed24e206052bc72,
0x26d7c3d1bc07dae5,
0xf88c5e441e28dbb4,
0x4fe27f9f96615270,
0x514d4ba49c2b14fe,
0x19,
0xec3fabc192b01799,
0x382b38cee8ee5375,
0x3bfb6c3f0e616572,
0x514abd0cf6c7bc86,
0x47521b1361dcc546,
0x178093843f863d14,
0xad1003c5d28918e7,
0x738450e42495bc81,
0xaf947c59af5e4047,
0x4653fb0685084ef2,
0x57fde2062ae35bf,
0xf02a3ac068ee110b,
0xa3630dafb8ae2d7,
0xce0dc874eaf9b55c,
0x9a95f6cff5b55c7e,
0x626d76abfed00c7b,
0xa0c1cf1251c204ad,
0xdaebd3006321052c,
0x3d4bd48b625a8065,
0x7f1e584e071f6ed2,
0x720574f0501caed3,
0xe3260ba93d23540a,
0x19,
0xe376678d843ce55e,
0x66f3860d7514e7fc,
0x7817f3dfff8b4ffa,
0x3929624a9def725b,
0x126ca37f215a80a,
0xfce2f5d02762a303,
0x1bc927375febbad7,
0x85b481e5243f60bf,
0x2d3c5f42a39c91a0,
0x811719919351ae8,
0xf669de0add993131,
0xab1cbd41d8c1e335,
0x9322ed4c0bc2df01,
0x51c3c0983d4284e5,
0x94178e291145c231,
0xfd0f1a973d6b2085,
0xd427ad96e2b39719,
0x8a52437fecaac06b,
0xdc20ee4b8c4c9a80,
0xa2c98e9549da2100,
0x1603fe12613db5b6,
0xe174929433c5505,
0x19,
0x7de38bae084da92d,
0x5b848442237e8a9b,
0xf6c705da84d57310,
0x31e6a4bdb6a49017,
0x889489706e5c5c0f,
0xe4a205459692a1b,
0xbac3fa75ee26f299,
0x5f5894f4057d755e,
0xb0dc3ecd724bb076,
0x5e34d8554a6452ba,
0x4f78fd8c1fdcc5f,
0x3d4eab2b8ef5f796,
0xcfff421583896e22,
0x4143cb32d39ac3d9,
0x22365051b78a5b65,
0x6f7fd010d027c9b6,
0xd9dd36fba77522ab,
0xa44cf1cb33e37165,
0x3fc83d3038c86417,
0xc4588d418e88d270,
0xce1320f10ab80fe2,
0xdb5eadbbec18de5d,
0x19,
0x4dd19c38779512ea,
0xdb79ba02704620e9,
0x92a29a3675a5d2be,
0xd5177029fe495166,
0xd32b3298a13330c1,
0x251c4a3eb2c5f8fd,
0xe1c48b26e0d98825,
0x3301d3362a4ffccb,
0x9bb6c88de8cd178,
0xdc05b676564f538a,
0x60192d883e473fee,
0x1183dfce7c454afd,
0x21cea4aa3d3ed949,
0xfce6f70303f2304,
0x19557d34b55551be,
0x4c56f689afc5bbc9,
0xa1e920844334f944,
0xbad66d423d2ec861,
0xf318c785dc9e0479,
0x99e2032e765ddd81,
0x400ccc9906d66f45,
0xe1197454db2e0dd9,
0x19,
0x16b9774801ac44a0,
0x3cb8411e786d3c8e,
0xa86e9cf505072491,
0x178928152e109ae,
0x5317b905a6e1ab7b,
0xda20b3be7f53d59f,
0xcb97dedecebee9ad,
0x4bd545218c59f58d,
0x77dc8d856c05a44a,
0x87948589e4f243fd,
0x7e5217af969952c2,
0x84d1ecc4d53d2ff1,
0xd8af8b9ceb4e11b6,
0x335856bb527b52f4,
0xc756f17fb59be595,
0xc0654e4ea5553a78,
0x9e9a46b61f2ea942,
0x14fc8b5b3b809127,
0xd7009f0f103be413,
0x3e0ee7b7a9fb4601,
0xa74e888922085ed7,
0xe80a7cde3d4ac526,
0x19,
0xbc58987d06a84e4d,
0xb5d420244c9cae3,
0xa3c4711b938c02c0,
0x3aace640a3e03990,
0x865a0f3249aacd8a,
0x8d00b2a7dbed06c7,
0x6eacb905beb7e2f8,
0x45322b216ec3ec7,
0xeb9de00d594828e6,
0x88c5f20df9e5c26,
0xf555f4112b19781f,
0x238aa6daa612186d,
0x9137a5c630bad4b4,
0xc7db3817870c5eda,
0x217e4f04e5718dc9,
0xcae814e2817bd99d,
0xe3292e7ab770a8ba,
0x7bb36ef70b6b9482,
0x3c7835fb85bca2d3,
0xfe2cdf8ee3c25e86,
0x61b3915ad7274b20,
0xeab75ca7c918e4ef,
0x19,
0xa8cedbff1813d3a7,
0x50dcaee0fd27d164,
0xf1cb02417e23bd82,
0xfaf322786e2abe8b,
0x937a4315beb5d9b6,
0x1b18992921a11d85,
0x7d66c4368b3c497b,
0xe7946317a6b4e99,
0xbe4430134182978b,
0x3771e82493ab262d,
0xa671690d8095ce82,
0xd6e15ffc055e154e,
0xec67881f381a32bf,
0xfbb1196092bf409c,
0xdc9d2e07830ba226,
0x698ef3245ff7988,
0x194fae2974f8b576,
0x7a5d9bea6ca4910e,
0x7aebfea95ccdd1c9,
0xf9bd38a67d5f0e86,
0xfa65539de65492d8,
0xf0dfcbe7653ff787,
0x19,
0xb035585f6e929d9d,
0xba1579c7e219b954,
0xcb201cf846db4ba3,
0x287bf9177372cf45,
0xa350e4f61147d0a6,
0xd5d0ecfb50bcff99,
0x2e166aa6c776ed21,
0xe1e66c991990e282,
0x662b329b01e7bb38,
0x8aa674b36144d9a9,
0xcbabf78f97f95e65,
0xbd87ad390420258,
0xad8617bca9e33c8,
0xc00ad377a1e2666,
0xac6fc58b3f0518f,
0xc0cc8a892cc4173,
0xc210accb117bc21,
0xb73630dbb46ca18,
0xc8be4920cbd4a54,
0xbfe877a21be1690,
0xae790559b0ded81,
0xbf50db2f8d6ce31,
0x19,
0xeec24b15a06b53fe,
0xc8a7aa07c5633533,
0xefe9c6fa4311ad51,
0xb9173f13977109a1,
0x69ce43c9cc94aedc,
0xecf623c9cd118815,
0x28625def198c33c7,
0xccfc5f7de5c3636a,
0xf5e6c40f1621c299,
0xcec0e58c34cb64b1,
0xa868ea113387939f,
0xcf29427ff7c58,
0xbd9b3cf49eec8,
0xd1dc8aa81fb26,
0xbc792d5c394ef,
0xd2ae0b2266453,
0xd413f12c496c1,
0xc84128cfed618,
0xdb5ebd48fc0d4,
0xd1b77326dcb90,
0xbeb0ccc145421,
0xd10e5b22b11d1,
0x19,
0xd8dddbdc5ce4ef45,
0xacfc51de8131458c,
0x146bb3c0fe499ac0,
0x9e65309f15943903,
0x80d0ad980773aa70,
0xf97817d4ddbf0607,
0xe4626620a75ba276,
0xdfdc7fd6fc74f66,
0xf464864ad6f2bb93,
0x2d55e52a5d44414,
0xdd8de62487c40925,
0xe24c99adad8,
0xcf389ed4bc8,
0xe580cbf6966,
0xcde5fd7e04f,
0xe63628041b3,
0xe7e81a87361,
0xdabe78f6d98,
0xefb14cac554,
0xe5574743b10,
0xd05709f42c1,
0xe4690c96af1,
0x19,
0xc15acf44759545a3,
0xcbfdcf39869719d4,
0x33f62042e2f80225,
0x2599c5ead81d8fa3,
0xb306cb6c1d7c8d0,
0x658c80d3df3729b1,
0xe8d1b2b21b41429c,
0xa1b67f09d4b3ccb8,
0xe1adf8b84437180,
0xd593a5e584af47b,
0xa023d94c56e151c7,
0xf7157bc98,
0xe3006d948,
0xfa65811e6,
0xe0d127e2f,
0xfc18bfe53,
0xfd002d901,
0xeed6461d8,
0x1068562754,
0xfa0236f50,
0xe3af13ee1,
0xfa460f6d1,
0x19,
0x49026cc3a4afc5a6,
0xe06dff00ab25b91b,
0xab38c561e8850ff,
0x92c3c8275e105eeb,
0xb65256e546889bd0,
0x3c0468236ea142f6,
0xee61766b889e18f2,
0xa206f41b12c30415,
0x2fe9d756c9f12d1,
0xe9633210630cbf12,
0x1ffea9fe85a0b0b1,
0x11131738,
0xf56d588,
0x11050f86,
0xf848f4f,
0x111527d3,
0x114369a1,
0x106f2f38,
0x11e2ca94,
0x110a29f0,
0xfa9f5c1,
0x10f625d1,
0x19,
0x81d1ae8cc50240f3,
0xf4c77a079a4607d7,
0xed446b2315e3efc1,
0xb0a6b70915178c3,
0xb11ff3e089f15d9a,
0x1d4dba0b7ae9cc18,
0x65d74e2f43b48d05,
0xa2df8c6b8ae0804a,
0xa4e6f0a8c33348a6,
0xc0a26efc7be5669b,
0xa6b6582c547d0d60,
0x11f718,
0x10b6c8,
0x134a96,
0x10cf7f,
0x124d03,
0x13f8a1,
0x117c58,
0x132c94,
0x134fc0,
0x10a091,
0x128961,
0x19,
0x84afc741f1c13213,
0x2f8f43734fc906f3,
0xde682d72da0a02d9,
0xbb005236adb9ef2,
0x5bdf35c10a8b5624,
0x739a8a343950010,
0x52f515f44785cfbc,
0xcbaf4e5d82856c60,
0xac9ea09074e3e150,
0x8f0fa011a2035fb0,
0x1a37905d8450904a,
0x1300,
0x1750,
0x114e,
0x131f,
0x167b,
0x1371,
0x1230,
0x182c,
0x1368,
0xf31,
0x15c9,
0x19,
0x3abeb80def61cc85,
0x9d19c9dd4eac4133,
0x75a652d9641a985,
0x9daf69ae1b67e667,
0x364f71da77920a18,
0x50bd769f745c95b1,
0xf223d1180dbbf3fc,
0x2f885e584e04aa99,
0xb69a0fa70aea684a,
0x9584acaa6e062a0,
0xbc051640145b19b,
0x14,
0x22,
0x12,
0x27,
0xd,
0xd,
0x1c,
0x2,
0x10,
0x29,
0xf,
}
// C is a constant array of element
C []*ffg.Element
// M is a matrix
M [][]*ffg.Element
// P is a matrix
P [][]*ffg.Element
// S is a array of element
S []*ffg.Element
)
func init() {
for i := 0; i < len(c); i++ {
C = append(C, ffg.NewElementFromUint64(c[i]))
}
for i := 0; i < len(s); i++ {
S = append(S, ffg.NewElementFromUint64(s[i]))
}
for i := 0; i < mLen; i++ {
var (
mRow []*ffg.Element
pRow []*ffg.Element
)
for j := 0; j < mLen; j++ {
ele := ffg.NewElementFromUint64(mcirc[(i-j+mLen)%mLen])
if i == j {
ele = ffg.NewElementFromUint64(mcirc[0] + mdiag[i])
}
mRow = append(mRow, ele)
pRow = append(pRow, ffg.NewElementFromUint64(p[i][j]))
}
M = append(M, mRow)
P = append(P, pRow)
}
}

107
goldenposeidon/poseidon.go Normal file
View File

@@ -0,0 +1,107 @@
package poseidon
import (
"math/big"
"github.com/iden3/go-iden3-crypto/ffg"
)
func zero() *ffg.Element {
return ffg.NewElement()
}
var big7 = big.NewInt(7)
// exp7 performs x^7 mod p
func exp7(a *ffg.Element) {
a.Exp(*a, big7)
}
// exp7state perform exp7 for whole state
func exp7state(state []*ffg.Element) {
for i := 0; i < len(state); i++ {
exp7(state[i])
}
}
// ark computes Add-Round Key, from the paper https://eprint.iacr.org/2019/458.pdf
func ark(state []*ffg.Element, it int) {
for i := 0; i < len(state); i++ {
state[i].Add(state[i], C[it+i])
}
}
// mix returns [[matrix]] * [vector]
func mix(state []*ffg.Element, opt bool) []*ffg.Element {
mul := zero()
newState := make([]*ffg.Element, mLen)
for i := 0; i < mLen; i++ {
newState[i] = zero()
}
for i := 0; i < mLen; i++ {
newState[i].SetUint64(0)
for j := 0; j < mLen; j++ {
if opt {
mul.Mul(P[j][i], state[j])
} else {
mul.Mul(M[j][i], state[j])
}
newState[i].Add(newState[i], mul)
}
}
return newState
}
// Hash computes the hash for the given inputs
func Hash(inpBI [NROUNDSF]uint64, capBI [CAPLEN]uint64) ([CAPLEN]uint64, error) {
state := make([]*ffg.Element, mLen)
for i := 0; i < NROUNDSF; i++ {
state[i] = ffg.NewElement().SetUint64(inpBI[i])
}
for i := 0; i < CAPLEN; i++ {
state[i+NROUNDSF] = ffg.NewElement().SetUint64(capBI[i])
}
for i := 0; i < mLen; i++ {
state[i].Add(state[i], C[i])
}
for r := 0; r < NROUNDSF/2; r++ {
exp7state(state)
ark(state, (r+1)*mLen)
state = mix(state, r == NROUNDSF/2-1)
}
for r := 0; r < NROUNDSP; r++ {
exp7(state[0])
state[0].Add(state[0], C[(NROUNDSF/2+1)*mLen+r])
s0 := zero()
mul := zero()
mul.Mul(S[(mLen*2-1)*r], state[0])
s0.Add(s0, mul)
for i := 1; i < mLen; i++ {
mul.Mul(S[(mLen*2-1)*r+i], state[i])
s0.Add(s0, mul)
mul.Mul(S[(mLen*2-1)*r+mLen+i-1], state[0])
state[i].Add(state[i], mul)
}
state[0] = s0
}
for r := 0; r < NROUNDSF/2; r++ {
exp7state(state)
if r < NROUNDSF/2-1 {
ark(state, (NROUNDSF/2+1+r)*mLen+NROUNDSP)
}
state = mix(state, false)
}
return [CAPLEN]uint64{
state[0].ToUint64Regular(),
state[1].ToUint64Regular(),
state[2].ToUint64Regular(),
state[3].ToUint64Regular(),
}, nil
}

View File

@@ -0,0 +1,107 @@
package poseidon
import (
"testing"
"github.com/stretchr/testify/assert"
)
const prime uint64 = 18446744069414584321
func TestPoseidonHashCompare(t *testing.T) {
b0 := uint64(0)
b1 := uint64(1)
bm1 := prime - 1
bM := prime
h, err := Hash([NROUNDSF]uint64{b0, b0, b0, b0, b0, b0, b0, b0},
[CAPLEN]uint64{b0, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t,
[CAPLEN]uint64{
4330397376401421145,
14124799381142128323,
8742572140681234676,
14345658006221440202,
}, h,
)
h, err = Hash([NROUNDSF]uint64{b1, b1, b1, b1, b1, b1, b1, b1},
[CAPLEN]uint64{b1, b1, b1, b1})
assert.Nil(t, err)
assert.Equal(t,
[CAPLEN]uint64{
16428316519797902711,
13351830238340666928,
682362844289978626,
12150588177266359240,
}, h,
)
h, err = Hash([NROUNDSF]uint64{b1, b1, b1, b1, b1, b1, b1, b1},
[CAPLEN]uint64{b1, b1, b1, b1})
assert.Nil(t, err)
assert.Equal(t,
[CAPLEN]uint64{
16428316519797902711,
13351830238340666928,
682362844289978626,
12150588177266359240,
}, h,
)
h, err = Hash(
[NROUNDSF]uint64{bm1, bm1, bm1, bm1, bm1, bm1, bm1, bm1},
[CAPLEN]uint64{bm1, bm1, bm1, bm1},
)
assert.Nil(t, err)
assert.Equal(t,
[CAPLEN]uint64{
13691089994624172887,
15662102337790434313,
14940024623104903507,
10772674582659927682,
}, h,
)
h, err = Hash([NROUNDSF]uint64{bM, bM, bM, bM, bM, bM, bM, bM},
[CAPLEN]uint64{b0, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t,
[CAPLEN]uint64{
4330397376401421145,
14124799381142128323,
8742572140681234676,
14345658006221440202,
}, h,
)
h, err = Hash([NROUNDSF]uint64{
uint64(923978),
uint64(235763497586),
uint64(9827635653498),
uint64(112870),
uint64(289273673480943876),
uint64(230295874986745876),
uint64(6254867324987),
uint64(2087),
}, [CAPLEN]uint64{b0, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t,
[CAPLEN]uint64{
1892171027578617759,
984732815927439256,
7866041765487844082,
8161503938059336191,
}, h,
)
}
func BenchmarkNeptuneHash(b *testing.B) {
inp := [NROUNDSF]uint64{1, 2, 3, 4, 5, 6, 7, 8}
_cap := [CAPLEN]uint64{10, 11, 12, 13}
for i := 0; i < b.N; i++ {
_, _ = Hash(inp, _cap)
}
}

14
keccak256/keccac256.go Normal file
View File

@@ -0,0 +1,14 @@
package keccak256
import (
"golang.org/x/crypto/sha3"
)
// Hash generates a Keccak256 hash from a byte array
func Hash(data ...[]byte) []byte {
hash := sha3.NewLegacyKeccak256()
for _, d := range data {
hash.Write(d) //nolint:errcheck,gosec
}
return hash.Sum(nil)
}

View File

@@ -0,0 +1,21 @@
package keccak256
import (
"encoding/hex"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
)
func TestKeccak256(t *testing.T) {
const SEED = "mimc"
res := Hash([]byte(SEED))
assert.Equal(t,
"b6e489e6b37224a50bebfddbe7d89fa8fdcaa84304a70bd13f79b5d9f7951e9e",
hex.EncodeToString(res))
c := new(big.Int).SetBytes(Hash([]byte(SEED)))
assert.Equal(t,
"82724731331859054037315113496710413141112897654334566532528783843265082629790",
c.String())
}

View File

@@ -4,9 +4,9 @@ import (
"errors"
"math/big"
"github.com/ethereum/go-ethereum/crypto"
_constants "github.com/iden3/go-iden3-crypto/constants"
"github.com/iden3/go-iden3-crypto/ff"
"github.com/iden3/go-iden3-crypto/keccak256"
"github.com/iden3/go-iden3-crypto/utils"
)
@@ -23,24 +23,24 @@ type constantsData struct {
}
func generateConstantsData() constantsData {
var constants constantsData
var consts constantsData
constants.seedHash = new(big.Int).SetBytes(crypto.Keccak256([]byte(SEED)))
c := new(big.Int).SetBytes(crypto.Keccak256([]byte(SEED + "_iv")))
constants.iv = new(big.Int).Mod(c, _constants.Q)
consts.seedHash = new(big.Int).SetBytes(keccak256.Hash([]byte(SEED)))
c := new(big.Int).SetBytes(keccak256.Hash([]byte(SEED + "_iv")))
consts.iv = new(big.Int).Mod(c, _constants.Q)
constants.nRounds = 91
cts := getConstants(SEED, constants.nRounds)
constants.cts = cts
return constants
consts.nRounds = 91
cts := getConstants(SEED, consts.nRounds)
consts.cts = cts
return consts
}
func getConstants(seed string, nRounds int) []*ff.Element {
cts := make([]*ff.Element, nRounds)
cts[0] = ff.NewElement()
c := new(big.Int).SetBytes(crypto.Keccak256([]byte(SEED)))
c := new(big.Int).SetBytes(keccak256.Hash([]byte(seed)))
for i := 1; i < nRounds; i++ {
c = new(big.Int).SetBytes(crypto.Keccak256(c.Bytes()))
c = new(big.Int).SetBytes(keccak256.Hash(c.Bytes()))
n := new(big.Int).Mod(c, _constants.Q)
cts[i] = ff.NewElement().SetBigInt(n)

View File

@@ -5,21 +5,9 @@ import (
"math/big"
"testing"
"github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/assert"
)
func TestKeccak256(t *testing.T) {
res := crypto.Keccak256([]byte(SEED))
assert.Equal(t,
"b6e489e6b37224a50bebfddbe7d89fa8fdcaa84304a70bd13f79b5d9f7951e9e",
hex.EncodeToString(res))
c := new(big.Int).SetBytes(crypto.Keccak256([]byte(SEED)))
assert.Equal(t,
"82724731331859054037315113496710413141112897654334566532528783843265082629790",
c.String())
}
func TestMIMC7Generic(t *testing.T) {
b1 := big.NewInt(int64(1))
b2 := big.NewInt(int64(2))
@@ -36,7 +24,7 @@ func TestMIMC7Generic(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t,
"6464402164086696096195815557694604139393321133243036833927490113253119343397",
(*big.Int)(hg).String())
hg.String())
}
func TestMIMC7(t *testing.T) {
@@ -51,7 +39,7 @@ func TestMIMC7(t *testing.T) {
h1, err := Hash(bigArray1, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h1).Bytes()),
assert.Equal(t, "0x"+hex.EncodeToString(h1.Bytes()),
"0x237c92644dbddb86d8a259e0e923aaab65a93f1ec5758b8799988894ac0958fd")
// h2a, hash of 2 elements
@@ -60,7 +48,7 @@ func TestMIMC7(t *testing.T) {
h2a, err := Hash(bigArray2a, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h2a).Bytes()),
assert.Equal(t, "0x"+hex.EncodeToString(h2a.Bytes()),
"0x067f3202335ea256ae6e6aadcd2d5f7f4b06a00b2d1e0de903980d5ab552dc70")
// h2b, hash of 2 elements
@@ -68,13 +56,13 @@ func TestMIMC7(t *testing.T) {
mh2b := MIMC7Hash(b12, b45)
assert.Nil(t, err)
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(mh2b).Bytes()),
assert.Equal(t, "0x"+hex.EncodeToString(mh2b.Bytes()),
"0x2ba7ebad3c6b6f5a20bdecba2333c63173ca1a5f2f49d958081d9fa7179c44e4")
h2b, err := Hash(bigArray2b, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h2b).Bytes()),
assert.Equal(t, "0x"+hex.EncodeToString(h2b.Bytes()),
"0x15ff7fe9793346a17c3150804bcb36d161c8662b110c50f55ccb7113948d8879")
// h4, hash of 4 elements
@@ -83,7 +71,7 @@ func TestMIMC7(t *testing.T) {
h4, err := Hash(bigArray4, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h4).Bytes()),
assert.Equal(t, "0x"+hex.EncodeToString(h4.Bytes()),
"0x284bc1f34f335933a23a433b6ff3ee179d682cd5e5e2fcdd2d964afa85104beb")
msg := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") //nolint:lll
@@ -101,6 +89,6 @@ func BenchmarkMIMC7(b *testing.B) {
bigArray4 := []*big.Int{b12, b45, b78, b41}
for i := 0; i < b.N; i++ {
Hash(bigArray4, nil) //nolint:errcheck,gosec
_, _ = Hash(bigArray4, nil)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,41 +9,48 @@ import (
"github.com/iden3/go-iden3-crypto/utils"
)
const NROUNDSF = 8 //nolint:golint
// NROUNDSF constant from Poseidon paper
const NROUNDSF = 8
var NROUNDSP = []int{56, 57, 56, 60, 60, 63, 64, 63} //nolint:golint
// NROUNDSP constant from Poseidon paper
var NROUNDSP = []int{56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68}
const spongeChunkSize = 31
const spongeInputs = 16
func zero() *ff.Element {
return ff.NewElement()
}
var big5 = big.NewInt(5)
// exp5 performs x^5 mod p
// https://eprint.iacr.org/2019/458.pdf page 8
func exp5(a *ff.Element) {
a.Exp(*a, big5)
}
// exp5state perform exp5 for whole state
func exp5state(state []*ff.Element) {
for i := 0; i < len(state); i++ {
exp5(state[i])
}
}
// ark computes Add-Round Key, from the paper https://eprint.iacr.org/2019/458.pdf
func ark(state []*ff.Element, c []*ff.Element, it int) {
func ark(state, c []*ff.Element, it int) {
for i := 0; i < len(state); i++ {
state[i].Add(state[i], c[it+i])
}
}
// exp5 performs x^5 mod p
// https://eprint.iacr.org/2019/458.pdf page 8
func exp5(a *ff.Element) {
a.Exp(*a, 5)
}
// sbox https://eprint.iacr.org/2019/458.pdf page 6
func sbox(nRoundsF, nRoundsP int, state []*ff.Element, i int) {
if (i < nRoundsF/2) || (i >= nRoundsF/2+nRoundsP) {
for j := 0; j < len(state); j++ {
exp5(state[j])
}
} else {
exp5(state[0])
}
}
// mix returns [[matrix]] * [vector]
func mix(state []*ff.Element, newState []*ff.Element, m [][]*ff.Element) {
func mix(state []*ff.Element, t int, m [][]*ff.Element) []*ff.Element {
mul := zero()
newState := make([]*ff.Element, t)
for i := 0; i < t; i++ {
newState[i] = zero()
}
for i := 0; i < len(state); i++ {
newState[i].SetUint64(0)
for j := 0; j < len(state); j++ {
@@ -51,41 +58,185 @@ func mix(state []*ff.Element, newState []*ff.Element, m [][]*ff.Element) {
newState[i].Add(newState[i], mul)
}
}
return newState
}
// Hash computes the Poseidon hash for the given inputs
func Hash(inpBI []*big.Int) (*big.Int, error) {
t := len(inpBI) + 1
if len(inpBI) == 0 || len(inpBI) >= len(NROUNDSP)-1 {
return nil, fmt.Errorf("invalid inputs length %d, max %d", len(inpBI), len(NROUNDSP)-1)
if len(inpBI) == 0 || len(inpBI) > len(NROUNDSP) {
return nil, fmt.Errorf("invalid inputs length %d, max %d", len(inpBI), len(NROUNDSP))
}
if !utils.CheckBigIntArrayInField(inpBI[:]) {
if !utils.CheckBigIntArrayInField(inpBI) {
return nil, errors.New("inputs values not inside Finite Field")
}
inp := utils.BigIntArrayToElementArray(inpBI[:])
state := make([]*ff.Element, t)
copy(state[:], inp[:])
state[len(state)-1] = zero()
inp := utils.BigIntArrayToElementArray(inpBI)
nRoundsF := NROUNDSF
nRoundsP := NROUNDSP[t-2]
C := c.c[t-2]
S := c.s[t-2]
M := c.m[t-2]
P := c.p[t-2]
newState := make([]*ff.Element, t)
for i := 0; i < t; i++ {
newState[i] = zero()
state := make([]*ff.Element, t)
state[0] = zero()
copy(state[1:], inp)
ark(state, C, 0)
for i := 0; i < nRoundsF/2-1; i++ {
exp5state(state)
ark(state, C, (i+1)*t)
state = mix(state, t, M)
}
exp5state(state)
ark(state, C, (nRoundsF/2)*t)
state = mix(state, t, P)
// ARK --> SBox --> M, https://eprint.iacr.org/2019/458.pdf pag.5
for i := 0; i < nRoundsF+nRoundsP; i++ {
ark(state, c.c[t-2], i*t)
sbox(nRoundsF, nRoundsP, state, i)
if i < nRoundsF+nRoundsP-1 {
mix(state, newState, c.m[t-2])
state, newState = newState, state
mul := zero()
for i := 0; i < nRoundsP; i++ {
exp5(state[0])
state[0].Add(state[0], C[(nRoundsF/2+1)*t+i])
mul.SetZero()
newState0 := zero()
for j := 0; j < len(state); j++ {
mul.Mul(S[(t*2-1)*i+j], state[j])
newState0.Add(newState0, mul)
}
for k := 1; k < t; k++ {
mul.SetZero()
state[k] = state[k].Add(state[k], mul.Mul(state[0], S[(t*2-1)*i+t+k-1]))
}
state[0] = newState0
}
for i := 0; i < nRoundsF/2-1; i++ {
exp5state(state)
ark(state, C, (nRoundsF/2+1)*t+nRoundsP+i*t)
state = mix(state, t, M)
}
exp5state(state)
state = mix(state, t, M)
rE := state[0]
r := big.NewInt(0)
rE.ToBigIntRegular(r)
return r, nil
}
// HashBytes returns a sponge hash of a msg byte slice split into blocks of 31 bytes
func HashBytes(msg []byte) (*big.Int, error) {
return HashBytesX(msg, spongeInputs)
}
// HashBytesX returns a sponge hash of a msg byte slice split into blocks of 31 bytes
func HashBytesX(msg []byte, frameSize int) (*big.Int, error) {
if frameSize < 2 || frameSize > 16 {
return nil, errors.New("incorrect frame size")
}
// not used inputs default to zero
inputs := make([]*big.Int, frameSize)
for j := 0; j < frameSize; j++ {
inputs[j] = new(big.Int)
}
dirty := false
var hash *big.Int
var err error
k := 0
for i := 0; i < len(msg)/spongeChunkSize; i++ {
dirty = true
inputs[k].SetBytes(msg[spongeChunkSize*i : spongeChunkSize*(i+1)])
if k == frameSize-1 {
hash, err = Hash(inputs)
dirty = false
if err != nil {
return nil, err
}
inputs = make([]*big.Int, frameSize)
inputs[0] = hash
for j := 1; j < frameSize; j++ {
inputs[j] = new(big.Int)
}
k = 1
} else {
k++
}
}
if len(msg)%spongeChunkSize != 0 {
// the last chunk of the message is less than 31 bytes
// zero padding it, so that 0xdeadbeaf becomes
// 0xdeadbeaf000000000000000000000000000000000000000000000000000000
var buf [spongeChunkSize]byte
copy(buf[:], msg[(len(msg)/spongeChunkSize)*spongeChunkSize:])
inputs[k] = new(big.Int).SetBytes(buf[:])
dirty = true
}
if dirty {
// we haven't hashed something in the main sponge loop and need to do hash here
hash, err = Hash(inputs)
if err != nil {
return nil, err
}
}
return hash, nil
}
// SpongeHash returns a sponge hash of inputs (using Poseidon with frame size of 16 inputs)
func SpongeHash(inputs []*big.Int) (*big.Int, error) {
return SpongeHashX(inputs, spongeInputs)
}
// SpongeHashX returns a sponge hash of inputs using Poseidon with configurable frame size
func SpongeHashX(inputs []*big.Int, frameSize int) (*big.Int, error) {
if frameSize < 2 || frameSize > 16 {
return nil, errors.New("incorrect frame size")
}
// not used frame default to zero
frame := make([]*big.Int, frameSize)
for j := 0; j < frameSize; j++ {
frame[j] = new(big.Int)
}
dirty := false
var hash *big.Int
var err error
k := 0
for i := 0; i < len(inputs); i++ {
dirty = true
frame[k] = inputs[i]
if k == frameSize-1 {
hash, err = Hash(frame)
dirty = false
if err != nil {
return nil, err
}
frame = make([]*big.Int, frameSize)
frame[0] = hash
for j := 1; j < frameSize; j++ {
frame[j] = new(big.Int)
}
k = 1
} else {
k++
}
}
if dirty {
// we haven't hashed something in the main sponge loop and need to do hash here
hash, err = Hash(frame)
if err != nil {
return nil, err
}
}
return hash, nil
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,60 @@
package poseidon
import (
"bytes"
"errors"
"hash"
)
type hasher struct {
buf *bytes.Buffer
frameSize int
}
// Sum returns the Poseidon hash of the input bytes.
// use frame size of 16 inputs by default
func Sum(b []byte) []byte {
h, _ := New(16)
h.Write(b)
return h.Sum(nil)
}
// New returns a new hash.Hash computing the Poseidon hash.
func New(frameSize int) (hash.Hash, error) {
if frameSize < 2 || frameSize > 16 {
return nil, errors.New("incorrect frame size")
}
return &hasher{
buf: bytes.NewBuffer([]byte{}),
frameSize: frameSize,
}, nil
}
// Write (via the embedded io.Writer interface) adds more data to the running hash.
func (h *hasher) Write(p []byte) (n int, err error) {
return h.buf.Write(p)
}
// Sum returns the Poseidon digest of the data.
func (h *hasher) Sum(b []byte) []byte {
hahs, err := HashBytesX(h.buf.Bytes(), h.frameSize)
if err != nil {
panic(err)
}
return append(b, hahs.Bytes()...)
}
// Reset resets the Hash to its initial state.
func (h *hasher) Reset() {
h.buf.Reset()
}
// Size returns the number of bytes Sum will return.
func (h *hasher) Size() int {
return 32
}
// BlockSize returns the hash block size.
func (h *hasher) BlockSize() int {
return spongeChunkSize
}

File diff suppressed because one or more lines are too long

View File

@@ -14,7 +14,7 @@ import (
// NewIntFromString creates a new big.Int from a decimal integer encoded as a
// string. It will panic if the string is not a decimal integer.
func NewIntFromString(s string) *big.Int {
v, ok := new(big.Int).SetString(s, 10)
v, ok := new(big.Int).SetString(s, 10) //nolint:gomnd
if !ok {
panic(fmt.Sprintf("Bad base 10 string %s", s))
}
@@ -46,7 +46,7 @@ func SetBigIntFromLEBytes(v *big.Int, leBuf []byte) *big.Int {
return v.SetBytes(beBuf)
}
// Hex is a byte slice type that can be marshalled and unmarshaled in hex
// Hex is a byte slice type that can be marshaled and unmarshaled in hex
type Hex []byte
// MarshalText encodes buf as hex
@@ -72,7 +72,7 @@ func HexDecode(h string) ([]byte, error) {
// HexDecodeInto decodes a hex string into an array of bytes (dst), verifying
// that the decoded array has the same length as dst.
func HexDecodeInto(dst []byte, h []byte) error {
func HexDecodeInto(dst, h []byte) error {
if bytes.HasPrefix(h, []byte("0x")) {
h = h[2:]
}
@@ -105,21 +105,21 @@ func CheckBigIntArrayInField(arr []*big.Int) bool {
// BigIntArrayToElementArray converts an array of *big.Int into an array of *ff.Element
func BigIntArrayToElementArray(bi []*big.Int) []*ff.Element {
var o []*ff.Element
o := make([]*ff.Element, len(bi))
for i := range bi {
o = append(o, ff.NewElement().SetBigInt(bi[i]))
o[i] = ff.NewElement().SetBigInt(bi[i])
}
return o
}
// ElementArrayToBigIntArray converts an array of *ff.Element into an array of *big.Int
func ElementArrayToBigIntArray(e []*ff.Element) []*big.Int {
var o []*big.Int
o := make([]*big.Int, len(e))
for i := range e {
ei := e[i]
bi := big.NewInt(0)
ei.ToBigIntRegular(bi)
o = append(o, bi)
o[i] = bi
}
return o
}