From f7e150a81b3f9d24262f2a2ccc287761bfd82afe Mon Sep 17 00:00:00 2001 From: therealyingtong Date: Fri, 20 Aug 2021 15:43:45 +0800 Subject: [PATCH] Create halo2-gadgets workspace. --- Cargo.toml | 8 +- halo2-gadgets/.gitignore | 4 + halo2-gadgets/Cargo.toml | 12 ++ halo2-gadgets/LICENSE-BOSL | 176 ++++++++++++++++++ halo2-gadgets/halo2_ecc/.gitignore | 4 + halo2-gadgets/halo2_ecc/Cargo.toml | 29 +++ halo2-gadgets/halo2_ecc/LICENSE-BOSL | 176 ++++++++++++++++++ .../halo2_ecc/src}/chip.rs | 38 ++-- .../halo2_ecc/src}/chip/add.rs | 0 .../halo2_ecc/src}/chip/add_incomplete.rs | 0 .../halo2_ecc/src}/chip/mul.rs | 2 +- .../halo2_ecc/src}/chip/mul/complete.rs | 0 .../halo2_ecc/src}/chip/mul/incomplete.rs | 0 .../halo2_ecc/src}/chip/mul/overflow.rs | 13 +- .../halo2_ecc/src}/chip/mul_fixed.rs | 0 .../src}/chip/mul_fixed/base_field_elem.rs | 15 +- .../src}/chip/mul_fixed/full_width.rs | 2 +- .../halo2_ecc/src}/chip/mul_fixed/short.rs | 2 +- .../halo2_ecc/src}/chip/witness_point.rs | 0 .../halo2_ecc/src/gadget.rs | 4 +- halo2-gadgets/halo2_ecc/src/lib.rs | 3 + halo2-gadgets/halo2_poseidon/.gitignore | 4 + halo2-gadgets/halo2_poseidon/Cargo.toml | 29 +++ halo2-gadgets/halo2_poseidon/LICENSE-BOSL | 176 ++++++++++++++++++ .../halo2_poseidon/benches/primitive.rs | 34 ++++ .../halo2_poseidon/src/gadget.rs | 5 +- halo2-gadgets/halo2_poseidon/src/lib.rs | 6 + .../halo2_poseidon/src}/pow5t3.rs | 8 +- .../halo2_poseidon/src/primitive.rs | 3 +- .../halo2_poseidon/src/primitive}/fp.rs | 0 .../halo2_poseidon/src/primitive}/fq.rs | 0 .../halo2_poseidon/src/primitive}/grain.rs | 2 +- .../halo2_poseidon/src/primitive}/mds.rs | 2 +- .../src/primitive}/p128pow5t3.rs | 3 +- .../src/primitive}/test_vectors.rs | 0 halo2-gadgets/halo2_utilities/.gitignore | 4 + halo2-gadgets/halo2_utilities/Cargo.toml | 21 +++ halo2-gadgets/halo2_utilities/LICENSE-BOSL | 176 ++++++++++++++++++ .../halo2_utilities/src}/cond_swap.rs | 18 +- .../src}/decompose_running_sum.rs | 0 halo2-gadgets/halo2_utilities/src/lib.rs | 7 + .../src}/lookup_range_check.rs | 3 +- .../halo2_utilities/src}/utilities.rs | 4 - halo2-gadgets/sinsemilla/.gitignore | 4 + halo2-gadgets/sinsemilla/Cargo.toml | 32 ++++ halo2-gadgets/sinsemilla/LICENSE-BOSL | 176 ++++++++++++++++++ .../sinsemilla/benches/primitive.rs | 21 +-- .../sinsemilla/src}/chip.rs | 7 + .../sinsemilla/src}/chip/generator_table.rs | 2 +- .../sinsemilla/src}/chip/hash_to_point.rs | 8 +- .../sinsemilla/src/gadget.rs | 32 +--- halo2-gadgets/sinsemilla/src/lib.rs | 10 + .../sinsemilla/src}/merkle.rs | 25 ++- .../sinsemilla/src}/merkle/chip.rs | 24 +-- .../sinsemilla/src}/message.rs | 2 +- .../sinsemilla/src/primitive.rs | 3 +- .../sinsemilla/src/primitive}/addition.rs | 0 .../sinsemilla/src/primitive}/sinsemilla_s.rs | 0 src/circuit.rs | 48 +++-- src/circuit/commit_ivk.rs | 16 +- src/circuit/gadget.rs | 7 +- src/circuit/note_commit.rs | 23 +-- src/constants.rs | 2 +- src/constants/fixed_bases.rs | 2 +- src/constants/fixed_bases/commit_ivk_r.rs | 2 +- src/constants/fixed_bases/note_commit_r.rs | 2 +- src/constants/sinsemilla.rs | 4 +- src/note/commitment.rs | 2 +- src/primitives.rs | 2 - src/spec.rs | 11 +- src/tree.rs | 2 +- 71 files changed, 1242 insertions(+), 220 deletions(-) create mode 100644 halo2-gadgets/.gitignore create mode 100644 halo2-gadgets/Cargo.toml create mode 100644 halo2-gadgets/LICENSE-BOSL create mode 100644 halo2-gadgets/halo2_ecc/.gitignore create mode 100644 halo2-gadgets/halo2_ecc/Cargo.toml create mode 100644 halo2-gadgets/halo2_ecc/LICENSE-BOSL rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip.rs (93%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/add.rs (100%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/add_incomplete.rs (100%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul.rs (99%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul/complete.rs (100%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul/incomplete.rs (100%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul/overflow.rs (95%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul_fixed.rs (100%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul_fixed/base_field_elem.rs (98%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul_fixed/full_width.rs (99%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/mul_fixed/short.rs (99%) rename {src/circuit/gadget/ecc => halo2-gadgets/halo2_ecc/src}/chip/witness_point.rs (100%) rename src/circuit/gadget/ecc.rs => halo2-gadgets/halo2_ecc/src/gadget.rs (99%) create mode 100644 halo2-gadgets/halo2_ecc/src/lib.rs create mode 100644 halo2-gadgets/halo2_poseidon/.gitignore create mode 100644 halo2-gadgets/halo2_poseidon/Cargo.toml create mode 100644 halo2-gadgets/halo2_poseidon/LICENSE-BOSL create mode 100644 halo2-gadgets/halo2_poseidon/benches/primitive.rs rename src/circuit/gadget/poseidon.rs => halo2-gadgets/halo2_poseidon/src/gadget.rs (97%) create mode 100644 halo2-gadgets/halo2_poseidon/src/lib.rs rename {src/circuit/gadget/poseidon => halo2-gadgets/halo2_poseidon/src}/pow5t3.rs (99%) rename src/primitives/poseidon.rs => halo2-gadgets/halo2_poseidon/src/primitive.rs (99%) rename {src/primitives/poseidon => halo2-gadgets/halo2_poseidon/src/primitive}/fp.rs (100%) rename {src/primitives/poseidon => halo2-gadgets/halo2_poseidon/src/primitive}/fq.rs (100%) rename {src/primitives/poseidon => halo2-gadgets/halo2_poseidon/src/primitive}/grain.rs (99%) rename {src/primitives/poseidon => halo2-gadgets/halo2_poseidon/src/primitive}/mds.rs (99%) rename {src/primitives/poseidon => halo2-gadgets/halo2_poseidon/src/primitive}/p128pow5t3.rs (99%) rename {src/primitives/poseidon => halo2-gadgets/halo2_poseidon/src/primitive}/test_vectors.rs (100%) create mode 100644 halo2-gadgets/halo2_utilities/.gitignore create mode 100644 halo2-gadgets/halo2_utilities/Cargo.toml create mode 100644 halo2-gadgets/halo2_utilities/LICENSE-BOSL rename {src/circuit/gadget/utilities => halo2-gadgets/halo2_utilities/src}/cond_swap.rs (95%) rename {src/circuit/gadget/utilities => halo2-gadgets/halo2_utilities/src}/decompose_running_sum.rs (100%) create mode 100644 halo2-gadgets/halo2_utilities/src/lib.rs rename {src/circuit/gadget/utilities => halo2-gadgets/halo2_utilities/src}/lookup_range_check.rs (99%) rename {src/circuit/gadget => halo2-gadgets/halo2_utilities/src}/utilities.rs (99%) create mode 100644 halo2-gadgets/sinsemilla/.gitignore create mode 100644 halo2-gadgets/sinsemilla/Cargo.toml create mode 100644 halo2-gadgets/sinsemilla/LICENSE-BOSL rename benches/primitives.rs => halo2-gadgets/sinsemilla/benches/primitive.rs (73%) rename {src/circuit/gadget/sinsemilla => halo2-gadgets/sinsemilla/src}/chip.rs (96%) rename {src/circuit/gadget/sinsemilla => halo2-gadgets/sinsemilla/src}/chip/generator_table.rs (98%) rename {src/circuit/gadget/sinsemilla => halo2-gadgets/sinsemilla/src}/chip/hash_to_point.rs (98%) rename src/circuit/gadget/sinsemilla.rs => halo2-gadgets/sinsemilla/src/gadget.rs (97%) create mode 100644 halo2-gadgets/sinsemilla/src/lib.rs rename {src/circuit/gadget/sinsemilla => halo2-gadgets/sinsemilla/src}/merkle.rs (95%) rename {src/circuit/gadget/sinsemilla => halo2-gadgets/sinsemilla/src}/merkle/chip.rs (97%) rename {src/circuit/gadget/sinsemilla => halo2-gadgets/sinsemilla/src}/message.rs (97%) rename src/primitives/sinsemilla.rs => halo2-gadgets/sinsemilla/src/primitive.rs (99%) rename {src/primitives/sinsemilla => halo2-gadgets/sinsemilla/src/primitive}/addition.rs (100%) rename {src/primitives/sinsemilla => halo2-gadgets/sinsemilla/src/primitive}/sinsemilla_s.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index f6601004..00b434f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,10 @@ serde = { version = "1.0", features = ["derive"] } subtle = "2.3" zcash_note_encryption = "0.0" incrementalmerkletree = "0.1" +ecc = { package = "halo2_ecc", version = "0.0", path = "./halo2-gadgets/halo2_ecc" } +utilities = { package = "halo2_utilities", version = "0.0", path = "./halo2-gadgets/halo2_utilities" } +poseidon = { package = "halo2_poseidon", version = "0.0", path = "./halo2-gadgets/halo2_poseidon", features = ["halo2"] } +sinsemilla = { version = "0.0", path = "./halo2-gadgets/sinsemilla", features = ["halo2"] } # Developer tooling dependencies plotters = { version = "0.3.0", optional = true } @@ -65,10 +69,6 @@ test-dependencies = ["proptest"] name = "note_decryption" harness = false -[[bench]] -name = "primitives" -harness = false - [[bench]] name = "small" harness = false diff --git a/halo2-gadgets/.gitignore b/halo2-gadgets/.gitignore new file mode 100644 index 00000000..173b9514 --- /dev/null +++ b/halo2-gadgets/.gitignore @@ -0,0 +1,4 @@ +/target +**/*.rs.bk +Cargo.lock +.vscode diff --git a/halo2-gadgets/Cargo.toml b/halo2-gadgets/Cargo.toml new file mode 100644 index 00000000..5a034811 --- /dev/null +++ b/halo2-gadgets/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] + +members = [ + "halo2_ecc", + "halo2_utilities", + "halo2_poseidon", + "sinsemilla", +] + +[patch.crates-io] +halo2 = { git = "https://github.com/zcash/halo2.git", rev = "27c4187673a9c6ade13fbdbd4f20955530c22d7f" } +orchard = { git = "https://github.com/zcash/orchard.git", rev = "b4a82211cee82ceb02d2e0e99b7566a967804a6c" } diff --git a/halo2-gadgets/LICENSE-BOSL b/halo2-gadgets/LICENSE-BOSL new file mode 100644 index 00000000..d73baa19 --- /dev/null +++ b/halo2-gadgets/LICENSE-BOSL @@ -0,0 +1,176 @@ +======================================================= +Bootstrap Open Source Licence ("BOSL") v. 1.0 +======================================================= +This Bootstrap Open Source Licence (the "License") applies to any original work +of authorship (the "Original Work") whose owner (the "Licensor") has placed the +following licensing notice adjacent to the copyright notice for the Original +Work: + +*Licensed under the Bootstrap Open Source Licence version 1.0* + +1. **Grant of Copyright License.** Licensor grants You a worldwide, + royalty-free, non-exclusive, sublicensable license, for the duration of the + copyright in the Original Work, to do the following: + + a. to reproduce the Original Work in copies, either alone or as part of + a collective work; + + b. to translate, adapt, alter, transform, modify, or arrange the + Original Work, thereby creating derivative works ("Derivative Works") + based upon the Original Work; + + c. to distribute or communicate copies of the Original Work and + Derivative Works to the public, provided that prior to any such + distribution or communication You first place a machine-readable copy + of the Source Code of the Original Work and such Derivative Works that + You intend to distribute or communicate in an information repository + reasonably calculated to permit inexpensive and convenient access + thereto by the public (“Information Repository”) for as long as You + continue to distribute or communicate said copies, accompanied by an + irrevocable offer to license said copies to the public free of charge + under this License, said offer valid starting no later than 12 months + after You first distribute or communicate said copies; + + d. to perform the Original Work publicly; and + + e. to display the Original Work publicly. + +2. **Grant of Patent License.** Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, under patent claims owned or controlled +by the Licensor that are embodied in the Original Work as furnished by the +Licensor, for the duration of the patents, to make, use, sell, offer for sale, +have made, and import the Original Work and Derivative Works. + +3. **Grant of Source Code License.** The "Source Code" for a work means the +preferred form of the work for making modifications to it and all available +documentation describing how to modify the work. Licensor agrees to provide a +machine-readable copy of the Source Code of the Original Work along with each +copy of the Original Work that Licensor distributes. Licensor reserves the +right to satisfy this obligation by placing a machine-readable copy of said +Source Code in an Information Repository for as long as Licensor continues to +distribute the Original Work. + +4. **Exclusions From License Grant.** Neither the names of Licensor, nor the +names of any contributors to the Original Work, nor any of their trademarks or +service marks, may be used to endorse or promote products derived from this +Original Work without express prior permission of the Licensor. Except as +expressly stated herein, nothing in this License grants any license to +Licensor's trademarks, copyrights, patents, trade secrets or any other +intellectual property. No patent license is granted to make, use, sell, offer +for sale, have made, or import embodiments of any patent claims other than the +licensed claims defined in Section 2. No license is granted to the trademarks +of Licensor even if such marks are included in the Original Work. Nothing in +this License shall be interpreted to prohibit Licensor from licensing under +terms different from this License any Original Work that Licensor otherwise +would have a right to license. + +5. **External Deployment.** The term "External Deployment" means the use, +distribution, or communication of the Original Work or Derivative Works in any +way such that the Original Work or Derivative Works may be used by anyone other +than You, whether those works are distributed or communicated to those persons +or made available as an application intended for use over a network. As an +express condition for the grants of license hereunder, You must treat any +External Deployment by You of the Original Work or a Derivative Work as a +distribution under section 1(c). + +6. **Attribution Rights.** You must retain, in the Source Code of any +Derivative Works that You create, all copyright, patent, or trademark notices +from the Source Code of the Original Work, as well as any notices of licensing +and any descriptive text identified therein as an "Attribution Notice." You +must cause the Source Code for any Derivative Works that You create to carry a +prominent Attribution Notice reasonably calculated to inform recipients that +You have modified the Original Work. + +7. **Warranty of Provenance and Disclaimer of Warranty.** Licensor warrants +that the copyright in and to the Original Work and the patent rights granted +herein by Licensor are owned by the Licensor or are sublicensed to You under +the terms of this License with the permission of the contributor(s) of those +copyrights and patent rights. Except as expressly stated in the immediately +preceding sentence, the Original Work is provided under this License on an "AS +IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without +limitation, the warranties of non-infringement, merchantability or fitness for +a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS +WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this +License. No license to the Original Work is granted by this License except +under this disclaimer. + +8. **Limitation of Liability.** Under no circumstances and under no legal +theory, whether in tort (including negligence), contract, or otherwise, shall +the Licensor be liable to anyone for any indirect, special, incidental, or +consequential damages of any character arising as a result of this License or +the use of the Original Work including, without limitation, damages for loss of +goodwill, work stoppage, computer failure or malfunction, or any and all other +commercial damages or losses. This limitation of liability shall not apply to +the extent applicable law prohibits such limitation. + +9. **Acceptance and Termination.** If, at any time, You expressly assented to +this License, that assent indicates your clear and irrevocable acceptance of +this License and all of its terms and conditions. If You distribute or +communicate copies of the Original Work or a Derivative Work, You must make a +reasonable effort under the circumstances to obtain the express assent of +recipients to the terms of this License. This License conditions your rights to +undertake the activities listed in Section 1, including your right to create +Derivative Works based upon the Original Work, and doing so without honoring +these terms and conditions is prohibited by copyright law and international +treaty. Nothing in this License is intended to affect copyright exceptions and +limitations (including 'fair use' or 'fair dealing'). This License shall +terminate immediately and You may no longer exercise any of the rights granted +to You by this License upon your failure to honor the conditions in Section +1(c). + +10. **Termination for Patent Action.** This License shall terminate +automatically and You may no longer exercise any of the rights granted to You +by this License as of the date You commence an action, including a cross-claim +or counterclaim, against Licensor or any licensee alleging that the Original +Work infringes a patent. This termination provision shall not apply for an +action alleging patent infringement by combinations of the Original Work with +other software or hardware. + +11. **Jurisdiction, Venue and Governing Law.** Any action or suit relating to +this License may be brought only in the courts of a jurisdiction wherein the +Licensor resides or in which Licensor conducts its primary business, and under +the laws of that jurisdiction excluding its conflict-of-law provisions. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any use of the Original Work outside the +scope of this License or after its termination shall be subject to the +requirements and penalties of copyright or patent law in the appropriate +jurisdiction. This section shall survive the termination of this License. + +12. **Attorneys' Fees.** In any action to enforce the terms of this License or +seeking damages relating thereto, the prevailing party shall be entitled to +recover its costs and expenses, including, without limitation, reasonable +attorneys' fees and costs incurred in connection with such action, including +any appeal of such action. This section shall survive the termination of this +License. + +13. **Miscellaneous.** If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent necessary to +make it enforceable. + +14. **Definition of "You" in This License.** "You" throughout this License, +whether in upper or lower case, means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this License. +For legal entities, "You" includes any entity that controls, is controlled by, +or is under common control with you. For 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. + +15. **Right to Use.** You may use the Original Work in all ways not otherwise +restricted or conditioned by this License or by law, and Licensor promises not +to interfere with or be responsible for such uses by You. + +16. **Modification of This License.** This License is Copyright © 2007 Zooko +Wilcox-O'Hearn. Permission is granted to copy, distribute, or communicate this +License without modification. Nothing in this License permits You to modify +this License as applied to the Original Work or to Derivative Works. However, +You may modify the text of this License and copy, distribute or communicate +your modified version (the "Modified License") and apply it to other original +works of authorship subject to the following conditions: (i) You may not +indicate in any way that your Modified License is the "Bootstrap Open Source +Licence" or "BOSL" and you may not use those names in the name of your Modified +License; and (ii) You must replace the notice specified in the first paragraph +above with the notice "Licensed under " or with +a notice of your own that is not confusingly similar to the notice in this +License. \ No newline at end of file diff --git a/halo2-gadgets/halo2_ecc/.gitignore b/halo2-gadgets/halo2_ecc/.gitignore new file mode 100644 index 00000000..173b9514 --- /dev/null +++ b/halo2-gadgets/halo2_ecc/.gitignore @@ -0,0 +1,4 @@ +/target +**/*.rs.bk +Cargo.lock +.vscode diff --git a/halo2-gadgets/halo2_ecc/Cargo.toml b/halo2-gadgets/halo2_ecc/Cargo.toml new file mode 100644 index 00000000..e78cc029 --- /dev/null +++ b/halo2-gadgets/halo2_ecc/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "halo2_ecc" +version = "0.0.0" +authors = [ + "Sean Bowe ", + "Jack Grigg ", +] +edition = "2018" +description = "ECC gadget for halo2" +license-file = "LICENSE-BOSL" +repository = "https://github.com/zcash/orchard" +documentation = "https://docs.rs/orchard" +readme = "README.md" + +# We are not publishing this yet. +publish = false + +[dependencies] +arrayvec = "0.7.0" +bigint = "4" +ff = "0.10" +group = "0.10" +halo2 = "0.0" +lazy_static = "1" +pasta_curves = "0.1.2" +utilities = { package = "halo2_utilities", version = "0.0", path = "../halo2_utilities" } + +[dev-dependencies] +orchard = "0.0" diff --git a/halo2-gadgets/halo2_ecc/LICENSE-BOSL b/halo2-gadgets/halo2_ecc/LICENSE-BOSL new file mode 100644 index 00000000..d73baa19 --- /dev/null +++ b/halo2-gadgets/halo2_ecc/LICENSE-BOSL @@ -0,0 +1,176 @@ +======================================================= +Bootstrap Open Source Licence ("BOSL") v. 1.0 +======================================================= +This Bootstrap Open Source Licence (the "License") applies to any original work +of authorship (the "Original Work") whose owner (the "Licensor") has placed the +following licensing notice adjacent to the copyright notice for the Original +Work: + +*Licensed under the Bootstrap Open Source Licence version 1.0* + +1. **Grant of Copyright License.** Licensor grants You a worldwide, + royalty-free, non-exclusive, sublicensable license, for the duration of the + copyright in the Original Work, to do the following: + + a. to reproduce the Original Work in copies, either alone or as part of + a collective work; + + b. to translate, adapt, alter, transform, modify, or arrange the + Original Work, thereby creating derivative works ("Derivative Works") + based upon the Original Work; + + c. to distribute or communicate copies of the Original Work and + Derivative Works to the public, provided that prior to any such + distribution or communication You first place a machine-readable copy + of the Source Code of the Original Work and such Derivative Works that + You intend to distribute or communicate in an information repository + reasonably calculated to permit inexpensive and convenient access + thereto by the public (“Information Repository”) for as long as You + continue to distribute or communicate said copies, accompanied by an + irrevocable offer to license said copies to the public free of charge + under this License, said offer valid starting no later than 12 months + after You first distribute or communicate said copies; + + d. to perform the Original Work publicly; and + + e. to display the Original Work publicly. + +2. **Grant of Patent License.** Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, under patent claims owned or controlled +by the Licensor that are embodied in the Original Work as furnished by the +Licensor, for the duration of the patents, to make, use, sell, offer for sale, +have made, and import the Original Work and Derivative Works. + +3. **Grant of Source Code License.** The "Source Code" for a work means the +preferred form of the work for making modifications to it and all available +documentation describing how to modify the work. Licensor agrees to provide a +machine-readable copy of the Source Code of the Original Work along with each +copy of the Original Work that Licensor distributes. Licensor reserves the +right to satisfy this obligation by placing a machine-readable copy of said +Source Code in an Information Repository for as long as Licensor continues to +distribute the Original Work. + +4. **Exclusions From License Grant.** Neither the names of Licensor, nor the +names of any contributors to the Original Work, nor any of their trademarks or +service marks, may be used to endorse or promote products derived from this +Original Work without express prior permission of the Licensor. Except as +expressly stated herein, nothing in this License grants any license to +Licensor's trademarks, copyrights, patents, trade secrets or any other +intellectual property. No patent license is granted to make, use, sell, offer +for sale, have made, or import embodiments of any patent claims other than the +licensed claims defined in Section 2. No license is granted to the trademarks +of Licensor even if such marks are included in the Original Work. Nothing in +this License shall be interpreted to prohibit Licensor from licensing under +terms different from this License any Original Work that Licensor otherwise +would have a right to license. + +5. **External Deployment.** The term "External Deployment" means the use, +distribution, or communication of the Original Work or Derivative Works in any +way such that the Original Work or Derivative Works may be used by anyone other +than You, whether those works are distributed or communicated to those persons +or made available as an application intended for use over a network. As an +express condition for the grants of license hereunder, You must treat any +External Deployment by You of the Original Work or a Derivative Work as a +distribution under section 1(c). + +6. **Attribution Rights.** You must retain, in the Source Code of any +Derivative Works that You create, all copyright, patent, or trademark notices +from the Source Code of the Original Work, as well as any notices of licensing +and any descriptive text identified therein as an "Attribution Notice." You +must cause the Source Code for any Derivative Works that You create to carry a +prominent Attribution Notice reasonably calculated to inform recipients that +You have modified the Original Work. + +7. **Warranty of Provenance and Disclaimer of Warranty.** Licensor warrants +that the copyright in and to the Original Work and the patent rights granted +herein by Licensor are owned by the Licensor or are sublicensed to You under +the terms of this License with the permission of the contributor(s) of those +copyrights and patent rights. Except as expressly stated in the immediately +preceding sentence, the Original Work is provided under this License on an "AS +IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without +limitation, the warranties of non-infringement, merchantability or fitness for +a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS +WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this +License. No license to the Original Work is granted by this License except +under this disclaimer. + +8. **Limitation of Liability.** Under no circumstances and under no legal +theory, whether in tort (including negligence), contract, or otherwise, shall +the Licensor be liable to anyone for any indirect, special, incidental, or +consequential damages of any character arising as a result of this License or +the use of the Original Work including, without limitation, damages for loss of +goodwill, work stoppage, computer failure or malfunction, or any and all other +commercial damages or losses. This limitation of liability shall not apply to +the extent applicable law prohibits such limitation. + +9. **Acceptance and Termination.** If, at any time, You expressly assented to +this License, that assent indicates your clear and irrevocable acceptance of +this License and all of its terms and conditions. If You distribute or +communicate copies of the Original Work or a Derivative Work, You must make a +reasonable effort under the circumstances to obtain the express assent of +recipients to the terms of this License. This License conditions your rights to +undertake the activities listed in Section 1, including your right to create +Derivative Works based upon the Original Work, and doing so without honoring +these terms and conditions is prohibited by copyright law and international +treaty. Nothing in this License is intended to affect copyright exceptions and +limitations (including 'fair use' or 'fair dealing'). This License shall +terminate immediately and You may no longer exercise any of the rights granted +to You by this License upon your failure to honor the conditions in Section +1(c). + +10. **Termination for Patent Action.** This License shall terminate +automatically and You may no longer exercise any of the rights granted to You +by this License as of the date You commence an action, including a cross-claim +or counterclaim, against Licensor or any licensee alleging that the Original +Work infringes a patent. This termination provision shall not apply for an +action alleging patent infringement by combinations of the Original Work with +other software or hardware. + +11. **Jurisdiction, Venue and Governing Law.** Any action or suit relating to +this License may be brought only in the courts of a jurisdiction wherein the +Licensor resides or in which Licensor conducts its primary business, and under +the laws of that jurisdiction excluding its conflict-of-law provisions. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any use of the Original Work outside the +scope of this License or after its termination shall be subject to the +requirements and penalties of copyright or patent law in the appropriate +jurisdiction. This section shall survive the termination of this License. + +12. **Attorneys' Fees.** In any action to enforce the terms of this License or +seeking damages relating thereto, the prevailing party shall be entitled to +recover its costs and expenses, including, without limitation, reasonable +attorneys' fees and costs incurred in connection with such action, including +any appeal of such action. This section shall survive the termination of this +License. + +13. **Miscellaneous.** If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent necessary to +make it enforceable. + +14. **Definition of "You" in This License.** "You" throughout this License, +whether in upper or lower case, means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this License. +For legal entities, "You" includes any entity that controls, is controlled by, +or is under common control with you. For 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. + +15. **Right to Use.** You may use the Original Work in all ways not otherwise +restricted or conditioned by this License or by law, and Licensor promises not +to interfere with or be responsible for such uses by You. + +16. **Modification of This License.** This License is Copyright © 2007 Zooko +Wilcox-O'Hearn. Permission is granted to copy, distribute, or communicate this +License without modification. Nothing in this License permits You to modify +this License as applied to the Original Work or to Derivative Works. However, +You may modify the text of this License and copy, distribute or communicate +your modified version (the "Modified License") and apply it to other original +works of authorship subject to the following conditions: (i) You may not +indicate in any way that your Modified License is the "Bootstrap Open Source +Licence" or "BOSL" and you may not use those names in the name of your Modified +License; and (ii) You must replace the notice specified in the first paragraph +above with the notice "Licensed under " or with +a notice of your own that is not confusingly similar to the notice in this +License. \ No newline at end of file diff --git a/src/circuit/gadget/ecc/chip.rs b/halo2-gadgets/halo2_ecc/src/chip.rs similarity index 93% rename from src/circuit/gadget/ecc/chip.rs rename to halo2-gadgets/halo2_ecc/src/chip.rs index 15f91e70..d7b1c2fd 100644 --- a/src/circuit/gadget/ecc/chip.rs +++ b/halo2-gadgets/halo2_ecc/src/chip.rs @@ -1,10 +1,7 @@ -use super::{EccInstructions, FixedPoints, FIXED_BASE_WINDOW_SIZE, H}; -use crate::{ - circuit::gadget::utilities::{ - copy, decompose_running_sum::RunningSumConfig, lookup_range_check::LookupRangeCheckConfig, - CellValue, UtilitiesInstructions, Var, - }, - primitives::sinsemilla, +use super::gadget::{EccInstructions, FixedPoints, FIXED_BASE_WINDOW_SIZE, H}; +use utilities::{ + copy, decompose_running_sum::RunningSumConfig, lookup_range_check::LookupRangeCheckConfig, + CellValue, UtilitiesInstructions, Var, }; use arrayvec::ArrayVec; use std::marker::PhantomData; @@ -50,6 +47,9 @@ pub(crate) const T_Q: u128 = 45560315531506369815346746415080538113; /// pub(crate) const T_P: u128 = 45560315531419706090280762371685220353; +/// Number of bits in the lookup table. +const LOOKUP_K: usize = 10; + /// A curve point represented in affine (x, y) coordinates, or the /// identity represented as (0, 0). /// Each coordinate is assigned to a cell. @@ -66,7 +66,7 @@ impl EccPoint { /// /// This is an internal API that we only use where we know we have a valid curve point /// (specifically inside Sinsemilla). - pub(in crate::circuit::gadget) fn from_coordinates_unchecked( + pub(crate) fn from_coordinates_unchecked( x: CellValue, y: CellValue, ) -> Self { @@ -199,19 +199,19 @@ pub struct EccConfig { pub q_point_non_id: Selector, /// Lookup range check using 10-bit lookup table - pub lookup_config: LookupRangeCheckConfig, + pub lookup_config: LookupRangeCheckConfig, /// Running sum decomposition. pub running_sum_config: RunningSumConfig, } /// A chip implementing EccInstructions #[derive(Clone, Debug, Eq, PartialEq)] -pub struct EccChip> { +pub struct EccChip> { config: EccConfig, _marker: PhantomData, } -impl> Chip for EccChip { +impl> Chip for EccChip { type Config = EccConfig; type Loaded = (); @@ -224,13 +224,13 @@ impl> Chip for EccChip> UtilitiesInstructions +impl> UtilitiesInstructions for EccChip { type Var = CellValue; } -impl> EccChip { +impl> EccChip { pub fn construct(config: >::Config) -> Self { Self { config, @@ -246,7 +246,7 @@ impl> EccChip { meta: &mut ConstraintSystem, advices: [Column; 10], lagrange_coeffs: [Column; 8], - range_check: LookupRangeCheckConfig, + range_check: LookupRangeCheckConfig, ) -> >::Config { // The following columns need to be equality-enabled for their use in sub-configs: // @@ -332,27 +332,27 @@ impl> EccChip { // and fixed-base mul using a base field element. { // The const generic does not matter when creating gates. - let mul_fixed_config: mul_fixed::Config = + let mul_fixed_config: mul_fixed::Config = (&config).into(); mul_fixed_config.running_sum_coords_gate(meta); } // Create gate that is only used in full-width fixed-base scalar mul. { - let mul_fixed_full_config: mul_fixed::full_width::Config = + let mul_fixed_full_config: mul_fixed::full_width::Config = (&config).into(); mul_fixed_full_config.create_gate(meta); } // Create gate that is only used in short fixed-base scalar mul. { - let short_config: mul_fixed::short::Config = (&config).into(); + let short_config: mul_fixed::short::Config = (&config).into(); short_config.create_gate(meta); } // Create gate that is only used in fixed-base mul using a base field element. { - let base_field_config: mul_fixed::base_field_elem::Config = + let base_field_config: mul_fixed::base_field_elem::Config = (&config).into(); base_field_config.create_gate(meta); } @@ -412,7 +412,7 @@ impl EccBaseFieldElemFixed { } } -impl> EccInstructions for EccChip { +impl> EccInstructions for EccChip { type ScalarFixed = EccScalarFixed; type ScalarFixedShort = EccScalarFixedShort; type ScalarVar = CellValue; diff --git a/src/circuit/gadget/ecc/chip/add.rs b/halo2-gadgets/halo2_ecc/src/chip/add.rs similarity index 100% rename from src/circuit/gadget/ecc/chip/add.rs rename to halo2-gadgets/halo2_ecc/src/chip/add.rs diff --git a/src/circuit/gadget/ecc/chip/add_incomplete.rs b/halo2-gadgets/halo2_ecc/src/chip/add_incomplete.rs similarity index 100% rename from src/circuit/gadget/ecc/chip/add_incomplete.rs rename to halo2-gadgets/halo2_ecc/src/chip/add_incomplete.rs diff --git a/src/circuit/gadget/ecc/chip/mul.rs b/halo2-gadgets/halo2_ecc/src/chip/mul.rs similarity index 99% rename from src/circuit/gadget/ecc/chip/mul.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul.rs index 295f081b..ff52d3a2 100644 --- a/src/circuit/gadget/ecc/chip/mul.rs +++ b/halo2-gadgets/halo2_ecc/src/chip/mul.rs @@ -1,5 +1,5 @@ use super::{add, CellValue, EccConfig, EccPoint, NonIdentityEccPoint, Var, T_Q}; -use crate::circuit::gadget::utilities::copy; +use utilities::copy; use std::ops::{Deref, Range}; use bigint::U256; diff --git a/src/circuit/gadget/ecc/chip/mul/complete.rs b/halo2-gadgets/halo2_ecc/src/chip/mul/complete.rs similarity index 100% rename from src/circuit/gadget/ecc/chip/mul/complete.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul/complete.rs diff --git a/src/circuit/gadget/ecc/chip/mul/incomplete.rs b/halo2-gadgets/halo2_ecc/src/chip/mul/incomplete.rs similarity index 100% rename from src/circuit/gadget/ecc/chip/mul/incomplete.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul/incomplete.rs diff --git a/src/circuit/gadget/ecc/chip/mul/overflow.rs b/halo2-gadgets/halo2_ecc/src/chip/mul/overflow.rs similarity index 95% rename from src/circuit/gadget/ecc/chip/mul/overflow.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul/overflow.rs index de996fd0..b8a4138a 100644 --- a/src/circuit/gadget/ecc/chip/mul/overflow.rs +++ b/halo2-gadgets/halo2_ecc/src/chip/mul/overflow.rs @@ -1,8 +1,7 @@ -use super::super::{copy, CellValue, EccConfig, Var}; +use super::super::{copy, CellValue, EccConfig, Var, LOOKUP_K}; use super::{T_Q, Z}; -use crate::{ - circuit::gadget::utilities::lookup_range_check::LookupRangeCheckConfig, primitives::sinsemilla, -}; +use utilities::lookup_range_check::LookupRangeCheckConfig; + use halo2::{ circuit::Layouter, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector}, @@ -18,7 +17,7 @@ pub struct Config { // Selector to check z_0 = alpha + t_q (mod p) q_mul_overflow: Selector, // 10-bit lookup table - lookup_config: LookupRangeCheckConfig, + lookup_config: LookupRangeCheckConfig, // Advice columns advices: [Column; 3], } @@ -206,8 +205,8 @@ impl Config { s: CellValue, ) -> Result, Error> { // Number of k-bit words we can use in the lookup decomposition. - let num_words = 130 / sinsemilla::K; - assert!(num_words * sinsemilla::K == 130); + let num_words = 130 / LOOKUP_K; + assert!(num_words * LOOKUP_K == 130); // Decompose the low 130 bits of `s` using thirteen 10-bit lookups. let zs = self.lookup_config.copy_check( diff --git a/src/circuit/gadget/ecc/chip/mul_fixed.rs b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed.rs similarity index 100% rename from src/circuit/gadget/ecc/chip/mul_fixed.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul_fixed.rs diff --git a/src/circuit/gadget/ecc/chip/mul_fixed/base_field_elem.rs b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed/base_field_elem.rs similarity index 98% rename from src/circuit/gadget/ecc/chip/mul_fixed/base_field_elem.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul_fixed/base_field_elem.rs index 038163b1..1a17d5c4 100644 --- a/src/circuit/gadget/ecc/chip/mul_fixed/base_field_elem.rs +++ b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed/base_field_elem.rs @@ -1,16 +1,13 @@ use super::super::{ EccBaseFieldElemFixed, EccConfig, EccPoint, FixedPoints, FIXED_BASE_WINDOW_SIZE, - L_ORCHARD_BASE, NUM_WINDOWS, T_P, + L_ORCHARD_BASE, NUM_WINDOWS, T_P, LOOKUP_K }; use super::H_BASE; - -use crate::{ - circuit::gadget::utilities::{ - bitrange_subset, copy, decompose_running_sum::RunningSumConfig, - lookup_range_check::LookupRangeCheckConfig, range_check, CellValue, Var, - }, - primitives::sinsemilla, +use utilities::{ + bitrange_subset, copy, decompose_running_sum::RunningSumConfig, + lookup_range_check::LookupRangeCheckConfig, range_check, CellValue, Var, }; + use halo2::{ circuit::Layouter, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector}, @@ -24,7 +21,7 @@ pub struct Config> { q_mul_fixed_running_sum: Selector, q_mul_fixed_base_field: Selector, canon_advices: [Column; 3], - lookup_config: LookupRangeCheckConfig, + lookup_config: LookupRangeCheckConfig, running_sum_config: RunningSumConfig, super_config: super::Config, } diff --git a/src/circuit/gadget/ecc/chip/mul_fixed/full_width.rs b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed/full_width.rs similarity index 99% rename from src/circuit/gadget/ecc/chip/mul_fixed/full_width.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul_fixed/full_width.rs index a23fc997..b9170550 100644 --- a/src/circuit/gadget/ecc/chip/mul_fixed/full_width.rs +++ b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed/full_width.rs @@ -3,7 +3,7 @@ use super::super::{ NUM_WINDOWS, }; -use crate::circuit::gadget::utilities::{decompose_word, range_check, CellValue, Var}; +use utilities::{decompose_word, range_check, CellValue, Var}; use arrayvec::ArrayVec; use halo2::{ circuit::{Layouter, Region}, diff --git a/src/circuit/gadget/ecc/chip/mul_fixed/short.rs b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed/short.rs similarity index 99% rename from src/circuit/gadget/ecc/chip/mul_fixed/short.rs rename to halo2-gadgets/halo2_ecc/src/chip/mul_fixed/short.rs index 70fb6c0d..37be1bbb 100644 --- a/src/circuit/gadget/ecc/chip/mul_fixed/short.rs +++ b/halo2-gadgets/halo2_ecc/src/chip/mul_fixed/short.rs @@ -4,7 +4,7 @@ use super::super::{ EccConfig, EccPoint, EccScalarFixedShort, FixedPoints, FIXED_BASE_WINDOW_SIZE, L_VALUE, NUM_WINDOWS_SHORT, }; -use crate::circuit::gadget::utilities::{ +use utilities::{ copy, decompose_running_sum::RunningSumConfig, CellValue, Var, }; diff --git a/src/circuit/gadget/ecc/chip/witness_point.rs b/halo2-gadgets/halo2_ecc/src/chip/witness_point.rs similarity index 100% rename from src/circuit/gadget/ecc/chip/witness_point.rs rename to halo2-gadgets/halo2_ecc/src/chip/witness_point.rs diff --git a/src/circuit/gadget/ecc.rs b/halo2-gadgets/halo2_ecc/src/gadget.rs similarity index 99% rename from src/circuit/gadget/ecc.rs rename to halo2-gadgets/halo2_ecc/src/gadget.rs index a76538b0..d1201ad4 100644 --- a/src/circuit/gadget/ecc.rs +++ b/halo2-gadgets/halo2_ecc/src/gadget.rs @@ -8,9 +8,7 @@ use halo2::{ plonk::Error, }; -use crate::circuit::gadget::utilities::UtilitiesInstructions; - -pub mod chip; +use utilities::UtilitiesInstructions; /// Window size for fixed-base scalar multiplication pub const FIXED_BASE_WINDOW_SIZE: usize = 3; diff --git a/halo2-gadgets/halo2_ecc/src/lib.rs b/halo2-gadgets/halo2_ecc/src/lib.rs new file mode 100644 index 00000000..2ece84df --- /dev/null +++ b/halo2-gadgets/halo2_ecc/src/lib.rs @@ -0,0 +1,3 @@ +//! ECC gadget and chip +pub mod gadget; +pub mod chip; diff --git a/halo2-gadgets/halo2_poseidon/.gitignore b/halo2-gadgets/halo2_poseidon/.gitignore new file mode 100644 index 00000000..173b9514 --- /dev/null +++ b/halo2-gadgets/halo2_poseidon/.gitignore @@ -0,0 +1,4 @@ +/target +**/*.rs.bk +Cargo.lock +.vscode diff --git a/halo2-gadgets/halo2_poseidon/Cargo.toml b/halo2-gadgets/halo2_poseidon/Cargo.toml new file mode 100644 index 00000000..a39ac9a3 --- /dev/null +++ b/halo2-gadgets/halo2_poseidon/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "halo2_poseidon" +version = "0.0.0" +authors = [ + "Sean Bowe ", + "Jack Grigg ", +] +edition = "2018" +description = "Poseidon hash function" +license-file = "LICENSE-BOSL" +repository = "https://github.com/zcash/orchard" +documentation = "https://docs.rs/orchard" +readme = "README.md" + +# We are not publishing this yet. +publish = false + +[target.'cfg(unix)'.dev-dependencies] +pprof = { version = "0.4.2", features = ["criterion", "flamegraph"] } + +[dependencies] +bitvec = "0.22" +halo2 = { version = "0.0", optional = true } +pasta_curves = "0.1.2" +utilities = { package = "halo2_utilities", version = "0.0", path = "../halo2_utilities" } + +[[bench]] +name = "primitive" +harness = false diff --git a/halo2-gadgets/halo2_poseidon/LICENSE-BOSL b/halo2-gadgets/halo2_poseidon/LICENSE-BOSL new file mode 100644 index 00000000..d73baa19 --- /dev/null +++ b/halo2-gadgets/halo2_poseidon/LICENSE-BOSL @@ -0,0 +1,176 @@ +======================================================= +Bootstrap Open Source Licence ("BOSL") v. 1.0 +======================================================= +This Bootstrap Open Source Licence (the "License") applies to any original work +of authorship (the "Original Work") whose owner (the "Licensor") has placed the +following licensing notice adjacent to the copyright notice for the Original +Work: + +*Licensed under the Bootstrap Open Source Licence version 1.0* + +1. **Grant of Copyright License.** Licensor grants You a worldwide, + royalty-free, non-exclusive, sublicensable license, for the duration of the + copyright in the Original Work, to do the following: + + a. to reproduce the Original Work in copies, either alone or as part of + a collective work; + + b. to translate, adapt, alter, transform, modify, or arrange the + Original Work, thereby creating derivative works ("Derivative Works") + based upon the Original Work; + + c. to distribute or communicate copies of the Original Work and + Derivative Works to the public, provided that prior to any such + distribution or communication You first place a machine-readable copy + of the Source Code of the Original Work and such Derivative Works that + You intend to distribute or communicate in an information repository + reasonably calculated to permit inexpensive and convenient access + thereto by the public (“Information Repository”) for as long as You + continue to distribute or communicate said copies, accompanied by an + irrevocable offer to license said copies to the public free of charge + under this License, said offer valid starting no later than 12 months + after You first distribute or communicate said copies; + + d. to perform the Original Work publicly; and + + e. to display the Original Work publicly. + +2. **Grant of Patent License.** Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, under patent claims owned or controlled +by the Licensor that are embodied in the Original Work as furnished by the +Licensor, for the duration of the patents, to make, use, sell, offer for sale, +have made, and import the Original Work and Derivative Works. + +3. **Grant of Source Code License.** The "Source Code" for a work means the +preferred form of the work for making modifications to it and all available +documentation describing how to modify the work. Licensor agrees to provide a +machine-readable copy of the Source Code of the Original Work along with each +copy of the Original Work that Licensor distributes. Licensor reserves the +right to satisfy this obligation by placing a machine-readable copy of said +Source Code in an Information Repository for as long as Licensor continues to +distribute the Original Work. + +4. **Exclusions From License Grant.** Neither the names of Licensor, nor the +names of any contributors to the Original Work, nor any of their trademarks or +service marks, may be used to endorse or promote products derived from this +Original Work without express prior permission of the Licensor. Except as +expressly stated herein, nothing in this License grants any license to +Licensor's trademarks, copyrights, patents, trade secrets or any other +intellectual property. No patent license is granted to make, use, sell, offer +for sale, have made, or import embodiments of any patent claims other than the +licensed claims defined in Section 2. No license is granted to the trademarks +of Licensor even if such marks are included in the Original Work. Nothing in +this License shall be interpreted to prohibit Licensor from licensing under +terms different from this License any Original Work that Licensor otherwise +would have a right to license. + +5. **External Deployment.** The term "External Deployment" means the use, +distribution, or communication of the Original Work or Derivative Works in any +way such that the Original Work or Derivative Works may be used by anyone other +than You, whether those works are distributed or communicated to those persons +or made available as an application intended for use over a network. As an +express condition for the grants of license hereunder, You must treat any +External Deployment by You of the Original Work or a Derivative Work as a +distribution under section 1(c). + +6. **Attribution Rights.** You must retain, in the Source Code of any +Derivative Works that You create, all copyright, patent, or trademark notices +from the Source Code of the Original Work, as well as any notices of licensing +and any descriptive text identified therein as an "Attribution Notice." You +must cause the Source Code for any Derivative Works that You create to carry a +prominent Attribution Notice reasonably calculated to inform recipients that +You have modified the Original Work. + +7. **Warranty of Provenance and Disclaimer of Warranty.** Licensor warrants +that the copyright in and to the Original Work and the patent rights granted +herein by Licensor are owned by the Licensor or are sublicensed to You under +the terms of this License with the permission of the contributor(s) of those +copyrights and patent rights. Except as expressly stated in the immediately +preceding sentence, the Original Work is provided under this License on an "AS +IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without +limitation, the warranties of non-infringement, merchantability or fitness for +a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS +WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this +License. No license to the Original Work is granted by this License except +under this disclaimer. + +8. **Limitation of Liability.** Under no circumstances and under no legal +theory, whether in tort (including negligence), contract, or otherwise, shall +the Licensor be liable to anyone for any indirect, special, incidental, or +consequential damages of any character arising as a result of this License or +the use of the Original Work including, without limitation, damages for loss of +goodwill, work stoppage, computer failure or malfunction, or any and all other +commercial damages or losses. This limitation of liability shall not apply to +the extent applicable law prohibits such limitation. + +9. **Acceptance and Termination.** If, at any time, You expressly assented to +this License, that assent indicates your clear and irrevocable acceptance of +this License and all of its terms and conditions. If You distribute or +communicate copies of the Original Work or a Derivative Work, You must make a +reasonable effort under the circumstances to obtain the express assent of +recipients to the terms of this License. This License conditions your rights to +undertake the activities listed in Section 1, including your right to create +Derivative Works based upon the Original Work, and doing so without honoring +these terms and conditions is prohibited by copyright law and international +treaty. Nothing in this License is intended to affect copyright exceptions and +limitations (including 'fair use' or 'fair dealing'). This License shall +terminate immediately and You may no longer exercise any of the rights granted +to You by this License upon your failure to honor the conditions in Section +1(c). + +10. **Termination for Patent Action.** This License shall terminate +automatically and You may no longer exercise any of the rights granted to You +by this License as of the date You commence an action, including a cross-claim +or counterclaim, against Licensor or any licensee alleging that the Original +Work infringes a patent. This termination provision shall not apply for an +action alleging patent infringement by combinations of the Original Work with +other software or hardware. + +11. **Jurisdiction, Venue and Governing Law.** Any action or suit relating to +this License may be brought only in the courts of a jurisdiction wherein the +Licensor resides or in which Licensor conducts its primary business, and under +the laws of that jurisdiction excluding its conflict-of-law provisions. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any use of the Original Work outside the +scope of this License or after its termination shall be subject to the +requirements and penalties of copyright or patent law in the appropriate +jurisdiction. This section shall survive the termination of this License. + +12. **Attorneys' Fees.** In any action to enforce the terms of this License or +seeking damages relating thereto, the prevailing party shall be entitled to +recover its costs and expenses, including, without limitation, reasonable +attorneys' fees and costs incurred in connection with such action, including +any appeal of such action. This section shall survive the termination of this +License. + +13. **Miscellaneous.** If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent necessary to +make it enforceable. + +14. **Definition of "You" in This License.** "You" throughout this License, +whether in upper or lower case, means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this License. +For legal entities, "You" includes any entity that controls, is controlled by, +or is under common control with you. For 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. + +15. **Right to Use.** You may use the Original Work in all ways not otherwise +restricted or conditioned by this License or by law, and Licensor promises not +to interfere with or be responsible for such uses by You. + +16. **Modification of This License.** This License is Copyright © 2007 Zooko +Wilcox-O'Hearn. Permission is granted to copy, distribute, or communicate this +License without modification. Nothing in this License permits You to modify +this License as applied to the Original Work or to Derivative Works. However, +You may modify the text of this License and copy, distribute or communicate +your modified version (the "Modified License") and apply it to other original +works of authorship subject to the following conditions: (i) You may not +indicate in any way that your Modified License is the "Bootstrap Open Source +Licence" or "BOSL" and you may not use those names in the name of your Modified +License; and (ii) You must replace the notice specified in the first paragraph +above with the notice "Licensed under " or with +a notice of your own that is not confusingly similar to the notice in this +License. \ No newline at end of file diff --git a/halo2-gadgets/halo2_poseidon/benches/primitive.rs b/halo2-gadgets/halo2_poseidon/benches/primitive.rs new file mode 100644 index 00000000..9e9eafb8 --- /dev/null +++ b/halo2-gadgets/halo2_poseidon/benches/primitive.rs @@ -0,0 +1,34 @@ +use std::array; + +use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; +use ff::Field; +use poseidon::primitive::{Hash, ConstantLength, P128Pow5T3}; + +use pasta_curves::pallas; +#[cfg(unix)] +use pprof::criterion::{Output, PProfProfiler}; +use rand::{rngs::OsRng, Rng}; + +fn bench_primitives(c: &mut Criterion) { + let mut rng = OsRng; + + { + let mut group = c.benchmark_group("Poseidon"); + + let message = [pallas::Base::random(rng), pallas::Base::random(rng)]; + + group.bench_function("2-to-1", |b| { + b.iter(|| Hash::init(P128Pow5T3, ConstantLength).hash(message)) + }); + } +} + +#[cfg(unix)] +criterion_group! { + name = benches; + config = Criterion::default().with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_primitives +} +#[cfg(not(unix))] +criterion_group!(benches, bench_primitives); +criterion_main!(benches); diff --git a/src/circuit/gadget/poseidon.rs b/halo2-gadgets/halo2_poseidon/src/gadget.rs similarity index 97% rename from src/circuit/gadget/poseidon.rs rename to halo2-gadgets/halo2_poseidon/src/gadget.rs index 8e6cd7c0..e5d1270f 100644 --- a/src/circuit/gadget/poseidon.rs +++ b/halo2-gadgets/halo2_poseidon/src/gadget.rs @@ -9,10 +9,7 @@ use halo2::{ plonk::Error, }; -mod pow5t3; -pub use pow5t3::{Pow5T3Chip, Pow5T3Config, StateWord}; - -use crate::primitives::poseidon::{ConstantLength, Domain, Spec, Sponge, SpongeState, State}; +use super::primitive::{ConstantLength, Domain, Spec, Sponge, SpongeState, State}; /// The set of circuit instructions required to use the Poseidon permutation. pub trait PoseidonInstructions, const T: usize, const RATE: usize>: diff --git a/halo2-gadgets/halo2_poseidon/src/lib.rs b/halo2-gadgets/halo2_poseidon/src/lib.rs new file mode 100644 index 00000000..72ef86e3 --- /dev/null +++ b/halo2-gadgets/halo2_poseidon/src/lib.rs @@ -0,0 +1,6 @@ +//! Gadget, chip, and primitives for the Poseidon hash function. +#[cfg(feature = "halo2")] +pub mod gadget; +#[cfg(feature = "halo2")] +pub mod pow5t3; +pub mod primitive; diff --git a/src/circuit/gadget/poseidon/pow5t3.rs b/halo2-gadgets/halo2_poseidon/src/pow5t3.rs similarity index 99% rename from src/circuit/gadget/poseidon/pow5t3.rs rename to halo2-gadgets/halo2_poseidon/src/pow5t3.rs index e07504a3..d516a906 100644 --- a/src/circuit/gadget/poseidon/pow5t3.rs +++ b/halo2-gadgets/halo2_poseidon/src/pow5t3.rs @@ -7,16 +7,16 @@ use halo2::{ poly::Rotation, }; -use super::{PoseidonDuplexInstructions, PoseidonInstructions}; -use crate::circuit::gadget::utilities::{CellValue, Var}; -use crate::primitives::poseidon::{Domain, Mds, Spec, SpongeState, State}; +use super::gadget::{PoseidonDuplexInstructions, PoseidonInstructions}; +use utilities::{CellValue, Var}; +use super::primitive::{Domain, Mds, Spec, SpongeState, State}; const WIDTH: usize = 3; /// Configuration for an [`Pow5T3Chip`]. #[derive(Clone, Debug)] pub struct Pow5T3Config { - pub(in crate::circuit) state: [Column; WIDTH], + pub(crate) state: [Column; WIDTH], partial_sbox: Column, rc_a: [Column; WIDTH], rc_b: [Column; WIDTH], diff --git a/src/primitives/poseidon.rs b/halo2-gadgets/halo2_poseidon/src/primitive.rs similarity index 99% rename from src/primitives/poseidon.rs rename to halo2-gadgets/halo2_poseidon/src/primitive.rs index f2892d1b..05986a4d 100644 --- a/src/primitives/poseidon.rs +++ b/halo2-gadgets/halo2_poseidon/src/primitive.rs @@ -5,9 +5,10 @@ use std::fmt; use std::iter; use std::marker::PhantomData; -use halo2::arithmetic::FieldExt; +use pasta_curves::arithmetic::FieldExt; pub(crate) mod fp; +#[allow(dead_code)] pub(crate) mod fq; pub(crate) mod grain; pub(crate) mod mds; diff --git a/src/primitives/poseidon/fp.rs b/halo2-gadgets/halo2_poseidon/src/primitive/fp.rs similarity index 100% rename from src/primitives/poseidon/fp.rs rename to halo2-gadgets/halo2_poseidon/src/primitive/fp.rs diff --git a/src/primitives/poseidon/fq.rs b/halo2-gadgets/halo2_poseidon/src/primitive/fq.rs similarity index 100% rename from src/primitives/poseidon/fq.rs rename to halo2-gadgets/halo2_poseidon/src/primitive/fq.rs diff --git a/src/primitives/poseidon/grain.rs b/halo2-gadgets/halo2_poseidon/src/primitive/grain.rs similarity index 99% rename from src/primitives/poseidon/grain.rs rename to halo2-gadgets/halo2_poseidon/src/primitive/grain.rs index 580f86d4..06339e1e 100644 --- a/src/primitives/poseidon/grain.rs +++ b/halo2-gadgets/halo2_poseidon/src/primitive/grain.rs @@ -3,7 +3,7 @@ use std::marker::PhantomData; use bitvec::prelude::*; -use halo2::arithmetic::FieldExt; +use pasta_curves::arithmetic::FieldExt; const STATE: usize = 80; diff --git a/src/primitives/poseidon/mds.rs b/halo2-gadgets/halo2_poseidon/src/primitive/mds.rs similarity index 99% rename from src/primitives/poseidon/mds.rs rename to halo2-gadgets/halo2_poseidon/src/primitive/mds.rs index 7f9d1460..903da0e8 100644 --- a/src/primitives/poseidon/mds.rs +++ b/halo2-gadgets/halo2_poseidon/src/primitive/mds.rs @@ -1,4 +1,4 @@ -use halo2::arithmetic::FieldExt; +use pasta_curves::arithmetic::FieldExt; use super::{grain::Grain, Mds}; diff --git a/src/primitives/poseidon/p128pow5t3.rs b/halo2-gadgets/halo2_poseidon/src/primitive/p128pow5t3.rs similarity index 99% rename from src/primitives/poseidon/p128pow5t3.rs rename to halo2-gadgets/halo2_poseidon/src/primitive/p128pow5t3.rs index 31c7217c..67992c91 100644 --- a/src/primitives/poseidon/p128pow5t3.rs +++ b/halo2-gadgets/halo2_poseidon/src/primitive/p128pow5t3.rs @@ -1,5 +1,4 @@ -use halo2::arithmetic::Field; -use pasta_curves::{pallas::Base as Fp, vesta::Base as Fq}; +use pasta_curves::{arithmetic::Field, pallas::Base as Fp, vesta::Base as Fq}; use super::{Mds, Spec}; diff --git a/src/primitives/poseidon/test_vectors.rs b/halo2-gadgets/halo2_poseidon/src/primitive/test_vectors.rs similarity index 100% rename from src/primitives/poseidon/test_vectors.rs rename to halo2-gadgets/halo2_poseidon/src/primitive/test_vectors.rs diff --git a/halo2-gadgets/halo2_utilities/.gitignore b/halo2-gadgets/halo2_utilities/.gitignore new file mode 100644 index 00000000..173b9514 --- /dev/null +++ b/halo2-gadgets/halo2_utilities/.gitignore @@ -0,0 +1,4 @@ +/target +**/*.rs.bk +Cargo.lock +.vscode diff --git a/halo2-gadgets/halo2_utilities/Cargo.toml b/halo2-gadgets/halo2_utilities/Cargo.toml new file mode 100644 index 00000000..5811ce47 --- /dev/null +++ b/halo2-gadgets/halo2_utilities/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "halo2_utilities" +version = "0.0.0" +authors = [ + "Sean Bowe ", + "Jack Grigg ", +] +edition = "2018" +description = "Utility gadgets for halo2" +license-file = "LICENSE-BOSL" +repository = "https://github.com/zcash/orchard" +documentation = "https://docs.rs/orchard" +readme = "README.md" + +# We are not publishing this yet. +publish = false + +[dependencies] +ff = "0.10" +halo2 = "0.0" +pasta_curves = "0.1.2" diff --git a/halo2-gadgets/halo2_utilities/LICENSE-BOSL b/halo2-gadgets/halo2_utilities/LICENSE-BOSL new file mode 100644 index 00000000..d73baa19 --- /dev/null +++ b/halo2-gadgets/halo2_utilities/LICENSE-BOSL @@ -0,0 +1,176 @@ +======================================================= +Bootstrap Open Source Licence ("BOSL") v. 1.0 +======================================================= +This Bootstrap Open Source Licence (the "License") applies to any original work +of authorship (the "Original Work") whose owner (the "Licensor") has placed the +following licensing notice adjacent to the copyright notice for the Original +Work: + +*Licensed under the Bootstrap Open Source Licence version 1.0* + +1. **Grant of Copyright License.** Licensor grants You a worldwide, + royalty-free, non-exclusive, sublicensable license, for the duration of the + copyright in the Original Work, to do the following: + + a. to reproduce the Original Work in copies, either alone or as part of + a collective work; + + b. to translate, adapt, alter, transform, modify, or arrange the + Original Work, thereby creating derivative works ("Derivative Works") + based upon the Original Work; + + c. to distribute or communicate copies of the Original Work and + Derivative Works to the public, provided that prior to any such + distribution or communication You first place a machine-readable copy + of the Source Code of the Original Work and such Derivative Works that + You intend to distribute or communicate in an information repository + reasonably calculated to permit inexpensive and convenient access + thereto by the public (“Information Repository”) for as long as You + continue to distribute or communicate said copies, accompanied by an + irrevocable offer to license said copies to the public free of charge + under this License, said offer valid starting no later than 12 months + after You first distribute or communicate said copies; + + d. to perform the Original Work publicly; and + + e. to display the Original Work publicly. + +2. **Grant of Patent License.** Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, under patent claims owned or controlled +by the Licensor that are embodied in the Original Work as furnished by the +Licensor, for the duration of the patents, to make, use, sell, offer for sale, +have made, and import the Original Work and Derivative Works. + +3. **Grant of Source Code License.** The "Source Code" for a work means the +preferred form of the work for making modifications to it and all available +documentation describing how to modify the work. Licensor agrees to provide a +machine-readable copy of the Source Code of the Original Work along with each +copy of the Original Work that Licensor distributes. Licensor reserves the +right to satisfy this obligation by placing a machine-readable copy of said +Source Code in an Information Repository for as long as Licensor continues to +distribute the Original Work. + +4. **Exclusions From License Grant.** Neither the names of Licensor, nor the +names of any contributors to the Original Work, nor any of their trademarks or +service marks, may be used to endorse or promote products derived from this +Original Work without express prior permission of the Licensor. Except as +expressly stated herein, nothing in this License grants any license to +Licensor's trademarks, copyrights, patents, trade secrets or any other +intellectual property. No patent license is granted to make, use, sell, offer +for sale, have made, or import embodiments of any patent claims other than the +licensed claims defined in Section 2. No license is granted to the trademarks +of Licensor even if such marks are included in the Original Work. Nothing in +this License shall be interpreted to prohibit Licensor from licensing under +terms different from this License any Original Work that Licensor otherwise +would have a right to license. + +5. **External Deployment.** The term "External Deployment" means the use, +distribution, or communication of the Original Work or Derivative Works in any +way such that the Original Work or Derivative Works may be used by anyone other +than You, whether those works are distributed or communicated to those persons +or made available as an application intended for use over a network. As an +express condition for the grants of license hereunder, You must treat any +External Deployment by You of the Original Work or a Derivative Work as a +distribution under section 1(c). + +6. **Attribution Rights.** You must retain, in the Source Code of any +Derivative Works that You create, all copyright, patent, or trademark notices +from the Source Code of the Original Work, as well as any notices of licensing +and any descriptive text identified therein as an "Attribution Notice." You +must cause the Source Code for any Derivative Works that You create to carry a +prominent Attribution Notice reasonably calculated to inform recipients that +You have modified the Original Work. + +7. **Warranty of Provenance and Disclaimer of Warranty.** Licensor warrants +that the copyright in and to the Original Work and the patent rights granted +herein by Licensor are owned by the Licensor or are sublicensed to You under +the terms of this License with the permission of the contributor(s) of those +copyrights and patent rights. Except as expressly stated in the immediately +preceding sentence, the Original Work is provided under this License on an "AS +IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without +limitation, the warranties of non-infringement, merchantability or fitness for +a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS +WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this +License. No license to the Original Work is granted by this License except +under this disclaimer. + +8. **Limitation of Liability.** Under no circumstances and under no legal +theory, whether in tort (including negligence), contract, or otherwise, shall +the Licensor be liable to anyone for any indirect, special, incidental, or +consequential damages of any character arising as a result of this License or +the use of the Original Work including, without limitation, damages for loss of +goodwill, work stoppage, computer failure or malfunction, or any and all other +commercial damages or losses. This limitation of liability shall not apply to +the extent applicable law prohibits such limitation. + +9. **Acceptance and Termination.** If, at any time, You expressly assented to +this License, that assent indicates your clear and irrevocable acceptance of +this License and all of its terms and conditions. If You distribute or +communicate copies of the Original Work or a Derivative Work, You must make a +reasonable effort under the circumstances to obtain the express assent of +recipients to the terms of this License. This License conditions your rights to +undertake the activities listed in Section 1, including your right to create +Derivative Works based upon the Original Work, and doing so without honoring +these terms and conditions is prohibited by copyright law and international +treaty. Nothing in this License is intended to affect copyright exceptions and +limitations (including 'fair use' or 'fair dealing'). This License shall +terminate immediately and You may no longer exercise any of the rights granted +to You by this License upon your failure to honor the conditions in Section +1(c). + +10. **Termination for Patent Action.** This License shall terminate +automatically and You may no longer exercise any of the rights granted to You +by this License as of the date You commence an action, including a cross-claim +or counterclaim, against Licensor or any licensee alleging that the Original +Work infringes a patent. This termination provision shall not apply for an +action alleging patent infringement by combinations of the Original Work with +other software or hardware. + +11. **Jurisdiction, Venue and Governing Law.** Any action or suit relating to +this License may be brought only in the courts of a jurisdiction wherein the +Licensor resides or in which Licensor conducts its primary business, and under +the laws of that jurisdiction excluding its conflict-of-law provisions. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any use of the Original Work outside the +scope of this License or after its termination shall be subject to the +requirements and penalties of copyright or patent law in the appropriate +jurisdiction. This section shall survive the termination of this License. + +12. **Attorneys' Fees.** In any action to enforce the terms of this License or +seeking damages relating thereto, the prevailing party shall be entitled to +recover its costs and expenses, including, without limitation, reasonable +attorneys' fees and costs incurred in connection with such action, including +any appeal of such action. This section shall survive the termination of this +License. + +13. **Miscellaneous.** If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent necessary to +make it enforceable. + +14. **Definition of "You" in This License.** "You" throughout this License, +whether in upper or lower case, means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this License. +For legal entities, "You" includes any entity that controls, is controlled by, +or is under common control with you. For 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. + +15. **Right to Use.** You may use the Original Work in all ways not otherwise +restricted or conditioned by this License or by law, and Licensor promises not +to interfere with or be responsible for such uses by You. + +16. **Modification of This License.** This License is Copyright © 2007 Zooko +Wilcox-O'Hearn. Permission is granted to copy, distribute, or communicate this +License without modification. Nothing in this License permits You to modify +this License as applied to the Original Work or to Derivative Works. However, +You may modify the text of this License and copy, distribute or communicate +your modified version (the "Modified License") and apply it to other original +works of authorship subject to the following conditions: (i) You may not +indicate in any way that your Modified License is the "Bootstrap Open Source +Licence" or "BOSL" and you may not use those names in the name of your Modified +License; and (ii) You must replace the notice specified in the first paragraph +above with the notice "Licensed under " or with +a notice of your own that is not confusingly similar to the notice in this +License. \ No newline at end of file diff --git a/src/circuit/gadget/utilities/cond_swap.rs b/halo2-gadgets/halo2_utilities/src/cond_swap.rs similarity index 95% rename from src/circuit/gadget/utilities/cond_swap.rs rename to halo2-gadgets/halo2_utilities/src/cond_swap.rs index 4d387cab..0fc11a38 100644 --- a/src/circuit/gadget/utilities/cond_swap.rs +++ b/halo2-gadgets/halo2_utilities/src/cond_swap.rs @@ -98,8 +98,8 @@ impl CondSwapInstructions for CondSwapChip { // Conditionally swap a let a_swapped = { let a_swapped = a - .value - .zip(b.value) + .value() + .zip(b.value()) .zip(swap) .map(|((a, b), swap)| if swap { b } else { a }); let a_swapped_cell = region.assign_advice( @@ -108,17 +108,14 @@ impl CondSwapInstructions for CondSwapChip { 0, || a_swapped.ok_or(Error::SynthesisError), )?; - CellValue { - cell: a_swapped_cell, - value: a_swapped, - } + CellValue::new(a_swapped_cell, a_swapped) }; // Conditionally swap b let b_swapped = { let b_swapped = a - .value - .zip(b.value) + .value() + .zip(b.value()) .zip(swap) .map(|((a, b), swap)| if swap { a } else { b }); let b_swapped_cell = region.assign_advice( @@ -127,10 +124,7 @@ impl CondSwapInstructions for CondSwapChip { 0, || b_swapped.ok_or(Error::SynthesisError), )?; - CellValue { - cell: b_swapped_cell, - value: b_swapped, - } + CellValue::new(b_swapped_cell, b_swapped) }; // Return swapped pair diff --git a/src/circuit/gadget/utilities/decompose_running_sum.rs b/halo2-gadgets/halo2_utilities/src/decompose_running_sum.rs similarity index 100% rename from src/circuit/gadget/utilities/decompose_running_sum.rs rename to halo2-gadgets/halo2_utilities/src/decompose_running_sum.rs diff --git a/halo2-gadgets/halo2_utilities/src/lib.rs b/halo2-gadgets/halo2_utilities/src/lib.rs new file mode 100644 index 00000000..77d9b849 --- /dev/null +++ b/halo2-gadgets/halo2_utilities/src/lib.rs @@ -0,0 +1,7 @@ +//! Utilities for halo2 circuits. +pub mod cond_swap; +pub mod utilities; +pub mod decompose_running_sum; +pub mod lookup_range_check; + +pub use utilities::*; \ No newline at end of file diff --git a/src/circuit/gadget/utilities/lookup_range_check.rs b/halo2-gadgets/halo2_utilities/src/lookup_range_check.rs similarity index 99% rename from src/circuit/gadget/utilities/lookup_range_check.rs rename to halo2-gadgets/halo2_utilities/src/lookup_range_check.rs index eba01f29..59f529c9 100644 --- a/src/circuit/gadget/utilities/lookup_range_check.rs +++ b/halo2-gadgets/halo2_utilities/src/lookup_range_check.rs @@ -3,9 +3,10 @@ use halo2::{ circuit::{Layouter, Region}, - plonk::{Advice, Column, ConstraintSystem, Error, Selector, TableColumn}, + plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector, TableColumn}, poly::Rotation, }; +use pasta_curves::arithmetic::FieldExt; use std::{convert::TryInto, marker::PhantomData}; use ff::PrimeFieldBits; diff --git a/src/circuit/gadget/utilities.rs b/halo2-gadgets/halo2_utilities/src/utilities.rs similarity index 99% rename from src/circuit/gadget/utilities.rs rename to halo2-gadgets/halo2_utilities/src/utilities.rs index 11cc0590..45f8fb30 100644 --- a/src/circuit/gadget/utilities.rs +++ b/halo2-gadgets/halo2_utilities/src/utilities.rs @@ -6,10 +6,6 @@ use halo2::{ use pasta_curves::arithmetic::FieldExt; use std::{array, convert::TryInto, ops::Range}; -pub(crate) mod cond_swap; -pub(crate) mod decompose_running_sum; -pub(crate) mod lookup_range_check; - /// A variable representing a field element. #[derive(Copy, Clone, Debug)] pub struct CellValue { diff --git a/halo2-gadgets/sinsemilla/.gitignore b/halo2-gadgets/sinsemilla/.gitignore new file mode 100644 index 00000000..173b9514 --- /dev/null +++ b/halo2-gadgets/sinsemilla/.gitignore @@ -0,0 +1,4 @@ +/target +**/*.rs.bk +Cargo.lock +.vscode diff --git a/halo2-gadgets/sinsemilla/Cargo.toml b/halo2-gadgets/sinsemilla/Cargo.toml new file mode 100644 index 00000000..ffb25888 --- /dev/null +++ b/halo2-gadgets/sinsemilla/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "sinsemilla" +version = "0.0.0" +authors = [ + "Sean Bowe ", + "Jack Grigg ", +] +edition = "2018" +description = "Sinsemilla hash function" +license-file = "LICENSE-BOSL" +repository = "https://github.com/zcash/orchard" +documentation = "https://docs.rs/orchard" +readme = "README.md" + +# We are not publishing this yet. +publish = false + +[target.'cfg(unix)'.dev-dependencies] +pprof = { version = "0.4.2", features = ["criterion", "flamegraph"] } + +[dependencies] +ecc = { package = "halo2_ecc", version = "0.0", path = "../halo2_ecc" } +ff = "0.10" +group = "0.10" +halo2 = { version = "0.0", optional = true } +pasta_curves = "0.1.2" +subtle = "2.3" +utilities = { package = "halo2_utilities", version = "0.0", path = "../halo2_utilities" } + +[[bench]] +name = "primitive" +harness = false diff --git a/halo2-gadgets/sinsemilla/LICENSE-BOSL b/halo2-gadgets/sinsemilla/LICENSE-BOSL new file mode 100644 index 00000000..d73baa19 --- /dev/null +++ b/halo2-gadgets/sinsemilla/LICENSE-BOSL @@ -0,0 +1,176 @@ +======================================================= +Bootstrap Open Source Licence ("BOSL") v. 1.0 +======================================================= +This Bootstrap Open Source Licence (the "License") applies to any original work +of authorship (the "Original Work") whose owner (the "Licensor") has placed the +following licensing notice adjacent to the copyright notice for the Original +Work: + +*Licensed under the Bootstrap Open Source Licence version 1.0* + +1. **Grant of Copyright License.** Licensor grants You a worldwide, + royalty-free, non-exclusive, sublicensable license, for the duration of the + copyright in the Original Work, to do the following: + + a. to reproduce the Original Work in copies, either alone or as part of + a collective work; + + b. to translate, adapt, alter, transform, modify, or arrange the + Original Work, thereby creating derivative works ("Derivative Works") + based upon the Original Work; + + c. to distribute or communicate copies of the Original Work and + Derivative Works to the public, provided that prior to any such + distribution or communication You first place a machine-readable copy + of the Source Code of the Original Work and such Derivative Works that + You intend to distribute or communicate in an information repository + reasonably calculated to permit inexpensive and convenient access + thereto by the public (“Information Repository”) for as long as You + continue to distribute or communicate said copies, accompanied by an + irrevocable offer to license said copies to the public free of charge + under this License, said offer valid starting no later than 12 months + after You first distribute or communicate said copies; + + d. to perform the Original Work publicly; and + + e. to display the Original Work publicly. + +2. **Grant of Patent License.** Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, under patent claims owned or controlled +by the Licensor that are embodied in the Original Work as furnished by the +Licensor, for the duration of the patents, to make, use, sell, offer for sale, +have made, and import the Original Work and Derivative Works. + +3. **Grant of Source Code License.** The "Source Code" for a work means the +preferred form of the work for making modifications to it and all available +documentation describing how to modify the work. Licensor agrees to provide a +machine-readable copy of the Source Code of the Original Work along with each +copy of the Original Work that Licensor distributes. Licensor reserves the +right to satisfy this obligation by placing a machine-readable copy of said +Source Code in an Information Repository for as long as Licensor continues to +distribute the Original Work. + +4. **Exclusions From License Grant.** Neither the names of Licensor, nor the +names of any contributors to the Original Work, nor any of their trademarks or +service marks, may be used to endorse or promote products derived from this +Original Work without express prior permission of the Licensor. Except as +expressly stated herein, nothing in this License grants any license to +Licensor's trademarks, copyrights, patents, trade secrets or any other +intellectual property. No patent license is granted to make, use, sell, offer +for sale, have made, or import embodiments of any patent claims other than the +licensed claims defined in Section 2. No license is granted to the trademarks +of Licensor even if such marks are included in the Original Work. Nothing in +this License shall be interpreted to prohibit Licensor from licensing under +terms different from this License any Original Work that Licensor otherwise +would have a right to license. + +5. **External Deployment.** The term "External Deployment" means the use, +distribution, or communication of the Original Work or Derivative Works in any +way such that the Original Work or Derivative Works may be used by anyone other +than You, whether those works are distributed or communicated to those persons +or made available as an application intended for use over a network. As an +express condition for the grants of license hereunder, You must treat any +External Deployment by You of the Original Work or a Derivative Work as a +distribution under section 1(c). + +6. **Attribution Rights.** You must retain, in the Source Code of any +Derivative Works that You create, all copyright, patent, or trademark notices +from the Source Code of the Original Work, as well as any notices of licensing +and any descriptive text identified therein as an "Attribution Notice." You +must cause the Source Code for any Derivative Works that You create to carry a +prominent Attribution Notice reasonably calculated to inform recipients that +You have modified the Original Work. + +7. **Warranty of Provenance and Disclaimer of Warranty.** Licensor warrants +that the copyright in and to the Original Work and the patent rights granted +herein by Licensor are owned by the Licensor or are sublicensed to You under +the terms of this License with the permission of the contributor(s) of those +copyrights and patent rights. Except as expressly stated in the immediately +preceding sentence, the Original Work is provided under this License on an "AS +IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without +limitation, the warranties of non-infringement, merchantability or fitness for +a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS +WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this +License. No license to the Original Work is granted by this License except +under this disclaimer. + +8. **Limitation of Liability.** Under no circumstances and under no legal +theory, whether in tort (including negligence), contract, or otherwise, shall +the Licensor be liable to anyone for any indirect, special, incidental, or +consequential damages of any character arising as a result of this License or +the use of the Original Work including, without limitation, damages for loss of +goodwill, work stoppage, computer failure or malfunction, or any and all other +commercial damages or losses. This limitation of liability shall not apply to +the extent applicable law prohibits such limitation. + +9. **Acceptance and Termination.** If, at any time, You expressly assented to +this License, that assent indicates your clear and irrevocable acceptance of +this License and all of its terms and conditions. If You distribute or +communicate copies of the Original Work or a Derivative Work, You must make a +reasonable effort under the circumstances to obtain the express assent of +recipients to the terms of this License. This License conditions your rights to +undertake the activities listed in Section 1, including your right to create +Derivative Works based upon the Original Work, and doing so without honoring +these terms and conditions is prohibited by copyright law and international +treaty. Nothing in this License is intended to affect copyright exceptions and +limitations (including 'fair use' or 'fair dealing'). This License shall +terminate immediately and You may no longer exercise any of the rights granted +to You by this License upon your failure to honor the conditions in Section +1(c). + +10. **Termination for Patent Action.** This License shall terminate +automatically and You may no longer exercise any of the rights granted to You +by this License as of the date You commence an action, including a cross-claim +or counterclaim, against Licensor or any licensee alleging that the Original +Work infringes a patent. This termination provision shall not apply for an +action alleging patent infringement by combinations of the Original Work with +other software or hardware. + +11. **Jurisdiction, Venue and Governing Law.** Any action or suit relating to +this License may be brought only in the courts of a jurisdiction wherein the +Licensor resides or in which Licensor conducts its primary business, and under +the laws of that jurisdiction excluding its conflict-of-law provisions. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any use of the Original Work outside the +scope of this License or after its termination shall be subject to the +requirements and penalties of copyright or patent law in the appropriate +jurisdiction. This section shall survive the termination of this License. + +12. **Attorneys' Fees.** In any action to enforce the terms of this License or +seeking damages relating thereto, the prevailing party shall be entitled to +recover its costs and expenses, including, without limitation, reasonable +attorneys' fees and costs incurred in connection with such action, including +any appeal of such action. This section shall survive the termination of this +License. + +13. **Miscellaneous.** If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent necessary to +make it enforceable. + +14. **Definition of "You" in This License.** "You" throughout this License, +whether in upper or lower case, means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this License. +For legal entities, "You" includes any entity that controls, is controlled by, +or is under common control with you. For 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. + +15. **Right to Use.** You may use the Original Work in all ways not otherwise +restricted or conditioned by this License or by law, and Licensor promises not +to interfere with or be responsible for such uses by You. + +16. **Modification of This License.** This License is Copyright © 2007 Zooko +Wilcox-O'Hearn. Permission is granted to copy, distribute, or communicate this +License without modification. Nothing in this License permits You to modify +this License as applied to the Original Work or to Derivative Works. However, +You may modify the text of this License and copy, distribute or communicate +your modified version (the "Modified License") and apply it to other original +works of authorship subject to the following conditions: (i) You may not +indicate in any way that your Modified License is the "Bootstrap Open Source +Licence" or "BOSL" and you may not use those names in the name of your Modified +License; and (ii) You must replace the notice specified in the first paragraph +above with the notice "Licensed under " or with +a notice of your own that is not confusingly similar to the notice in this +License. \ No newline at end of file diff --git a/benches/primitives.rs b/halo2-gadgets/sinsemilla/benches/primitive.rs similarity index 73% rename from benches/primitives.rs rename to halo2-gadgets/sinsemilla/benches/primitive.rs index df6747b5..f2e3be7b 100644 --- a/benches/primitives.rs +++ b/halo2-gadgets/sinsemilla/benches/primitive.rs @@ -2,10 +2,7 @@ use std::array; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use ff::Field; -use orchard::primitives::{ - poseidon::{self, ConstantLength, P128Pow5T3}, - sinsemilla, -}; +use sinsemilla::primitive; use pasta_curves::pallas; #[cfg(unix)] @@ -16,20 +13,10 @@ fn bench_primitives(c: &mut Criterion) { let mut rng = OsRng; { - let mut group = c.benchmark_group("Poseidon"); + let mut group = c.benchmark_group("Primitiprimitive"); - let message = [pallas::Base::random(rng), pallas::Base::random(rng)]; - - group.bench_function("2-to-1", |b| { - b.iter(|| poseidon::Hash::init(P128Pow5T3, ConstantLength).hash(message)) - }); - } - - { - let mut group = c.benchmark_group("Sinsemilla"); - - let hasher = sinsemilla::HashDomain::new("hasher"); - let committer = sinsemilla::CommitDomain::new("committer"); + let hasher = primitive::HashDomain::new("hasher"); + let committer = primitive::CommitDomain::new("committer"); let bits: Vec = (0..1086).map(|_| rng.gen()).collect(); let r = pallas::Scalar::random(rng); diff --git a/src/circuit/gadget/sinsemilla/chip.rs b/halo2-gadgets/sinsemilla/src/chip.rs similarity index 96% rename from src/circuit/gadget/sinsemilla/chip.rs rename to halo2-gadgets/sinsemilla/src/chip.rs index 457972bb..7c3b9200 100644 --- a/src/circuit/gadget/sinsemilla/chip.rs +++ b/halo2-gadgets/sinsemilla/src/chip.rs @@ -1,5 +1,6 @@ use super::{ message::{Message, MessagePiece}, +<<<<<<< HEAD:src/circuit/gadget/sinsemilla/chip.rs CommitDomains, HashDomains, SinsemillaInstructions, }; use crate::{ @@ -8,7 +9,13 @@ use crate::{ utilities::{lookup_range_check::LookupRangeCheckConfig, CellValue, Var}, }, primitives::sinsemilla, +======= + gadget::{CommitDomains, HashDomains, SinsemillaInstructions}, + primitive as sinsemilla +>>>>>>> b48c9047... Create halo2-gadgets workspace.:halo2-gadgets/sinsemilla/src/chip.rs }; +use ecc::{chip::EccPoint, gadget::FixedPoints}; +use utilities::{lookup_range_check::LookupRangeCheckConfig, CellValue, Var}; use std::marker::PhantomData; use halo2::{ diff --git a/src/circuit/gadget/sinsemilla/chip/generator_table.rs b/halo2-gadgets/sinsemilla/src/chip/generator_table.rs similarity index 98% rename from src/circuit/gadget/sinsemilla/chip/generator_table.rs rename to halo2-gadgets/sinsemilla/src/chip/generator_table.rs index 9c85c1af..f11c259b 100644 --- a/src/circuit/gadget/sinsemilla/chip/generator_table.rs +++ b/halo2-gadgets/sinsemilla/src/chip/generator_table.rs @@ -1,4 +1,4 @@ -use crate::primitives::sinsemilla::{self, SINSEMILLA_S}; +use crate::primitive::{self as sinsemilla, SINSEMILLA_S}; use halo2::{ circuit::Layouter, plonk::{ConstraintSystem, Error, Expression, TableColumn}, diff --git a/src/circuit/gadget/sinsemilla/chip/hash_to_point.rs b/halo2-gadgets/sinsemilla/src/chip/hash_to_point.rs similarity index 98% rename from src/circuit/gadget/sinsemilla/chip/hash_to_point.rs rename to halo2-gadgets/sinsemilla/src/chip/hash_to_point.rs index da1c1cb6..f57c90b8 100644 --- a/src/circuit/gadget/sinsemilla/chip/hash_to_point.rs +++ b/halo2-gadgets/sinsemilla/src/chip/hash_to_point.rs @@ -1,8 +1,8 @@ -use super::super::{CommitDomains, HashDomains, SinsemillaInstructions}; -use super::{CellValue, NonIdentityEccPoint, SinsemillaChip, Var}; +use crate::gadget::{CommitDomains, HashDomains, SinsemillaInstructions}; +use super::{CellValue, EccPoint, NonIdentityEccPoint, SinsemillaChip, Var}; -use crate::circuit::gadget::ecc::FixedPoints; -use crate::primitives::sinsemilla::{self, lebs2ip_k, INV_TWO_POW_K, SINSEMILLA_S}; +use ecc::gadget::FixedPoints; +use crate::primitive::{self as sinsemilla, lebs2ip_k, INV_TWO_POW_K, SINSEMILLA_S}; use halo2::{ circuit::{Chip, Region}, plonk::Error, diff --git a/src/circuit/gadget/sinsemilla.rs b/halo2-gadgets/sinsemilla/src/gadget.rs similarity index 97% rename from src/circuit/gadget/sinsemilla.rs rename to halo2-gadgets/sinsemilla/src/gadget.rs index bf0a626d..2fcac1c4 100644 --- a/src/circuit/gadget/sinsemilla.rs +++ b/halo2-gadgets/sinsemilla/src/gadget.rs @@ -1,17 +1,11 @@ //! Gadget and chips for the Sinsemilla hash function. -use crate::circuit::gadget::{ - ecc::{self, EccInstructions}, - utilities::Var, -}; +use ecc::gadget::{self as Ecc, EccInstructions}; +use utilities::Var; use ff::PrimeField; use halo2::{circuit::Layouter, plonk::Error}; use pasta_curves::arithmetic::{CurveAffine, FieldExt}; use std::{convert::TryInto, fmt::Debug}; -pub mod chip; -pub mod merkle; -mod message; - /// The set of circuit instructions required to use the [`Sinsemilla`](https://zcash.github.io/halo2/design/gadgets/sinsemilla.html) gadget. /// This trait is bounded on two constant parameters: `K`, the number of bits /// in each word accepted by the Sinsemilla hash, and `MAX_WORDS`, the maximum @@ -283,11 +277,11 @@ where &self, layouter: impl Layouter, message: Message, - ) -> Result<(ecc::NonIdentityPoint, Vec), Error> { + ) -> Result<(Ecc::NonIdentityPoint, Vec), Error> { assert_eq!(self.sinsemilla_chip, message.chip); self.sinsemilla_chip .hash_to_point(layouter, self.Q, message.inner) - .map(|(point, zs)| (ecc::NonIdentityPoint::from_inner(self.ecc_chip.clone(), point), zs)) + .map(|(point, zs)| (Ecc::NonIdentityPoint::from_inner(self.ecc_chip.clone(), point), zs)) } /// $\mathsf{SinsemillaHash}$ from [§ 5.4.1.9][concretesinsemillahash]. @@ -298,7 +292,7 @@ where &self, layouter: impl Layouter, message: Message, - ) -> Result<(ecc::X, Vec), Error> { + ) -> Result<(Ecc::X, Vec), Error> { assert_eq!(self.sinsemilla_chip, message.chip); let (p, zs) = self.hash_to_point(layouter, message)?; Ok((p.extract_p(), zs)) @@ -341,7 +335,7 @@ pub struct CommitDomain< + Eq, { M: HashDomain, - R: ecc::FixedPoint, + R: Ecc::FixedPoint, } impl @@ -365,7 +359,7 @@ where ) -> Self { CommitDomain { M: HashDomain::new(sinsemilla_chip, ecc_chip.clone(), &domain.hash_domain()), - R: ecc::FixedPoint::from_inner(ecc_chip, domain.r()), + R: Ecc::FixedPoint::from_inner(ecc_chip, domain.r()), } } @@ -378,13 +372,7 @@ where mut layouter: impl Layouter, message: Message, r: Option, - ) -> Result< - ( - ecc::Point, - Vec, - ), - Error, - > { + ) -> Result<(Ecc::Point, Vec), Error> { assert_eq!(self.M.sinsemilla_chip, message.chip); let (blind, _) = self.R.mul(layouter.namespace(|| "[r] R"), r)?; let (p, zs) = self.M.hash_to_point(layouter.namespace(|| "M"), message)?; @@ -401,7 +389,7 @@ where mut layouter: impl Layouter, message: Message, r: Option, - ) -> Result<(ecc::X, Vec), Error> { + ) -> Result<(Ecc::X, Vec), Error> { assert_eq!(self.M.sinsemilla_chip, message.chip); let (p, zs) = self.commit(layouter.namespace(|| "commit"), message, r)?; Ok((p.extract_p(), zs)) @@ -423,7 +411,7 @@ mod tests { use crate::{ circuit::gadget::{ - ecc::{ + Ecc::{ chip::{EccChip, EccConfig}, NonIdentityPoint, }, diff --git a/halo2-gadgets/sinsemilla/src/lib.rs b/halo2-gadgets/sinsemilla/src/lib.rs new file mode 100644 index 00000000..43a6c3a6 --- /dev/null +++ b/halo2-gadgets/sinsemilla/src/lib.rs @@ -0,0 +1,10 @@ +//! Gadget, chips, and primitives for the Sinsemilla hash function. +#[cfg(feature = "halo2")] +pub mod gadget; +#[cfg(feature = "halo2")] +pub mod chip; +#[cfg(feature = "halo2")] +mod message; +#[cfg(feature = "halo2")] +pub mod merkle; +pub mod primitive; diff --git a/src/circuit/gadget/sinsemilla/merkle.rs b/halo2-gadgets/sinsemilla/src/merkle.rs similarity index 95% rename from src/circuit/gadget/sinsemilla/merkle.rs rename to halo2-gadgets/sinsemilla/src/merkle.rs index e9c1a57c..2b2aeeee 100644 --- a/src/circuit/gadget/sinsemilla/merkle.rs +++ b/halo2-gadgets/sinsemilla/src/merkle.rs @@ -4,16 +4,15 @@ use halo2::{ }; use pasta_curves::arithmetic::CurveAffine; -use crate::circuit::gadget::{ - sinsemilla::{HashDomains, SinsemillaInstructions}, - utilities::{ - cond_swap::CondSwapInstructions, gen_const_array, transpose_option_array, - UtilitiesInstructions, - }, +use crate::gadget::{HashDomains, SinsemillaInstructions}; +use utilities::{ + cond_swap::CondSwapInstructions, gen_const_array, transpose_option_array, + UtilitiesInstructions, }; + use std::iter; -pub(in crate::circuit) mod chip; +pub mod chip; /// SWU hash-to-curve personalization for the Merkle CRH generator pub const MERKLE_CRH_PERSONALIZATION: &str = "z.cash:Orchard-MerkleCRH"; @@ -74,12 +73,12 @@ pub struct MerklePath< > where MerkleChip: MerkleInstructions + Clone, { - pub(in crate::circuit) chip_1: MerkleChip, - pub(in crate::circuit) chip_2: MerkleChip, - pub(in crate::circuit) domain: MerkleChip::HashDomains, - pub(in crate::circuit) leaf_pos: Option, + pub(crate) chip_1: MerkleChip, + pub(crate) chip_2: MerkleChip, + pub(crate) domain: MerkleChip::HashDomains, + pub(crate) leaf_pos: Option, // The Merkle path is ordered from leaves to root. - pub(in crate::circuit) path: Option<[C::Base; PATH_LENGTH]>, + pub(crate) path: Option<[C::Base; PATH_LENGTH]>, } #[allow(non_snake_case)] @@ -94,7 +93,7 @@ where MerkleChip: MerkleInstructions + Clone, { /// Calculates the root of the tree containing the given leaf at this Merkle path. - pub(in crate::circuit) fn calculate_root( + pub(crate) fn calculate_root( &self, mut layouter: impl Layouter, leaf: MerkleChip::Var, diff --git a/src/circuit/gadget/sinsemilla/merkle/chip.rs b/halo2-gadgets/sinsemilla/src/merkle/chip.rs similarity index 97% rename from src/circuit/gadget/sinsemilla/merkle/chip.rs rename to halo2-gadgets/sinsemilla/src/merkle/chip.rs index f4fafd27..762ac71f 100644 --- a/src/circuit/gadget/sinsemilla/merkle/chip.rs +++ b/halo2-gadgets/sinsemilla/src/merkle/chip.rs @@ -1,3 +1,4 @@ +//! Chip instantiating a Merkle hash using Sinsemilla. use halo2::{ circuit::{Chip, Layouter}, plonk::{Advice, Column, ConstraintSystem, Error, Selector}, @@ -6,21 +7,16 @@ use halo2::{ use pasta_curves::{arithmetic::FieldExt, pallas}; use super::{MerkleInstructions, L_ORCHARD_BASE, MERKLE_DEPTH_ORCHARD}; - +use ecc::gadget::FixedPoints; use crate::{ - circuit::gadget::{ - ecc::FixedPoints, - sinsemilla::{ - chip::{SinsemillaChip, SinsemillaConfig}, - CommitDomains, HashDomains, SinsemillaInstructions, - }, - utilities::{ - bitrange_subset, - cond_swap::{CondSwapChip, CondSwapConfig, CondSwapInstructions}, - copy, CellValue, UtilitiesInstructions, Var, - }, - }, - primitives::sinsemilla, + chip::{SinsemillaChip, SinsemillaConfig}, + gadget::{CommitDomains, HashDomains, SinsemillaInstructions}, + primitive as sinsemilla +}; +use utilities::{ + bitrange_subset, + cond_swap::{CondSwapChip, CondSwapConfig, CondSwapInstructions}, + copy, CellValue, UtilitiesInstructions, Var, }; use std::array; diff --git a/src/circuit/gadget/sinsemilla/message.rs b/halo2-gadgets/sinsemilla/src/message.rs similarity index 97% rename from src/circuit/gadget/sinsemilla/message.rs rename to halo2-gadgets/sinsemilla/src/message.rs index ac2926d9..2182817e 100644 --- a/src/circuit/gadget/sinsemilla/message.rs +++ b/halo2-gadgets/sinsemilla/src/message.rs @@ -1,5 +1,5 @@ //! Gadget and chips for the Sinsemilla hash function. -use crate::circuit::gadget::utilities::{CellValue, Var}; +use utilities::{CellValue, Var}; use ff::PrimeFieldBits; use halo2::{arithmetic::FieldExt, circuit::Cell}; use std::fmt::Debug; diff --git a/src/primitives/sinsemilla.rs b/halo2-gadgets/sinsemilla/src/primitive.rs similarity index 99% rename from src/primitives/sinsemilla.rs rename to halo2-gadgets/sinsemilla/src/primitive.rs index f6776b92..c6b272bc 100644 --- a/src/primitives/sinsemilla.rs +++ b/halo2-gadgets/sinsemilla/src/primitive.rs @@ -1,8 +1,7 @@ //! The Sinsemilla hash function and commitment scheme. use group::{Curve, Wnaf}; -use halo2::arithmetic::{CurveAffine, CurveExt}; -use pasta_curves::pallas; +use pasta_curves::{arithmetic::{CurveAffine, CurveExt}, pallas}; use subtle::CtOption; mod addition; diff --git a/src/primitives/sinsemilla/addition.rs b/halo2-gadgets/sinsemilla/src/primitive/addition.rs similarity index 100% rename from src/primitives/sinsemilla/addition.rs rename to halo2-gadgets/sinsemilla/src/primitive/addition.rs diff --git a/src/primitives/sinsemilla/sinsemilla_s.rs b/halo2-gadgets/sinsemilla/src/primitive/sinsemilla_s.rs similarity index 100% rename from src/primitives/sinsemilla/sinsemilla_s.rs rename to halo2-gadgets/sinsemilla/src/primitive/sinsemilla_s.rs diff --git a/src/circuit.rs b/src/circuit.rs index dc6bb318..0b6e125c 100644 --- a/src/circuit.rs +++ b/src/circuit.rs @@ -26,37 +26,33 @@ use crate::{ nullifier::Nullifier, ExtractedNoteCommitment, }, - primitives::{ - poseidon::{self, ConstantLength}, - redpallas::{SpendAuth, VerificationKey}, - }, + primitives::redpallas::{SpendAuth, VerificationKey}, spec::NonIdentityPallasPoint, tree::{Anchor, MerkleHashOrchard}, value::{NoteValue, ValueCommitTrapdoor, ValueCommitment}, }; -use gadget::{ - ecc::{ - chip::{EccChip, EccConfig}, - FixedPoint, NonIdentityPoint, Point, +use ecc::{ + chip::{EccChip, EccConfig}, + gadget::{FixedPoint, NonIdentityPoint, Point}, +}; +use poseidon::{ + gadget::{Hash as PoseidonHash, Word}, + pow5t3::{Pow5T3Chip as PoseidonChip, Pow5T3Config as PoseidonConfig, StateWord}, + primitive::{ConstantLength, P128Pow5T3}, +}; +use sinsemilla::{ + chip::{SinsemillaChip, SinsemillaConfig}, + merkle::{ + chip::{MerkleChip, MerkleConfig}, + MerklePath, }, - poseidon::{ - Hash as PoseidonHash, Pow5T3Chip as PoseidonChip, Pow5T3Config as PoseidonConfig, - StateWord, Word, - }, - sinsemilla::{ - chip::{SinsemillaChip, SinsemillaConfig}, - merkle::{ - chip::{MerkleChip, MerkleConfig}, - MerklePath, - }, - }, - utilities::{copy, CellValue, UtilitiesInstructions, Var}, +}; +use utilities::{ + copy, lookup_range_check::LookupRangeCheckConfig, CellValue, UtilitiesInstructions, Var, }; use std::convert::TryInto; -use self::gadget::utilities::lookup_range_check::LookupRangeCheckConfig; - mod commit_ivk; pub(crate) mod gadget; mod note_commit; @@ -252,7 +248,7 @@ impl plonk::Circuit for Circuit { // Configuration for the Poseidon hash. let poseidon_config = PoseidonChip::configure( meta, - poseidon::P128Pow5T3, + P128Pow5T3, // We place the state columns after the partial_sbox column so that the // pad-and-add region can be layed out more efficiently. advices[6..9].try_into().unwrap(), @@ -507,9 +503,9 @@ impl plonk::Circuit for Circuit { || value.ok_or(plonk::Error::SynthesisError), )?; region.constrain_equal(var, message[i].cell())?; - Ok(Word::<_, _, poseidon::P128Pow5T3, 3, 2>::from_inner( - StateWord::new(var, value), - )) + Ok(Word::<_, _, P128Pow5T3, 3, 2>::from_inner(StateWord::new( + var, value, + ))) }; Ok([message_word(0)?, message_word(1)?]) diff --git a/src/circuit/commit_ivk.rs b/src/circuit/commit_ivk.rs index 7885e2dd..dcc4cf77 100644 --- a/src/circuit/commit_ivk.rs +++ b/src/circuit/commit_ivk.rs @@ -5,17 +5,13 @@ use halo2::{ }; use pasta_curves::{arithmetic::FieldExt, pallas}; -use crate::{ - circuit::gadget::{ - ecc::{chip::EccChip, X}, - sinsemilla::{ - chip::{SinsemillaChip, SinsemillaConfig}, - CommitDomain, Message, MessagePiece, - }, - utilities::{bitrange_subset, bool_check, copy, CellValue, Var}, - }, - constants::{OrchardCommitDomains, OrchardFixedBases, OrchardHashDomains, T_P}, +use crate::constants::{OrchardCommitDomains, OrchardFixedBases, OrchardHashDomains, T_P}; +use ecc::{chip::EccChip, gadget::X}; +use sinsemilla::{ + chip::{SinsemillaChip, SinsemillaConfig}, + gadget::{CommitDomain, Message, MessagePiece}, }; +use utilities::{bitrange_subset, bool_check, copy, CellValue, Var}; #[derive(Clone, Debug)] pub struct CommitIvkConfig { diff --git a/src/circuit/gadget.rs b/src/circuit/gadget.rs index 9f2455bb..bcc6b47f 100644 --- a/src/circuit/gadget.rs +++ b/src/circuit/gadget.rs @@ -2,14 +2,9 @@ use pasta_curves::pallas; use crate::constants::{OrchardCommitDomains, OrchardFixedBases, OrchardHashDomains}; use ecc::chip::EccChip; -use poseidon::Pow5T3Chip as PoseidonChip; +use poseidon::chip::Pow5T3Chip as PoseidonChip; use sinsemilla::{chip::SinsemillaChip, merkle::chip::MerkleChip}; -pub(crate) mod ecc; -pub(crate) mod poseidon; -pub(crate) mod sinsemilla; -pub(crate) mod utilities; - impl super::Config { pub(super) fn ecc_chip(&self) -> EccChip { EccChip::construct(self.ecc_config.clone()) diff --git a/src/circuit/note_commit.rs b/src/circuit/note_commit.rs index b4d08ba1..396ccd6f 100644 --- a/src/circuit/note_commit.rs +++ b/src/circuit/note_commit.rs @@ -5,20 +5,17 @@ use halo2::{ }; use pasta_curves::{arithmetic::FieldExt, pallas}; -use crate::{ - circuit::gadget::{ - ecc::{ - chip::{EccChip, NonIdentityEccPoint}, - Point, - }, - sinsemilla::{ - chip::{SinsemillaChip, SinsemillaConfig}, - CommitDomain, Message, MessagePiece, - }, - utilities::{bitrange_subset, bool_check, copy, CellValue, Var}, - }, - constants::{OrchardCommitDomains, OrchardFixedBases, OrchardHashDomains, T_P}, +use ecc::{ + chip::{EccChip, NonIdentityEccPoint}, + gadget::Point, }; +use sinsemilla::{ + chip::{SinsemillaChip, SinsemillaConfig}, + gadget::{CommitDomain, Message, MessagePiece}, +}; +use utilities::{bitrange_subset, bool_check, copy, CellValue, Var}; + +use crate::constants::{OrchardCommitDomains, OrchardFixedBases, OrchardHashDomains, T_P}; /* diff --git a/src/constants.rs b/src/constants.rs index 99752f5d..bcb1870e 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -3,8 +3,8 @@ pub mod fixed_bases; pub mod sinsemilla; pub mod util; +pub use self::sinsemilla::{OrchardCommitDomains, OrchardHashDomains}; pub use fixed_bases::OrchardFixedBases; -pub use sinsemilla::{OrchardCommitDomains, OrchardHashDomains}; pub use util::{evaluate, gen_const_array}; /// $\mathsf{MerkleDepth^{Orchard}}$ diff --git a/src/constants/fixed_bases.rs b/src/constants/fixed_bases.rs index 862fe09d..708202b0 100644 --- a/src/constants/fixed_bases.rs +++ b/src/constants/fixed_bases.rs @@ -1,6 +1,6 @@ //! Orchard fixed bases. use super::{L_ORCHARD_SCALAR, L_VALUE}; -use crate::circuit::gadget::ecc::FixedPoints; +use ecc::gadget::FixedPoints; use arrayvec::ArrayVec; use ff::Field; diff --git a/src/constants/fixed_bases/commit_ivk_r.rs b/src/constants/fixed_bases/commit_ivk_r.rs index c0e0b508..c4cdd2a0 100644 --- a/src/constants/fixed_bases/commit_ivk_r.rs +++ b/src/constants/fixed_bases/commit_ivk_r.rs @@ -2934,12 +2934,12 @@ mod tests { test_lagrange_coeffs, test_zs_and_us, COMMIT_IVK_PERSONALIZATION, NUM_WINDOWS, }; use super::*; - use crate::primitives::sinsemilla::CommitDomain; use group::Curve; use pasta_curves::{ arithmetic::{CurveAffine, FieldExt}, pallas, }; + use sinsemilla::primitive::CommitDomain; #[test] fn generator() { diff --git a/src/constants/fixed_bases/note_commit_r.rs b/src/constants/fixed_bases/note_commit_r.rs index 4a12734d..efaf104b 100644 --- a/src/constants/fixed_bases/note_commit_r.rs +++ b/src/constants/fixed_bases/note_commit_r.rs @@ -2934,12 +2934,12 @@ mod tests { test_lagrange_coeffs, test_zs_and_us, NOTE_COMMITMENT_PERSONALIZATION, NUM_WINDOWS, }; use super::*; - use crate::primitives::sinsemilla::CommitDomain; use group::Curve; use pasta_curves::{ arithmetic::{CurveAffine, FieldExt}, pallas, }; + use sinsemilla::primitive::CommitDomain; #[test] fn generator() { diff --git a/src/constants/sinsemilla.rs b/src/constants/sinsemilla.rs index dd7b2d7c..13cc6a55 100644 --- a/src/constants/sinsemilla.rs +++ b/src/constants/sinsemilla.rs @@ -1,7 +1,7 @@ //! Sinsemilla generators use super::OrchardFixedBases; -use crate::circuit::gadget::sinsemilla::{CommitDomains, HashDomains}; use crate::spec::i2lebsp; +use sinsemilla::gadget::{CommitDomains, HashDomains}; use pasta_curves::{ arithmetic::{CurveAffine, FieldExt}, @@ -146,7 +146,7 @@ mod tests { fixed_bases::{COMMIT_IVK_PERSONALIZATION, NOTE_COMMITMENT_PERSONALIZATION}, sinsemilla::MERKLE_CRH_PERSONALIZATION, }; - use crate::primitives::sinsemilla::{CommitDomain, HashDomain}; + use sinsemilla::primitive::{CommitDomain, HashDomain}; use ff::PrimeField; use group::Curve; diff --git a/src/note/commitment.rs b/src/note/commitment.rs index 825bd4d6..3f46a05f 100644 --- a/src/note/commitment.rs +++ b/src/note/commitment.rs @@ -7,10 +7,10 @@ use subtle::{ConstantTimeEq, CtOption}; use crate::{ constants::{fixed_bases::NOTE_COMMITMENT_PERSONALIZATION, L_ORCHARD_BASE}, - primitives::sinsemilla, spec::extract_p, value::NoteValue, }; +use sinsemilla::primitive as sinsemilla; #[derive(Debug)] pub(crate) struct NoteCommitTrapdoor(pub(super) pallas::Scalar); diff --git a/src/primitives.rs b/src/primitives.rs index 25e8142f..42a01fe4 100644 --- a/src/primitives.rs +++ b/src/primitives.rs @@ -4,6 +4,4 @@ // - EphemeralPublicKey // - EphemeralSecretKey -pub mod poseidon; pub mod redpallas; -pub mod sinsemilla; diff --git a/src/spec.rs b/src/spec.rs index 44253a5a..eaf2c96f 100644 --- a/src/spec.rs +++ b/src/spec.rs @@ -10,13 +10,12 @@ use halo2::arithmetic::{CurveAffine, CurveExt, FieldExt}; use pasta_curves::pallas; use subtle::{ConditionallySelectable, CtOption}; -use crate::{ - constants::{ - fixed_bases::COMMIT_IVK_PERSONALIZATION, util::gen_const_array, - KEY_DIVERSIFICATION_PERSONALIZATION, L_ORCHARD_BASE, - }, - primitives::{poseidon, sinsemilla}, +use crate::constants::{ + fixed_bases::COMMIT_IVK_PERSONALIZATION, util::gen_const_array, + KEY_DIVERSIFICATION_PERSONALIZATION, L_ORCHARD_BASE, }; +use poseidon::primitive as poseidon; +use sinsemilla::primitive as sinsemilla; mod prf_expand; pub(crate) use prf_expand::PrfExpand; diff --git a/src/tree.rs b/src/tree.rs index d04262db..77da78f3 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -7,10 +7,10 @@ use crate::{ MERKLE_DEPTH_ORCHARD, }, note::commitment::ExtractedNoteCommitment, - primitives::sinsemilla::HashDomain, }; use incrementalmerkletree::{Altitude, Hashable}; use pasta_curves::{arithmetic::FieldExt, pallas}; +use sinsemilla::primitive::HashDomain; use ff::{Field, PrimeField, PrimeFieldBits}; use lazy_static::lazy_static;