├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── poseidon-base ├── Cargo.toml └── src │ ├── hash.rs │ ├── lib.rs │ ├── params.rs │ ├── primitives.rs │ └── primitives │ ├── binops.rs │ ├── bn256 │ ├── fp.rs │ └── mod.rs │ ├── fields.rs │ ├── grain.rs │ ├── mds.rs │ ├── p128pow5t3.rs │ ├── p128pow5t3_compact.rs │ └── pasta │ ├── fp.rs │ ├── mod.rs │ └── test_vectors.rs ├── poseidon-circuit ├── Cargo.toml ├── benches │ └── hash.rs ├── src │ ├── hash.rs │ ├── lib.rs │ ├── poseidon.rs │ └── poseidon │ │ ├── pow5.rs │ │ ├── septidon.rs │ │ └── septidon │ │ ├── control.rs │ │ ├── full_round.rs │ │ ├── instruction.rs │ │ ├── loop_chip.rs │ │ ├── params.rs │ │ ├── septidon_chip.rs │ │ ├── septuple_round.rs │ │ ├── state.rs │ │ ├── tests.rs │ │ ├── transition_round.rs │ │ └── util.rs └── tests │ └── hash_proving.rs ├── rust-toolchain └── spec ├── Septidon.png ├── hash-table.md ├── septidon.md └── types.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | /layouts -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "poseidon-circuit", 4 | "poseidon-base" 5 | ] 6 | resolver = "2" 7 | 8 | [workspace.dependencies] 9 | bencher = "0.1" 10 | bitvec = "1" 11 | ff = "0.13" 12 | halo2curves = { version = "0.1.0", features = [ "derive_serde" ] } 13 | halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2022_09_10" } 14 | itertools = "0.13.0" # for compatibility msrv 1.75 15 | lazy_static = "1.4" 16 | log = "0.4" 17 | once_cell = "1.19" 18 | rand = "0.8" 19 | rand_chacha = "0.3.0" 20 | rand_xorshift = "0.3" 21 | subtle = "2" 22 | thiserror = "1.0" 23 | 24 | [profile.test] 25 | opt-level = 3 26 | debug-assertions = true 27 | 28 | [patch."https://github.com/privacy-scaling-explorations/halo2.git"] 29 | halo2_proofs = { git = "https://github.com/scroll-tech/halo2.git", branch = "v1.0" } 30 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2022 The Scroll Foundation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # poseidon-circuit 2 | 3 | Poseidon hash circuit and primitives. It integrated several poseidon hash schemes from [zcash](https://github.com/zcash/halo2/tree/main/halo2_gadgets/src/poseidon) and [iden3](https://github.com/iden3/go-iden3-crypto/tree/master/poseidon) and support sponge progress for hashing messages in any length. 4 | 5 | 6 | ## Usage 7 | 8 | To connect to the hash circuit, see `spec/hash-table.md`. 9 | 10 | The circuit code can be implied with field which have satisified `Hashable` trait and currently only `poseidon-circuit::Bn256Fr` (the alias of `halo2_proofs::halo2curves::bn256::Fr`) has satisified this trait. 11 | 12 | The circuit type under `hash::HashCircuit` prove poseidon hash progress base on permutation with 3 fields and a 2 fields rate. You also need to set a fixed step size for proving message hashing with variable length. A message has to be complied with an initial capacity size and for each sponge step the capacity would be substracted by the fixed step size. In the final step the capacity has to be equal or less than the fixed step. 13 | 14 | For example, when we hashing a message with 19 fields: 15 | 16 | 1. You can use a circuit with fixed step size as `2`, and set the initialized capacity as `19` (i.e. the field len of input message). In each sponge progess the capacity is reduced by `2` and in final step it became `1`; 17 | 18 | 2. You can use a circuit with fixed step size as `32` and a initialized capacity between `298` to `320`. 19 | 20 | The `DEFAULT_STEP` being decalred in the crate is `32`. 21 | 22 | 23 | ## Installation 24 | 25 | Add `Cargo.toml` under `[dependencies]`: 26 | 27 | ```toml 28 | [dependencies] 29 | poseidon-circuit = { git = "https://github.com/scroll-tech/poseidon-circuit.git" } 30 | ``` 31 | 32 | ## License 33 | 34 | Licensed under either of 35 | 36 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 37 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 38 | 39 | at your option. 40 | -------------------------------------------------------------------------------- /poseidon-base/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "poseidon-base" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | lazy_static.workspace = true 8 | bitvec.workspace = true 9 | halo2curves.workspace = true 10 | once_cell.workspace = true 11 | 12 | subtle = { workspace = true, optional = true} 13 | 14 | [dev-dependencies] 15 | subtle.workspace = true 16 | 17 | [features] 18 | default = ["short"] 19 | short = [] 20 | test = ["subtle"] 21 | legacy = [] -------------------------------------------------------------------------------- /poseidon-base/src/hash.rs: -------------------------------------------------------------------------------- 1 | use crate::primitives::{CachedSpec, ConstantLengthIden3, Domain, Hash, Spec, VariableLengthIden3}; 2 | use halo2curves::bn256::Fr; 3 | use halo2curves::ff::FromUniformBytes; 4 | use once_cell::sync::OnceCell; 5 | 6 | #[cfg(not(feature = "short"))] 7 | mod chip_long { 8 | use crate::primitives::P128Pow5T3; 9 | 10 | /// The specified base hashable trait 11 | pub trait Hashablebase: crate::primitives::P128Pow5T3Constants {} 12 | /// Set the spec type as P128Pow5T3 13 | pub type HashSpec = P128Pow5T3; 14 | } 15 | 16 | #[cfg(feature = "short")] 17 | mod chip_short { 18 | use crate::primitives::P128Pow5T3Compact; 19 | 20 | /// The specified base hashable trait 21 | pub trait Hashablebase: crate::params::CachedConstants {} 22 | /// Set the spec type as P128Pow5T3Compact 23 | pub type HashSpec = P128Pow5T3Compact; 24 | } 25 | 26 | #[cfg(not(feature = "short"))] 27 | pub use chip_long::*; 28 | 29 | #[cfg(feature = "short")] 30 | pub use chip_short::*; 31 | 32 | /// the domain factor applied to var-len mode hash 33 | #[cfg(not(feature = "legacy"))] 34 | pub const HASHABLE_DOMAIN_SPEC: u128 = 0x10000000000000000; 35 | #[cfg(feature = "legacy")] 36 | pub const HASHABLE_DOMAIN_SPEC: u128 = 1; 37 | 38 | /// indicate an field can be hashed in merkle tree (2 Fields to 1 Field) 39 | pub trait Hashable: Hashablebase + FromUniformBytes<64> + Ord { 40 | /// the spec type used in circuit for this hashable field 41 | type SpecType: CachedSpec; 42 | /// the domain type used for hash calculation 43 | type DomainType: Domain; 44 | 45 | /// execute hash for any sequence of fields 46 | #[deprecated] 47 | fn hash(inp: [Self; 2]) -> Self { 48 | Self::hash_with_domain(inp, Self::ZERO) 49 | } 50 | 51 | /// execute hash for any sequence of fields, with domain being specified 52 | fn hash_with_domain(inp: [Self; 2], domain: Self) -> Self; 53 | /// obtain the rows consumed by each circuit block 54 | fn hash_block_size() -> usize { 55 | #[cfg(feature = "short")] 56 | { 57 | 1 + Self::SpecType::full_rounds() 58 | } 59 | #[cfg(not(feature = "short"))] 60 | { 61 | 1 + Self::SpecType::full_rounds() + (Self::SpecType::partial_rounds() + 1) / 2 62 | } 63 | } 64 | /// init a hasher used for hash 65 | fn hasher() -> Hash { 66 | Hash::::init() 67 | } 68 | } 69 | 70 | /// indicate an message stream constructed by the field can be hashed, commonly 71 | /// it just need to update the Domain 72 | pub trait MessageHashable: Hashable { 73 | /// the domain type used for message hash 74 | type DomainType: Domain; 75 | /// hash message, if cap is not provided, it use the basic spec: (len of msg * 2^64, or len of msg in legacy mode) 76 | fn hash_msg(msg: &[Self], cap: Option) -> Self; 77 | /// init a hasher used for hash message 78 | fn msg_hasher( 79 | ) -> Hash::SpecType, ::DomainType, 3, 2> { 80 | Hash::::SpecType, ::DomainType, 3, 2>::init() 81 | } 82 | } 83 | 84 | impl Hashablebase for Fr {} 85 | 86 | impl Hashable for Fr { 87 | type SpecType = HashSpec; 88 | type DomainType = ConstantLengthIden3<2>; 89 | 90 | fn hash_with_domain(inp: [Self; 2], domain: Self) -> Self { 91 | Self::hasher().hash(inp, domain) 92 | } 93 | 94 | fn hasher() -> Hash { 95 | static INIT: OnceCell< 96 | Hash::SpecType, ::DomainType, 3, 2>, 97 | > = OnceCell::new(); 98 | INIT.get_or_init(Hash::init).clone() 99 | } 100 | } 101 | 102 | impl MessageHashable for Fr { 103 | type DomainType = VariableLengthIden3; 104 | 105 | fn hash_msg(msg: &[Self], cap: Option) -> Self { 106 | Self::msg_hasher() 107 | .hash_with_cap(msg, cap.unwrap_or(msg.len() as u128 * HASHABLE_DOMAIN_SPEC)) 108 | } 109 | 110 | fn msg_hasher( 111 | ) -> Hash::SpecType, ::DomainType, 3, 2> { 112 | static INIT: OnceCell< 113 | Hash::SpecType, ::DomainType, 3, 2>, 114 | > = OnceCell::new(); 115 | INIT.get_or_init(Hash::init).clone() 116 | } 117 | } 118 | 119 | #[cfg(test)] 120 | mod tests { 121 | use super::*; 122 | 123 | #[test] 124 | fn test_lazy_init() { 125 | let _ = Fr::hasher(); 126 | let _ = Fr::msg_hasher(); 127 | 128 | let _ = Fr::hasher(); 129 | let _ = Fr::msg_hasher(); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /poseidon-base/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod hash; 2 | pub mod params; 3 | pub mod primitives; 4 | 5 | pub use hash::{Hashable, HASHABLE_DOMAIN_SPEC}; 6 | -------------------------------------------------------------------------------- /poseidon-base/src/params.rs: -------------------------------------------------------------------------------- 1 | use crate::primitives::{Mds as MdsT, P128Pow5T3Constants}; 2 | 3 | pub type Mds = MdsT; 4 | 5 | /// This is the base "hashable" type requirement for septidon 6 | pub trait CachedConstants: P128Pow5T3Constants { 7 | /// cached round constants 8 | fn cached_round_constants() -> &'static [[Self; 3]]; 9 | /// cached mds 10 | fn cached_mds() -> &'static Mds; 11 | /// cached inversed mds 12 | fn cached_mds_inv() -> &'static Mds; 13 | } 14 | 15 | mod bn254 { 16 | use super::{CachedConstants, Mds}; 17 | use crate::hash::HashSpec; 18 | use crate::primitives::{CachedSpec, P128Pow5T3Compact, Spec}; 19 | use ::halo2curves::bn256::Fr as F; 20 | use lazy_static::lazy_static; 21 | lazy_static! { 22 | // Cache the round constants and the MDS matrix (and unused inverse MDS matrix). 23 | static ref CONSTANTS: (Vec<[F; 3]>, Mds, Mds) = P128Pow5T3Compact::::constants(); 24 | } 25 | 26 | impl CachedConstants for F { 27 | fn cached_round_constants() -> &'static [[Self; 3]] { 28 | &CONSTANTS.0 29 | } 30 | fn cached_mds() -> &'static Mds { 31 | &CONSTANTS.1 32 | } 33 | fn cached_mds_inv() -> &'static Mds { 34 | &CONSTANTS.2 35 | } 36 | } 37 | 38 | impl CachedSpec for HashSpec { 39 | fn cached_round_constants() -> &'static [[F; 3]] { 40 | &CONSTANTS.0 41 | } 42 | fn cached_mds() -> &'static Mds { 43 | &CONSTANTS.1 44 | } 45 | fn cached_mds_inv() -> &'static Mds { 46 | &CONSTANTS.2 47 | } 48 | } 49 | } 50 | 51 | pub fn round_constant(index: usize) -> [F; 3] { 52 | F::cached_round_constants()[index] 53 | } 54 | 55 | pub fn mds() -> &'static Mds { 56 | F::cached_mds() 57 | } 58 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives.rs: -------------------------------------------------------------------------------- 1 | //! The Poseidon algebraic hash function. 2 | 3 | use std::convert::TryInto; 4 | use std::fmt; 5 | use std::iter; 6 | use std::marker::PhantomData; 7 | 8 | use halo2curves::ff::FromUniformBytes; 9 | 10 | pub(crate) mod grain; 11 | pub(crate) mod mds; 12 | 13 | // mod fields; 14 | // #[macro_use] 15 | // mod binops; 16 | 17 | pub mod bn256; 18 | #[cfg(any(test, feature = "test"))] 19 | pub mod pasta; 20 | 21 | //#[cfg(test)] 22 | //pub(crate) mod test_vectors; 23 | 24 | mod p128pow5t3; 25 | mod p128pow5t3_compact; 26 | 27 | pub use p128pow5t3::P128Pow5T3; 28 | pub use p128pow5t3::P128Pow5T3Constants; 29 | pub use p128pow5t3_compact::P128Pow5T3Compact; 30 | 31 | use grain::SboxType; 32 | 33 | /// The type used to hold permutation state. 34 | pub type State = [F; T]; 35 | 36 | /// The type used to hold sponge rate. 37 | pub type SpongeRate = [Option; RATE]; 38 | 39 | /// The type used to hold the MDS matrix and its inverse. 40 | pub type Mds = [[F; T]; T]; 41 | 42 | /// A specification for a Poseidon permutation. 43 | pub trait Spec + Ord, const T: usize, const RATE: usize>: 44 | Copy + fmt::Debug 45 | { 46 | /// The number of full rounds for this specification. 47 | /// 48 | /// This must be an even number. 49 | fn full_rounds() -> usize; 50 | 51 | /// The number of partial rounds for this specification. 52 | fn partial_rounds() -> usize; 53 | 54 | /// The S-box for this specification. 55 | fn sbox(val: F) -> F; 56 | 57 | /// Side-loaded index of the first correct and secure MDS that will be generated by 58 | /// the reference implementation. 59 | /// 60 | /// This is used by the default implementation of [`Spec::constants`]. If you are 61 | /// hard-coding the constants, you may leave this unimplemented. 62 | fn secure_mds() -> usize; 63 | 64 | /// Generates `(round_constants, mds, mds^-1)` corresponding to this specification. 65 | fn constants() -> (Vec<[F; T]>, Mds, Mds) { 66 | let r_f = Self::full_rounds(); 67 | let r_p = Self::partial_rounds(); 68 | 69 | let mut grain = grain::Grain::new(SboxType::Pow, T as u16, r_f as u16, r_p as u16); 70 | 71 | let round_constants = (0..(r_f + r_p)) 72 | .map(|_| { 73 | let mut rc_row = [F::ZERO; T]; 74 | for (rc, value) in rc_row 75 | .iter_mut() 76 | .zip((0..T).map(|_| grain.next_field_element())) 77 | { 78 | *rc = value; 79 | } 80 | rc_row 81 | }) 82 | .collect(); 83 | 84 | let (mds, mds_inv) = mds::generate_mds::(&mut grain, Self::secure_mds()); 85 | 86 | (round_constants, mds, mds_inv) 87 | } 88 | } 89 | 90 | pub trait CachedSpec + Ord, const T: usize, const RATE: usize>: 91 | Spec 92 | { 93 | fn cached_round_constants() -> &'static [[F; T]]; 94 | fn cached_mds() -> &'static Mds; 95 | fn cached_mds_inv() -> &'static Mds; 96 | } 97 | 98 | /// Runs the Poseidon permutation on the given state. 99 | pub fn permute< 100 | F: FromUniformBytes<64> + Ord, 101 | S: Spec, 102 | const T: usize, 103 | const RATE: usize, 104 | >( 105 | state: &mut State, 106 | mds: &Mds, 107 | round_constants: &[[F; T]], 108 | ) { 109 | let r_f = S::full_rounds() / 2; 110 | let r_p = S::partial_rounds(); 111 | 112 | let apply_mds = |state: &mut State| { 113 | let mut new_state = [F::ZERO; T]; 114 | // Matrix multiplication 115 | #[allow(clippy::needless_range_loop)] 116 | for i in 0..T { 117 | for j in 0..T { 118 | new_state[i] += mds[i][j] * state[j]; 119 | } 120 | } 121 | *state = new_state; 122 | }; 123 | 124 | let full_round = |state: &mut State, rcs: &[F; T]| { 125 | for (word, rc) in state.iter_mut().zip(rcs.iter()) { 126 | *word = S::sbox(*word + rc); 127 | } 128 | apply_mds(state); 129 | }; 130 | 131 | let part_round = |state: &mut State, rcs: &[F; T]| { 132 | for (word, rc) in state.iter_mut().zip(rcs.iter()) { 133 | *word += rc; 134 | } 135 | // In a partial round, the S-box is only applied to the first state word. 136 | state[0] = S::sbox(state[0]); 137 | apply_mds(state); 138 | }; 139 | 140 | iter::empty() 141 | .chain(iter::repeat(&full_round as &dyn Fn(&mut State, &[F; T])).take(r_f)) 142 | .chain(iter::repeat(&part_round as &dyn Fn(&mut State, &[F; T])).take(r_p)) 143 | .chain(iter::repeat(&full_round as &dyn Fn(&mut State, &[F; T])).take(r_f)) 144 | .zip(round_constants.iter()) 145 | .fold(state, |state, (round, rcs)| { 146 | round(state, rcs); 147 | state 148 | }); 149 | } 150 | 151 | fn poseidon_sponge< 152 | F: FromUniformBytes<64> + Ord, 153 | S: Spec, 154 | const T: usize, 155 | const RATE: usize, 156 | >( 157 | state: &mut State, 158 | input: Option<(&Absorbing, usize)>, 159 | mds_matrix: &Mds, 160 | round_constants: &[[F; T]], 161 | ) -> Squeezing { 162 | if let Some((Absorbing(input), layout_offset)) = input { 163 | assert!(layout_offset <= T - RATE); 164 | // `Iterator::zip` short-circuits when one iterator completes, so this will only 165 | // mutate the rate portion of the state. 166 | for (word, value) in state.iter_mut().skip(layout_offset).zip(input.iter()) { 167 | *word += value.expect("poseidon_sponge is called with a padded input"); 168 | } 169 | } 170 | 171 | permute::(state, mds_matrix, round_constants); 172 | 173 | let mut output = [None; RATE]; 174 | for (word, value) in output.iter_mut().zip(state.iter()) { 175 | *word = Some(*value); 176 | } 177 | Squeezing(output) 178 | } 179 | 180 | mod private { 181 | pub trait SealedSpongeMode {} 182 | impl SealedSpongeMode for super::Absorbing {} 183 | impl SealedSpongeMode for super::Squeezing {} 184 | } 185 | 186 | /// The state of the `Sponge`. 187 | pub trait SpongeMode: private::SealedSpongeMode + Clone {} 188 | 189 | /// The absorbing state of the `Sponge`. 190 | #[derive(Debug, Copy, Clone)] 191 | pub struct Absorbing(pub SpongeRate); 192 | 193 | /// The squeezing state of the `Sponge`. 194 | #[derive(Debug, Copy, Clone)] 195 | pub struct Squeezing(pub SpongeRate); 196 | 197 | impl SpongeMode for Absorbing {} 198 | impl SpongeMode for Squeezing {} 199 | 200 | impl Absorbing { 201 | pub fn init_with(val: F) -> Self { 202 | Self( 203 | iter::once(Some(val)) 204 | .chain((1..RATE).map(|_| None)) 205 | .collect::>() 206 | .try_into() 207 | .unwrap(), 208 | ) 209 | } 210 | } 211 | 212 | /// A Poseidon sponge. 213 | #[derive(Clone)] 214 | pub(crate) struct Sponge< 215 | F: FromUniformBytes<64> + Ord, 216 | S: CachedSpec, 217 | M: SpongeMode, 218 | const T: usize, 219 | const RATE: usize, 220 | > { 221 | mode: M, 222 | state: State, 223 | layout: usize, 224 | _marker: PhantomData, 225 | } 226 | 227 | impl< 228 | F: FromUniformBytes<64> + Ord, 229 | S: CachedSpec, 230 | const T: usize, 231 | const RATE: usize, 232 | > Sponge, T, RATE> 233 | { 234 | /// Constructs a new sponge for the given Poseidon specification. 235 | pub(crate) fn new(initial_capacity_element: F, layout: usize) -> Self { 236 | let mode = Absorbing([None; RATE]); 237 | let mut state = [F::ZERO; T]; 238 | state[(RATE + layout) % T] = initial_capacity_element; 239 | 240 | Sponge { 241 | mode, 242 | state, 243 | layout, 244 | _marker: PhantomData, 245 | } 246 | } 247 | 248 | /// add the capacity into current position of output 249 | pub(crate) fn update_capacity(&mut self, capacity_element: F) { 250 | self.state[(RATE + self.layout) % T] += capacity_element; 251 | } 252 | 253 | /// Absorbs an element into the sponge. 254 | pub(crate) fn absorb(&mut self, value: F) { 255 | for entry in self.mode.0.iter_mut() { 256 | if entry.is_none() { 257 | *entry = Some(value); 258 | return; 259 | } 260 | } 261 | 262 | // We've already absorbed as many elements as we can 263 | let _ = poseidon_sponge::( 264 | &mut self.state, 265 | Some((&self.mode, self.layout)), 266 | S::cached_mds(), 267 | S::cached_round_constants(), 268 | ); 269 | self.mode = Absorbing::init_with(value); 270 | } 271 | 272 | /// Transitions the sponge into its squeezing state. 273 | pub(crate) fn finish_absorbing(mut self) -> Sponge, T, RATE> { 274 | let mode = poseidon_sponge::( 275 | &mut self.state, 276 | Some((&self.mode, self.layout)), 277 | S::cached_mds(), 278 | S::cached_round_constants(), 279 | ); 280 | 281 | Sponge { 282 | mode, 283 | state: self.state, 284 | layout: self.layout, 285 | _marker: PhantomData, 286 | } 287 | } 288 | } 289 | 290 | impl< 291 | F: FromUniformBytes<64> + Ord, 292 | S: CachedSpec, 293 | const T: usize, 294 | const RATE: usize, 295 | > Sponge, T, RATE> 296 | { 297 | /// Squeezes an element from the sponge. 298 | pub(crate) fn squeeze(&mut self) -> F { 299 | loop { 300 | for entry in self.mode.0.iter_mut() { 301 | if let Some(e) = entry.take() { 302 | return e; 303 | } 304 | } 305 | 306 | // We've already squeezed out all available elements 307 | self.mode = poseidon_sponge::( 308 | &mut self.state, 309 | None, 310 | S::cached_mds(), 311 | S::cached_round_constants(), 312 | ); 313 | } 314 | } 315 | } 316 | 317 | /// A domain in which a Poseidon hash function is being used. 318 | pub trait Domain + Ord, const RATE: usize> { 319 | /// Iterator that outputs padding field elements. 320 | type Padding: IntoIterator; 321 | 322 | /// The name of this domain, for debug formatting purposes. 323 | fn name() -> String; 324 | 325 | /// The initial capacity element, encoding this domain. 326 | fn initial_capacity_element() -> F; 327 | 328 | /// Returns the padding to be appended to the input. 329 | fn padding(input_len: usize) -> Self::Padding; 330 | 331 | /// Set the position of inputs in state: how many fields 332 | /// of offset the first input should be put in, for iden3, 333 | /// inputs are right aligned in the state array 334 | fn layout(_width: usize) -> usize { 335 | 0 336 | } 337 | } 338 | 339 | /// A Poseidon hash function used with constant input length. 340 | /// 341 | /// Domain specified in [ePrint 2019/458 section 4.2](https://eprint.iacr.org/2019/458.pdf). 342 | #[derive(Clone, Copy, Debug)] 343 | pub struct ConstantLength; 344 | 345 | impl + Ord, const RATE: usize, const L: usize> Domain 346 | for ConstantLength 347 | { 348 | type Padding = iter::Take>; 349 | 350 | fn name() -> String { 351 | format!("ConstantLength<{L}>") 352 | } 353 | 354 | fn initial_capacity_element() -> F { 355 | // Capacity value is $length \cdot 2^64 + (o-1)$ where o is the output length. 356 | // We hard-code an output length of 1. 357 | F::from_u128((L as u128) << 64) 358 | } 359 | 360 | fn padding(input_len: usize) -> Self::Padding { 361 | assert_eq!(input_len, L); 362 | // For constant-input-length hashing, we pad the input with zeroes to a multiple 363 | // of RATE. On its own this would not be sponge-compliant padding, but the 364 | // Poseidon authors encode the constant length into the capacity element, ensuring 365 | // that inputs of different lengths do not share the same permutation. 366 | let k = (L + RATE - 1) / RATE; 367 | iter::repeat(F::ZERO).take(k * RATE - L) 368 | } 369 | } 370 | 371 | /// A Poseidon hash function used with constant input length, this is iden3's specifications 372 | #[derive(Clone, Copy, Debug)] 373 | pub struct ConstantLengthIden3; 374 | 375 | impl + Ord, const RATE: usize, const L: usize> Domain 376 | for ConstantLengthIden3 377 | { 378 | type Padding = as Domain>::Padding; 379 | 380 | fn name() -> String { 381 | format!("ConstantLength<{L}> in iden3's style") 382 | } 383 | 384 | // iden3's scheme do not set any capacity mark 385 | fn initial_capacity_element() -> F { 386 | F::ZERO 387 | } 388 | 389 | fn padding(input_len: usize) -> Self::Padding { 390 | as Domain>::padding(input_len) 391 | } 392 | 393 | fn layout(width: usize) -> usize { 394 | width - RATE 395 | } 396 | } 397 | 398 | /// A Poseidon hash function used with variable input length, this is iden3's specifications 399 | #[derive(Clone, Copy, Debug)] 400 | pub struct VariableLengthIden3; 401 | 402 | impl + Ord, const RATE: usize> Domain for VariableLengthIden3 { 403 | type Padding = as Domain>::Padding; 404 | 405 | fn name() -> String { 406 | "VariableLength in iden3's style".to_string() 407 | } 408 | 409 | // iden3's scheme do not set any capacity mark 410 | fn initial_capacity_element() -> F { 411 | as Domain>::initial_capacity_element() 412 | } 413 | 414 | fn padding(input_len: usize) -> Self::Padding { 415 | let k = input_len % RATE; 416 | iter::repeat(F::ZERO).take(if k == 0 { 0 } else { RATE - k }) 417 | } 418 | 419 | fn layout(width: usize) -> usize { 420 | as Domain>::layout(width) 421 | } 422 | } 423 | 424 | /// A Poseidon hash function, built around a sponge. 425 | #[derive(Clone)] 426 | pub struct Hash< 427 | F: FromUniformBytes<64> + Ord, 428 | S: CachedSpec, 429 | D: Domain, 430 | const T: usize, 431 | const RATE: usize, 432 | > { 433 | sponge: Sponge, T, RATE>, 434 | _domain: PhantomData, 435 | } 436 | 437 | impl< 438 | F: FromUniformBytes<64> + Ord, 439 | S: CachedSpec, 440 | D: Domain, 441 | const T: usize, 442 | const RATE: usize, 443 | > fmt::Debug for Hash 444 | { 445 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 446 | f.debug_struct("Hash") 447 | .field("width", &T) 448 | .field("rate", &RATE) 449 | .field("R_F", &S::full_rounds()) 450 | .field("R_P", &S::partial_rounds()) 451 | .field("domain", &D::name()) 452 | .finish() 453 | } 454 | } 455 | 456 | impl< 457 | F: FromUniformBytes<64> + Ord, 458 | S: CachedSpec, 459 | D: Domain, 460 | const T: usize, 461 | const RATE: usize, 462 | > Hash 463 | { 464 | /// Initializes a new hasher. 465 | pub fn init() -> Self { 466 | Hash { 467 | sponge: Sponge::new(D::initial_capacity_element(), D::layout(T)), 468 | _domain: PhantomData, 469 | } 470 | } 471 | 472 | /// help permute a state 473 | pub fn permute(&self, state: &mut [F; T]) { 474 | permute::(state, S::cached_mds(), S::cached_round_constants()); 475 | } 476 | } 477 | 478 | impl< 479 | F: FromUniformBytes<64> + Ord, 480 | S: CachedSpec, 481 | const T: usize, 482 | const RATE: usize, 483 | const L: usize, 484 | > Hash, T, RATE> 485 | { 486 | /// Hashes the given input. 487 | pub fn hash(mut self, message: [F; L]) -> F { 488 | for value in message 489 | .into_iter() 490 | .chain( as Domain>::padding(L)) 491 | { 492 | self.sponge.absorb(value); 493 | } 494 | self.sponge.finish_absorbing().squeeze() 495 | } 496 | } 497 | 498 | impl< 499 | F: FromUniformBytes<64> + Ord, 500 | S: CachedSpec, 501 | const T: usize, 502 | const RATE: usize, 503 | const L: usize, 504 | > Hash, T, RATE> 505 | { 506 | /// Hashes the given input. 507 | pub fn hash(mut self, message: [F; L], domain: F) -> F { 508 | // notice iden3 domain has no initial capacity element so the domain is updated here 509 | self.sponge.update_capacity(domain); 510 | for value in message 511 | .into_iter() 512 | .chain( as Domain>::padding(L)) 513 | { 514 | self.sponge.absorb(value); 515 | } 516 | self.sponge.finish_absorbing().squeeze() 517 | } 518 | } 519 | 520 | impl< 521 | F: FromUniformBytes<64> + Ord, 522 | S: CachedSpec, 523 | const T: usize, 524 | const RATE: usize, 525 | > Hash 526 | { 527 | /// Hashes the given input. 528 | pub fn hash_with_cap(mut self, message: &[F], cap: u128) -> F { 529 | self.sponge.update_capacity(F::from_u128(cap)); 530 | for value in message { 531 | self.sponge.absorb(*value); 532 | } 533 | 534 | for pad in >::padding(message.len()) { 535 | self.sponge.absorb(pad); 536 | } 537 | 538 | self.sponge.finish_absorbing().squeeze() 539 | } 540 | } 541 | 542 | #[cfg(test)] 543 | mod tests { 544 | use super::pasta::Fp; 545 | 546 | use super::{permute, ConstantLength, Hash, P128Pow5T3, P128Pow5T3Compact, Spec}; 547 | type OrchardNullifier = P128Pow5T3; 548 | 549 | #[test] 550 | fn orchard_spec_equivalence() { 551 | let message = [Fp::from(6), Fp::from(42)]; 552 | 553 | let (round_constants, mds, _) = OrchardNullifier::constants(); 554 | 555 | let hasher = Hash::<_, OrchardNullifier, ConstantLength<2>, 3, 2>::init(); 556 | let result = hasher.hash(message); 557 | 558 | // The result should be equivalent to just directly applying the permutation and 559 | // taking the first state element as the output. 560 | let mut two_to_sixty_five = Fp::from(1 << 63); 561 | two_to_sixty_five = two_to_sixty_five.double(); 562 | two_to_sixty_five = two_to_sixty_five.double(); 563 | let mut state = [message[0], message[1], two_to_sixty_five]; 564 | permute::<_, OrchardNullifier, 3, 2>(&mut state, &mds, &round_constants); 565 | assert_eq!(state[0], result); 566 | } 567 | 568 | #[test] 569 | fn hasher_permute_equivalence() { 570 | let message = [Fp::from(6), Fp::from(42)]; 571 | let hasher = Hash::<_, OrchardNullifier, ConstantLength<2>, 3, 2>::init(); 572 | // The result should be equivalent to just directly applying the permutation and 573 | // taking the first state element as the output. 574 | let mut two_to_sixty_five = Fp::from(1 << 63); 575 | two_to_sixty_five = two_to_sixty_five.double(); 576 | two_to_sixty_five = two_to_sixty_five.double(); 577 | let mut state = [Fp::from(6), Fp::from(42), two_to_sixty_five]; 578 | 579 | hasher.permute(&mut state); 580 | 581 | let result = hasher.hash(message); 582 | assert_eq!(state[0], result); 583 | } 584 | 585 | #[test] 586 | fn spec_equivalence() { 587 | let message = [Fp::from(6), Fp::from(42)]; 588 | let hasher1 = Hash::<_, P128Pow5T3, ConstantLength<2>, 3, 2>::init(); 589 | let hasher2 = Hash::<_, P128Pow5T3Compact, ConstantLength<2>, 3, 2>::init(); 590 | 591 | let result1 = hasher1.hash(message.clone()); 592 | let result2 = hasher2.hash(message.clone()); 593 | assert_eq!(result1, result2); 594 | } 595 | } 596 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/binops.rs: -------------------------------------------------------------------------------- 1 | macro_rules! impl_add_binop_specify_output { 2 | ($lhs:ident, $rhs:ident, $output:ident) => { 3 | impl<'b> ::core::ops::Add<&'b $rhs> for $lhs { 4 | type Output = $output; 5 | 6 | #[inline] 7 | fn add(self, rhs: &'b $rhs) -> $output { 8 | &self + rhs 9 | } 10 | } 11 | 12 | impl<'a> ::core::ops::Add<$rhs> for &'a $lhs { 13 | type Output = $output; 14 | 15 | #[inline] 16 | fn add(self, rhs: $rhs) -> $output { 17 | self + &rhs 18 | } 19 | } 20 | 21 | impl ::core::ops::Add<$rhs> for $lhs { 22 | type Output = $output; 23 | 24 | #[inline] 25 | fn add(self, rhs: $rhs) -> $output { 26 | &self + &rhs 27 | } 28 | } 29 | }; 30 | } 31 | 32 | macro_rules! impl_sub_binop_specify_output { 33 | ($lhs:ident, $rhs:ident, $output:ident) => { 34 | impl<'b> ::core::ops::Sub<&'b $rhs> for $lhs { 35 | type Output = $output; 36 | 37 | #[inline] 38 | fn sub(self, rhs: &'b $rhs) -> $output { 39 | &self - rhs 40 | } 41 | } 42 | 43 | impl<'a> ::core::ops::Sub<$rhs> for &'a $lhs { 44 | type Output = $output; 45 | 46 | #[inline] 47 | fn sub(self, rhs: $rhs) -> $output { 48 | self - &rhs 49 | } 50 | } 51 | 52 | impl ::core::ops::Sub<$rhs> for $lhs { 53 | type Output = $output; 54 | 55 | #[inline] 56 | fn sub(self, rhs: $rhs) -> $output { 57 | &self - &rhs 58 | } 59 | } 60 | }; 61 | } 62 | 63 | macro_rules! impl_binops_additive_specify_output { 64 | ($lhs:ident, $rhs:ident, $output:ident) => { 65 | impl_add_binop_specify_output!($lhs, $rhs, $output); 66 | impl_sub_binop_specify_output!($lhs, $rhs, $output); 67 | }; 68 | } 69 | 70 | macro_rules! impl_binops_multiplicative_mixed { 71 | ($lhs:ident, $rhs:ident, $output:ident) => { 72 | impl<'b> ::core::ops::Mul<&'b $rhs> for $lhs { 73 | type Output = $output; 74 | 75 | #[inline] 76 | fn mul(self, rhs: &'b $rhs) -> $output { 77 | &self * rhs 78 | } 79 | } 80 | 81 | impl<'a> ::core::ops::Mul<$rhs> for &'a $lhs { 82 | type Output = $output; 83 | 84 | #[inline] 85 | fn mul(self, rhs: $rhs) -> $output { 86 | self * &rhs 87 | } 88 | } 89 | 90 | impl ::core::ops::Mul<$rhs> for $lhs { 91 | type Output = $output; 92 | 93 | #[inline] 94 | fn mul(self, rhs: $rhs) -> $output { 95 | &self * &rhs 96 | } 97 | } 98 | }; 99 | } 100 | 101 | macro_rules! impl_binops_additive { 102 | ($lhs:ident, $rhs:ident) => { 103 | impl_binops_additive_specify_output!($lhs, $rhs, $lhs); 104 | 105 | impl ::core::ops::SubAssign<$rhs> for $lhs { 106 | #[inline] 107 | fn sub_assign(&mut self, rhs: $rhs) { 108 | *self = &*self - &rhs; 109 | } 110 | } 111 | 112 | impl ::core::ops::AddAssign<$rhs> for $lhs { 113 | #[inline] 114 | fn add_assign(&mut self, rhs: $rhs) { 115 | *self = &*self + &rhs; 116 | } 117 | } 118 | 119 | impl<'b> ::core::ops::SubAssign<&'b $rhs> for $lhs { 120 | #[inline] 121 | fn sub_assign(&mut self, rhs: &'b $rhs) { 122 | *self = &*self - rhs; 123 | } 124 | } 125 | 126 | impl<'b> ::core::ops::AddAssign<&'b $rhs> for $lhs { 127 | #[inline] 128 | fn add_assign(&mut self, rhs: &'b $rhs) { 129 | *self = &*self + rhs; 130 | } 131 | } 132 | }; 133 | } 134 | 135 | macro_rules! impl_binops_multiplicative { 136 | ($lhs:ident, $rhs:ident) => { 137 | impl_binops_multiplicative_mixed!($lhs, $rhs, $lhs); 138 | 139 | impl ::core::ops::MulAssign<$rhs> for $lhs { 140 | #[inline] 141 | fn mul_assign(&mut self, rhs: $rhs) { 142 | *self = &*self * &rhs; 143 | } 144 | } 145 | 146 | impl<'b> ::core::ops::MulAssign<&'b $rhs> for $lhs { 147 | #[inline] 148 | fn mul_assign(&mut self, rhs: &'b $rhs) { 149 | *self = &*self * rhs; 150 | } 151 | } 152 | }; 153 | } 154 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/bn256/fp.rs: -------------------------------------------------------------------------------- 1 | // Parameters generated from: 2 | // 3 | // https://github.com/scroll-tech/poseidon-circuit/blob/e3841d0828e577b80c9cd84aa71f79adc96756fc/src/poseidon/primitives.rs#L61 4 | // 5 | // or equivalently: 6 | // 7 | // https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/b5434fd2b2785926dd1dd386efbef167da57c064/code/poseidonperm_x5_254_3.sage 8 | // 9 | 10 | use halo2curves::{ 11 | bn256::Fr as Fp, 12 | group::ff::{Field, PrimeField}, 13 | }; 14 | use lazy_static::lazy_static; 15 | 16 | lazy_static! { 17 | pub static ref ROUND_CONSTANTS: [[Fp; 3]; 65] = { 18 | let c_str = round_constants(); 19 | let ret: Vec<[Fp; 3]> = (0..65) 20 | .map(|i| [0, 1, 2].map(|j| Fp::from_str_vartime(c_str[i * 3 + j]).unwrap())) 21 | .collect(); 22 | 23 | ret.try_into().unwrap() 24 | }; 25 | pub static ref MDS: [[Fp; 3]; 3] = { 26 | let m_str = mds(); 27 | 28 | [0, 1, 2].map(|i| [0, 1, 2].map(|j| Fp::from_str_vartime(m_str[i][j]).unwrap())) 29 | }; 30 | pub static ref MDS_INV: [[Fp; 3]; 3] = { 31 | let mds = *MDS; 32 | 33 | let det_items = |idx: usize| { 34 | (0..3) 35 | .map(|i| mds[(idx + i) % 3][i]) 36 | .reduce(|acc, fr| acc * fr) 37 | .unwrap() 38 | - (0..3) 39 | .map(|i| mds[(idx + 3 - i) % 3][i]) 40 | .reduce(|acc, fr| acc * fr) 41 | .unwrap() 42 | }; 43 | 44 | let det = (0..3) 45 | .map(det_items) 46 | .reduce(|acc, fr| acc + fr) 47 | .unwrap() 48 | .invert() 49 | .unwrap(); 50 | 51 | let ci = |i: usize, j: usize| { 52 | mds[(i + 1) % 3][(j + 1) % 3] * mds[(i + 2) % 3][(j + 2) % 3] 53 | - mds[(i + 1) % 3][(j + 2) % 3] * mds[(i + 2) % 3][(j + 1) % 3] 54 | }; 55 | 56 | [ 57 | [ci(0, 0) * det, ci(1, 0) * det, ci(2, 0) * det], 58 | [ci(0, 1) * det, ci(1, 1) * det, ci(2, 1) * det], 59 | [ci(0, 2) * det, ci(1, 2) * det, ci(2, 2) * det], 60 | ] 61 | }; 62 | } 63 | 64 | fn round_constants() -> Vec<&'static str> { 65 | vec![ 66 | "6745197990210204598374042828761989596302876299545964402857411729872131034734", 67 | "426281677759936592021316809065178817848084678679510574715894138690250139748", 68 | "4014188762916583598888942667424965430287497824629657219807941460227372577781", 69 | "21328925083209914769191926116470334003273872494252651254811226518870906634704", 70 | "19525217621804205041825319248827370085205895195618474548469181956339322154226", 71 | "1402547928439424661186498190603111095981986484908825517071607587179649375482", 72 | "18320863691943690091503704046057443633081959680694199244583676572077409194605", 73 | "17709820605501892134371743295301255810542620360751268064484461849423726103416", 74 | "15970119011175710804034336110979394557344217932580634635707518729185096681010", 75 | "9818625905832534778628436765635714771300533913823445439412501514317783880744", 76 | "6235167673500273618358172865171408902079591030551453531218774338170981503478", 77 | "12575685815457815780909564540589853169226710664203625668068862277336357031324", 78 | "7381963244739421891665696965695211188125933529845348367882277882370864309593", 79 | "14214782117460029685087903971105962785460806586237411939435376993762368956406", 80 | "13382692957873425730537487257409819532582973556007555550953772737680185788165", 81 | "2203881792421502412097043743980777162333765109810562102330023625047867378813", 82 | "2916799379096386059941979057020673941967403377243798575982519638429287573544", 83 | "4341714036313630002881786446132415875360643644216758539961571543427269293497", 84 | "2340590164268886572738332390117165591168622939528604352383836760095320678310", 85 | "5222233506067684445011741833180208249846813936652202885155168684515636170204", 86 | "7963328565263035669460582454204125526132426321764384712313576357234706922961", 87 | "1394121618978136816716817287892553782094854454366447781505650417569234586889", 88 | "20251767894547536128245030306810919879363877532719496013176573522769484883301", 89 | "141695147295366035069589946372747683366709960920818122842195372849143476473", 90 | "15919677773886738212551540894030218900525794162097204800782557234189587084981", 91 | "2616624285043480955310772600732442182691089413248613225596630696960447611520", 92 | "4740655602437503003625476760295930165628853341577914460831224100471301981787", 93 | "19201590924623513311141753466125212569043677014481753075022686585593991810752", 94 | "12116486795864712158501385780203500958268173542001460756053597574143933465696", 95 | "8481222075475748672358154589993007112877289817336436741649507712124418867136", 96 | "5181207870440376967537721398591028675236553829547043817076573656878024336014", 97 | "1576305643467537308202593927724028147293702201461402534316403041563704263752", 98 | "2555752030748925341265856133642532487884589978209403118872788051695546807407", 99 | "18840924862590752659304250828416640310422888056457367520753407434927494649454", 100 | "14593453114436356872569019099482380600010961031449147888385564231161572479535", 101 | "20826991704411880672028799007667199259549645488279985687894219600551387252871", 102 | "9159011389589751902277217485643457078922343616356921337993871236707687166408", 103 | "5605846325255071220412087261490782205304876403716989785167758520729893194481", 104 | "1148784255964739709393622058074925404369763692117037208398835319441214134867", 105 | "20945896491956417459309978192328611958993484165135279604807006821513499894540", 106 | "229312996389666104692157009189660162223783309871515463857687414818018508814", 107 | "21184391300727296923488439338697060571987191396173649012875080956309403646776", 108 | "21853424399738097885762888601689700621597911601971608617330124755808946442758", 109 | "12776298811140222029408960445729157525018582422120161448937390282915768616621", 110 | "7556638921712565671493830639474905252516049452878366640087648712509680826732", 111 | "19042212131548710076857572964084011858520620377048961573689299061399932349935", 112 | "12871359356889933725034558434803294882039795794349132643274844130484166679697", 113 | "3313271555224009399457959221795880655466141771467177849716499564904543504032", 114 | "15080780006046305940429266707255063673138269243146576829483541808378091931472", 115 | "21300668809180077730195066774916591829321297484129506780637389508430384679582", 116 | "20480395468049323836126447690964858840772494303543046543729776750771407319822", 117 | "10034492246236387932307199011778078115444704411143703430822959320969550003883", 118 | "19584962776865783763416938001503258436032522042569001300175637333222729790225", 119 | "20155726818439649091211122042505326538030503429443841583127932647435472711802", 120 | "13313554736139368941495919643765094930693458639277286513236143495391474916777", 121 | "14606609055603079181113315307204024259649959674048912770003912154260692161833", 122 | "5563317320536360357019805881367133322562055054443943486481491020841431450882", 123 | "10535419877021741166931390532371024954143141727751832596925779759801808223060", 124 | "12025323200952647772051708095132262602424463606315130667435888188024371598063", 125 | "2906495834492762782415522961458044920178260121151056598901462871824771097354", 126 | "19131970618309428864375891649512521128588657129006772405220584460225143887876", 127 | "8896386073442729425831367074375892129571226824899294414632856215758860965449", 128 | "7748212315898910829925509969895667732958278025359537472413515465768989125274", 129 | "422974903473869924285294686399247660575841594104291551918957116218939002865", 130 | "6398251826151191010634405259351528880538837895394722626439957170031528482771", 131 | "18978082967849498068717608127246258727629855559346799025101476822814831852169", 132 | "19150742296744826773994641927898928595714611370355487304294875666791554590142", 133 | "12896891575271590393203506752066427004153880610948642373943666975402674068209", 134 | "9546270356416926575977159110423162512143435321217584886616658624852959369669", 135 | "2159256158967802519099187112783460402410585039950369442740637803310736339200", 136 | "8911064487437952102278704807713767893452045491852457406400757953039127292263", 137 | "745203718271072817124702263707270113474103371777640557877379939715613501668", 138 | "19313999467876585876087962875809436559985619524211587308123441305315685710594", 139 | "13254105126478921521101199309550428567648131468564858698707378705299481802310", 140 | "1842081783060652110083740461228060164332599013503094142244413855982571335453", 141 | "9630707582521938235113899367442877106957117302212260601089037887382200262598", 142 | "5066637850921463603001689152130702510691309665971848984551789224031532240292", 143 | "4222575506342961001052323857466868245596202202118237252286417317084494678062", 144 | "2919565560395273474653456663643621058897649501626354982855207508310069954086", 145 | "6828792324689892364977311977277548750189770865063718432946006481461319858171", 146 | "2245543836264212411244499299744964607957732316191654500700776604707526766099", 147 | "19602444885919216544870739287153239096493385668743835386720501338355679311704", 148 | "8239538512351936341605373169291864076963368674911219628966947078336484944367", 149 | "15053013456316196458870481299866861595818749671771356646798978105863499965417", 150 | "7173615418515925804810790963571435428017065786053377450925733428353831789901", 151 | "8239211677777829016346247446855147819062679124993100113886842075069166957042", 152 | "15330855478780269194281285878526984092296288422420009233557393252489043181621", 153 | "10014883178425964324400942419088813432808659204697623248101862794157084619079", 154 | "14014440630268834826103915635277409547403899966106389064645466381170788813506", 155 | "3580284508947993352601712737893796312152276667249521401778537893620670305946", 156 | "2559754020964039399020874042785294258009596917335212876725104742182177996988", 157 | "14898657953331064524657146359621913343900897440154577299309964768812788279359", 158 | "2094037260225570753385567402013028115218264157081728958845544426054943497065", 159 | "18051086536715129874440142649831636862614413764019212222493256578581754875930", 160 | "21680659279808524976004872421382255670910633119979692059689680820959727969489", 161 | "13950668739013333802529221454188102772764935019081479852094403697438884885176", 162 | "9703845704528288130475698300068368924202959408694460208903346143576482802458", 163 | "12064310080154762977097567536495874701200266107682637369509532768346427148165", 164 | "16970760937630487134309762150133050221647250855182482010338640862111040175223", 165 | "9790997389841527686594908620011261506072956332346095631818178387333642218087", 166 | "16314772317774781682315680698375079500119933343877658265473913556101283387175", 167 | "82044870826814863425230825851780076663078706675282523830353041968943811739", 168 | "21696416499108261787701615667919260888528264686979598953977501999747075085778", 169 | "327771579314982889069767086599893095509690747425186236545716715062234528958", 170 | "4606746338794869835346679399457321301521448510419912225455957310754258695442", 171 | "64499140292086295251085369317820027058256893294990556166497635237544139149", 172 | "10455028514626281809317431738697215395754892241565963900707779591201786416553", 173 | "10421411526406559029881814534127830959833724368842872558146891658647152404488", 174 | "18848084335930758908929996602136129516563864917028006334090900573158639401697", 175 | "13844582069112758573505569452838731733665881813247931940917033313637916625267", 176 | "13488838454403536473492810836925746129625931018303120152441617863324950564617", 177 | "15742141787658576773362201234656079648895020623294182888893044264221895077688", 178 | "6756884846734501741323584200608866954194124526254904154220230538416015199997", 179 | "7860026400080412708388991924996537435137213401947704476935669541906823414404", 180 | "7871040688194276447149361970364037034145427598711982334898258974993423182255", 181 | "20758972836260983284101736686981180669442461217558708348216227791678564394086", 182 | "21723241881201839361054939276225528403036494340235482225557493179929400043949", 183 | "19428469330241922173653014973246050805326196062205770999171646238586440011910", 184 | "7969200143746252148180468265998213908636952110398450526104077406933642389443", 185 | "10950417916542216146808986264475443189195561844878185034086477052349738113024", 186 | "18149233917533571579549129116652755182249709970669448788972210488823719849654", 187 | "3729796741814967444466779622727009306670204996071028061336690366291718751463", 188 | "5172504399789702452458550583224415301790558941194337190035441508103183388987", 189 | "6686473297578275808822003704722284278892335730899287687997898239052863590235", 190 | "19426913098142877404613120616123695099909113097119499573837343516470853338513", 191 | "5120337081764243150760446206763109494847464512045895114970710519826059751800", 192 | "5055737465570446530938379301905385631528718027725177854815404507095601126720", 193 | "14235578612970484492268974539959119923625505766550088220840324058885914976980", 194 | "653592517890187950103239281291172267359747551606210609563961204572842639923", 195 | "5507360526092411682502736946959369987101940689834541471605074817375175870579", 196 | "7864202866011437199771472205361912625244234597659755013419363091895334445453", 197 | "21294659996736305811805196472076519801392453844037698272479731199885739891648", 198 | "13767183507040326119772335839274719411331242166231012705169069242737428254651", 199 | "810181532076738148308457416289197585577119693706380535394811298325092337781", 200 | "14232321930654703053193240133923161848171310212544136614525040874814292190478", 201 | "16796904728299128263054838299534612533844352058851230375569421467352578781209", 202 | "16256310366973209550759123431979563367001604350120872788217761535379268327259", 203 | "19791658638819031543640174069980007021961272701723090073894685478509001321817", 204 | "7046232469803978873754056165670086532908888046886780200907660308846356865119", 205 | "16001732848952745747636754668380555263330934909183814105655567108556497219752", 206 | "9737276123084413897604802930591512772593843242069849260396983774140735981896", 207 | "11410895086919039954381533622971292904413121053792570364694836768885182251535", 208 | "19098362474249267294548762387533474746422711206129028436248281690105483603471", 209 | "11013788190750472643548844759298623898218957233582881400726340624764440203586", 210 | "2206958256327295151076063922661677909471794458896944583339625762978736821035", 211 | "7171889270225471948987523104033632910444398328090760036609063776968837717795", 212 | "2510237900514902891152324520472140114359583819338640775472608119384714834368", 213 | "8825275525296082671615660088137472022727508654813239986303576303490504107418", 214 | "1481125575303576470988538039195271612778457110700618040436600537924912146613", 215 | "16268684562967416784133317570130804847322980788316762518215429249893668424280", 216 | "4681491452239189664806745521067158092729838954919425311759965958272644506354", 217 | "3131438137839074317765338377823608627360421824842227925080193892542578675835", 218 | "7930402370812046914611776451748034256998580373012248216998696754202474945793", 219 | "8973151117361309058790078507956716669068786070949641445408234962176963060145", 220 | "10223139291409280771165469989652431067575076252562753663259473331031932716923", 221 | "2232089286698717316374057160056566551249777684520809735680538268209217819725", 222 | "16930089744400890347392540468934821520000065594669279286854302439710657571308", 223 | "21739597952486540111798430281275997558482064077591840966152905690279247146674", 224 | "7508315029150148468008716674010060103310093296969466203204862163743615534994", 225 | "11418894863682894988747041469969889669847284797234703818032750410328384432224", 226 | "10895338268862022698088163806301557188640023613155321294365781481663489837917", 227 | "18644184384117747990653304688839904082421784959872380449968500304556054962449", 228 | "7414443845282852488299349772251184564170443662081877445177167932875038836497", 229 | "5391299369598751507276083947272874512197023231529277107201098701900193273851", 230 | "10329906873896253554985208009869159014028187242848161393978194008068001342262", 231 | "4711719500416619550464783480084256452493890461073147512131129596065578741786", 232 | "11943219201565014805519989716407790139241726526989183705078747065985453201504", 233 | "4298705349772984837150885571712355513879480272326239023123910904259614053334", 234 | "9999044003322463509208400801275356671266978396985433172455084837770460579627", 235 | "4908416131442887573991189028182614782884545304889259793974797565686968097291", 236 | "11963412684806827200577486696316210731159599844307091475104710684559519773777", 237 | "20129916000261129180023520480843084814481184380399868943565043864970719708502", 238 | "12884788430473747619080473633364244616344003003135883061507342348586143092592", 239 | "20286808211545908191036106582330883564479538831989852602050135926112143921015", 240 | "16282045180030846845043407450751207026423331632332114205316676731302016331498", 241 | "4332932669439410887701725251009073017227450696965904037736403407953448682093", 242 | "11105712698773407689561953778861118250080830258196150686012791790342360778288", 243 | "21853934471586954540926699232107176721894655187276984175226220218852955976831", 244 | "9807888223112768841912392164376763820266226276821186661925633831143729724792", 245 | "13411808896854134882869416756427789378942943805153730705795307450368858622668", 246 | "17906847067500673080192335286161014930416613104209700445088168479205894040011", 247 | "14554387648466176616800733804942239711702169161888492380425023505790070369632", 248 | "4264116751358967409634966292436919795665643055548061693088119780787376143967", 249 | "2401104597023440271473786738539405349187326308074330930748109868990675625380", 250 | "12251645483867233248963286274239998200789646392205783056343767189806123148785", 251 | "15331181254680049984374210433775713530849624954688899814297733641575188164316", 252 | "13108834590369183125338853868477110922788848506677889928217413952560148766472", 253 | "6843160824078397950058285123048455551935389277899379615286104657075620692224", 254 | "10151103286206275742153883485231683504642432930275602063393479013696349676320", 255 | "7074320081443088514060123546121507442501369977071685257650287261047855962224", 256 | "11413928794424774638606755585641504971720734248726394295158115188173278890938", 257 | "7312756097842145322667451519888915975561412209738441762091369106604423801080", 258 | "7181677521425162567568557182629489303281861794357882492140051324529826589361", 259 | "15123155547166304758320442783720138372005699143801247333941013553002921430306", 260 | "13409242754315411433193860530743374419854094495153957441316635981078068351329", 261 | ] 262 | } 263 | 264 | fn mds() -> Vec> { 265 | vec![ 266 | vec![ 267 | "7511745149465107256748700652201246547602992235352608707588321460060273774987", 268 | "10370080108974718697676803824769673834027675643658433702224577712625900127200", 269 | "19705173408229649878903981084052839426532978878058043055305024233888854471533", 270 | ], 271 | vec![ 272 | "18732019378264290557468133440468564866454307626475683536618613112504878618481", 273 | "20870176810702568768751421378473869562658540583882454726129544628203806653987", 274 | "7266061498423634438633389053804536045105766754026813321943009179476902321146", 275 | ], 276 | vec![ 277 | "9131299761947733513298312097611845208338517739621853568979632113419485819303", 278 | "10595341252162738537912664445405114076324478519622938027420701542910180337937", 279 | "11597556804922396090267472882856054602429588299176362916247939723151043581408", 280 | ], 281 | ] 282 | } 283 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/bn256/mod.rs: -------------------------------------------------------------------------------- 1 | pub use halo2curves::bn256::Fr as Fp; 2 | 3 | use crate::primitives::p128pow5t3::P128Pow5T3Constants; 4 | use crate::primitives::Mds; 5 | 6 | pub mod fp; 7 | 8 | impl P128Pow5T3Constants for Fp { 9 | fn partial_rounds() -> usize { 10 | 57 11 | } 12 | 13 | fn round_constants() -> Vec<[Fp; 3]> { 14 | fp::ROUND_CONSTANTS.to_vec() 15 | } 16 | fn mds() -> Mds { 17 | *fp::MDS 18 | } 19 | fn mds_inv() -> Mds { 20 | *fp::MDS_INV 21 | } 22 | } 23 | 24 | #[cfg(any(test, feature = "test"))] 25 | #[allow(unused_imports)] 26 | mod tests { 27 | use std::marker::PhantomData; 28 | 29 | use crate::primitives::{permute, P128Pow5T3, P128Pow5T3Compact, Spec}; 30 | 31 | use super::*; 32 | 33 | /// The same Poseidon specification as poseidon::P128Pow5T3, but constructed 34 | /// such that its constants will be generated at runtime. 35 | #[derive(Debug, Copy, Clone)] 36 | pub struct P128Pow5T3Gen(PhantomData); 37 | 38 | impl P128Pow5T3Gen { 39 | pub fn new() -> Self { 40 | P128Pow5T3Gen(PhantomData::default()) 41 | } 42 | } 43 | 44 | impl Spec for P128Pow5T3Gen { 45 | fn full_rounds() -> usize { 46 | P128Pow5T3::::full_rounds() 47 | } 48 | 49 | fn partial_rounds() -> usize { 50 | P128Pow5T3::::partial_rounds() 51 | } 52 | 53 | fn sbox(val: F) -> F { 54 | P128Pow5T3::::sbox(val) 55 | } 56 | 57 | fn secure_mds() -> usize { 58 | 0 59 | } 60 | 61 | // fn constants(): default implementation that generates the parameters. 62 | } 63 | 64 | #[test] 65 | fn verify_constants_generation() { 66 | let (round_constants, mds, mds_inv) = P128Pow5T3Gen::::constants(); 67 | let (round_constants2, mds2, mds_inv2) = P128Pow5T3::::constants(); 68 | 69 | assert_eq!(round_constants.len(), 57 + 8); 70 | assert_eq!(round_constants, round_constants2); 71 | assert_eq!(mds, mds2); 72 | assert_eq!(mds_inv, mds_inv2); 73 | } 74 | 75 | #[test] 76 | fn verify_constants() { 77 | let c = fp::ROUND_CONSTANTS.to_vec(); 78 | let m = *fp::MDS; 79 | 80 | assert_eq!( 81 | format!("{:?}", c[0][0]), 82 | "0x0ee9a592ba9a9518d05986d656f40c2114c4993c11bb29938d21d47304cd8e6e" 83 | ); 84 | assert_eq!( 85 | format!("{:?}", c[c.len() - 1][2]), 86 | "0x1da55cc900f0d21f4a3e694391918a1b3c23b2ac773c6b3ef88e2e4228325161" 87 | ); 88 | assert_eq!( 89 | format!("{:?}", m[0][0]), 90 | "0x109b7f411ba0e4c9b2b70caf5c36a7b194be7c11ad24378bfedb68592ba8118b" 91 | ); 92 | assert_eq!( 93 | format!("{:?}", m[m.len() - 1][0]), 94 | "0x143021ec686a3f330d5f9e654638065ce6cd79e28c5b3753326244ee65a1b1a7" 95 | ); 96 | } 97 | 98 | // Verify that MDS * MDS^-1 = I. 99 | #[test] 100 | fn verify_mds() { 101 | let mds = ::mds(); 102 | let mds_inv = ::mds_inv(); 103 | 104 | #[allow(clippy::needless_range_loop)] 105 | for i in 0..3 { 106 | for j in 0..3 { 107 | let expected = if i == j { Fp::one() } else { Fp::zero() }; 108 | assert_eq!( 109 | (0..3).fold(Fp::zero(), |acc, k| acc + (mds[i][k] * mds_inv[k][j])), 110 | expected 111 | ); 112 | } 113 | } 114 | } 115 | 116 | #[test] 117 | fn test_compact_constants() { 118 | let input = [ 119 | Fp::from_raw([ 120 | 0x0000_0000_0000_0000, 121 | 0x0000_0000_0000_0000, 122 | 0x0000_0000_0000_0000, 123 | 0x0000_0000_0000_0000, 124 | ]), 125 | Fp::from_raw([ 126 | 0x0000_0000_0000_0001, 127 | 0x0000_0000_0000_0000, 128 | 0x0000_0000_0000_0000, 129 | 0x0000_0000_0000_0000, 130 | ]), 131 | Fp::from_raw([ 132 | 0x0000_0000_0000_0002, 133 | 0x0000_0000_0000_0000, 134 | 0x0000_0000_0000_0000, 135 | 0x0000_0000_0000_0000, 136 | ]), 137 | ]; 138 | 139 | let output = { 140 | let mut state = input.clone(); 141 | 142 | let (rc, mds, _inv) = P128Pow5T3::::constants(); 143 | permute::, 3, 2>(&mut state, &mds, &rc[..]); 144 | 145 | // This is the raw form with 3 constants per round. 146 | assert_ne!(rc[4][1], Fp::zero()); 147 | 148 | state 149 | }; 150 | 151 | let output_compact = { 152 | let mut state = input.clone(); 153 | 154 | let (rc, mds, _inv) = P128Pow5T3Compact::::constants(); 155 | permute::, 3, 2>(&mut state, &mds, &rc[..]); 156 | 157 | // This is the compact form with 1 constant per partial round. 158 | for i in 4..4 + 57 { 159 | assert_eq!(rc[i][1], Fp::zero()); 160 | assert_eq!(rc[i][2], Fp::zero()); 161 | } 162 | 163 | state 164 | }; 165 | 166 | assert_eq!(output, output_compact); 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/fields.rs: -------------------------------------------------------------------------------- 1 | /// Compute a + b + carry, returning the result and the new carry over. 2 | #[inline(always)] 3 | pub(crate) const fn adc(a: u64, b: u64, carry: u64) -> (u64, u64) { 4 | let ret = (a as u128) + (b as u128) + (carry as u128); 5 | (ret as u64, (ret >> 64) as u64) 6 | } 7 | 8 | /// Compute a - (b + borrow), returning the result and the new borrow. 9 | #[inline(always)] 10 | pub(crate) const fn sbb(a: u64, b: u64, borrow: u64) -> (u64, u64) { 11 | let ret = (a as u128).wrapping_sub((b as u128) + ((borrow >> 63) as u128)); 12 | (ret as u64, (ret >> 64) as u64) 13 | } 14 | 15 | /// Compute a + (b * c) + carry, returning the result and the new carry over. 16 | #[inline(always)] 17 | pub(crate) const fn mac(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) { 18 | let ret = (a as u128) + ((b as u128) * (c as u128)) + (carry as u128); 19 | (ret as u64, (ret >> 64) as u64) 20 | } 21 | 22 | /// Compute a + (b * c), returning the result and the new carry over. 23 | #[inline(always)] 24 | pub(crate) const fn macx(a: u64, b: u64, c: u64) -> (u64, u64) { 25 | let res = (a as u128) + ((b as u128) * (c as u128)); 26 | (res as u64, (res >> 64) as u64) 27 | } 28 | 29 | /// Compute a * b, returning the result. 30 | #[inline(always)] 31 | pub(crate) fn mul_512(a: [u64; 4], b: [u64; 4]) -> [u64; 8] { 32 | let (r0, carry) = macx(0, a[0], b[0]); 33 | let (r1, carry) = macx(carry, a[0], b[1]); 34 | let (r2, carry) = macx(carry, a[0], b[2]); 35 | let (r3, carry_out) = macx(carry, a[0], b[3]); 36 | 37 | let (r1, carry) = macx(r1, a[1], b[0]); 38 | let (r2, carry) = mac(r2, a[1], b[1], carry); 39 | let (r3, carry) = mac(r3, a[1], b[2], carry); 40 | let (r4, carry_out) = mac(carry_out, a[1], b[3], carry); 41 | 42 | let (r2, carry) = macx(r2, a[2], b[0]); 43 | let (r3, carry) = mac(r3, a[2], b[1], carry); 44 | let (r4, carry) = mac(r4, a[2], b[2], carry); 45 | let (r5, carry_out) = mac(carry_out, a[2], b[3], carry); 46 | 47 | let (r3, carry) = macx(r3, a[3], b[0]); 48 | let (r4, carry) = mac(r4, a[3], b[1], carry); 49 | let (r5, carry) = mac(r5, a[3], b[2], carry); 50 | let (r6, carry_out) = mac(carry_out, a[3], b[3], carry); 51 | 52 | [r0, r1, r2, r3, r4, r5, r6, carry_out] 53 | } 54 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/grain.rs: -------------------------------------------------------------------------------- 1 | //! The Grain LFSR in self-shrinking mode, as used by Poseidon. 2 | 3 | use std::marker::PhantomData; 4 | 5 | use bitvec::prelude::*; 6 | use halo2curves::ff::FromUniformBytes; 7 | 8 | const STATE: usize = 80; 9 | 10 | #[derive(Debug, Clone, Copy)] 11 | pub(crate) enum FieldType { 12 | /// GF(2^n) 13 | #[allow(dead_code)] 14 | Binary, 15 | /// GF(p) 16 | PrimeOrder, 17 | } 18 | 19 | impl FieldType { 20 | fn tag(&self) -> u8 { 21 | match self { 22 | FieldType::Binary => 0, 23 | FieldType::PrimeOrder => 1, 24 | } 25 | } 26 | } 27 | 28 | #[derive(Debug, Clone, Copy)] 29 | pub(crate) enum SboxType { 30 | /// x^alpha 31 | Pow, 32 | /// x^(-1) 33 | #[allow(dead_code)] 34 | Inv, 35 | } 36 | 37 | impl SboxType { 38 | fn tag(&self) -> u8 { 39 | match self { 40 | SboxType::Pow => 0, 41 | SboxType::Inv => 1, 42 | } 43 | } 44 | } 45 | 46 | pub(crate) struct Grain + Ord> { 47 | state: BitArr!(for 80, in u8, Msb0), 48 | next_bit: usize, 49 | _field: PhantomData, 50 | } 51 | 52 | impl + Ord> Grain { 53 | pub(crate) fn new(sbox: SboxType, t: u16, r_f: u16, r_p: u16) -> Self { 54 | // Initialize the LFSR state. 55 | let mut state = bitarr![u8, Msb0; 1; STATE]; 56 | let mut set_bits = |offset: usize, len, value| { 57 | // Poseidon reference impl sets initial state bits in MSB order. 58 | for i in 0..len { 59 | *state.get_mut(offset + len - 1 - i).unwrap() = (value >> i) & 1 != 0; 60 | } 61 | }; 62 | set_bits(0, 2, FieldType::PrimeOrder.tag() as u16); 63 | set_bits(2, 4, sbox.tag() as u16); 64 | set_bits(6, 12, F::NUM_BITS as u16); 65 | set_bits(18, 12, t); 66 | set_bits(30, 10, r_f); 67 | set_bits(40, 10, r_p); 68 | 69 | let mut grain = Grain { 70 | state, 71 | next_bit: STATE, 72 | _field: PhantomData, 73 | }; 74 | 75 | // Discard the first 160 bits. 76 | for _ in 0..20 { 77 | grain.load_next_8_bits(); 78 | grain.next_bit = STATE; 79 | } 80 | 81 | grain 82 | } 83 | 84 | fn load_next_8_bits(&mut self) { 85 | let mut new_bits = 0u8; 86 | for i in 0..8 { 87 | new_bits |= ((self.state[i + 62] 88 | ^ self.state[i + 51] 89 | ^ self.state[i + 38] 90 | ^ self.state[i + 23] 91 | ^ self.state[i + 13] 92 | ^ self.state[i]) as u8) 93 | << i; 94 | } 95 | self.state.rotate_left(8); 96 | self.next_bit -= 8; 97 | for i in 0..8 { 98 | *self.state.get_mut(self.next_bit + i).unwrap() = (new_bits >> i) & 1 != 0; 99 | } 100 | } 101 | 102 | fn get_next_bit(&mut self) -> bool { 103 | if self.next_bit == STATE { 104 | self.load_next_8_bits(); 105 | } 106 | let ret = self.state[self.next_bit]; 107 | self.next_bit += 1; 108 | ret 109 | } 110 | 111 | /// Returns the next field element from this Grain instantiation. 112 | pub(crate) fn next_field_element(&mut self) -> F { 113 | // Loop until we get an element in the field. 114 | loop { 115 | let mut bytes = F::Repr::default(); 116 | 117 | // Poseidon reference impl interprets the bits as a repr in MSB order, because 118 | // it's easy to do that in Python. Meanwhile, our field elements all use LSB 119 | // order. There's little motivation to diverge from the reference impl; these 120 | // are all constants, so we aren't introducing big-endianness into the rest of 121 | // the circuit (assuming unkeyed Poseidon, but we probably wouldn't want to 122 | // implement Grain inside a circuit, so we'd use a different round constant 123 | // derivation function there). 124 | let view = bytes.as_mut(); 125 | for (i, bit) in self.take(F::NUM_BITS as usize).enumerate() { 126 | // If we diverged from the reference impl and interpreted the bits in LSB 127 | // order, we would remove this line. 128 | let i = F::NUM_BITS as usize - 1 - i; 129 | 130 | view[i / 8] |= if bit { 1 << (i % 8) } else { 0 }; 131 | } 132 | 133 | if let Some(f) = F::from_repr_vartime(bytes) { 134 | break f; 135 | } 136 | } 137 | } 138 | 139 | /// Returns the next field element from this Grain instantiation, without using 140 | /// rejection sampling. 141 | pub(crate) fn next_field_element_without_rejection(&mut self) -> F { 142 | let mut bytes = [0u8; 64]; 143 | 144 | // Poseidon reference impl interprets the bits as a repr in MSB order, because 145 | // it's easy to do that in Python. Additionally, it does not use rejection 146 | // sampling in cases where the constants don't specifically need to be uniformly 147 | // random for security. We do not provide APIs that take a field-element-sized 148 | // array and reduce it modulo the field order, because those are unsafe APIs to 149 | // offer generally (accidentally using them can lead to divergence in consensus 150 | // systems due to not rejecting canonical forms). 151 | // 152 | // Given that we don't want to diverge from the reference implementation, we hack 153 | // around this restriction by serializing the bits into a 64-byte array and then 154 | // calling F::from_uniform_bytes. PLEASE DO NOT COPY THIS INTO YOUR OWN CODE! 155 | let view = bytes.as_mut(); 156 | for (i, bit) in self.take(F::NUM_BITS as usize).enumerate() { 157 | // If we diverged from the reference impl and interpreted the bits in LSB 158 | // order, we would remove this line. 159 | let i = F::NUM_BITS as usize - 1 - i; 160 | 161 | view[i / 8] |= if bit { 1 << (i % 8) } else { 0 }; 162 | } 163 | 164 | F::from_uniform_bytes(&bytes) 165 | } 166 | } 167 | 168 | impl + Ord> Iterator for Grain { 169 | type Item = bool; 170 | 171 | fn next(&mut self) -> Option { 172 | // Evaluate bits in pairs: 173 | // - If the first bit is a 1, output the second bit. 174 | // - If the first bit is a 0, discard the second bit. 175 | while !self.get_next_bit() { 176 | self.get_next_bit(); 177 | } 178 | Some(self.get_next_bit()) 179 | } 180 | } 181 | 182 | #[cfg(test)] 183 | mod tests { 184 | use super::super::pasta::Fp; 185 | use super::{Grain, SboxType}; 186 | 187 | #[test] 188 | fn grain() { 189 | let mut grain = Grain::::new(SboxType::Pow, 3, 8, 56); 190 | let _f = grain.next_field_element(); 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/mds.rs: -------------------------------------------------------------------------------- 1 | use halo2curves::ff::FromUniformBytes; 2 | 3 | use super::{grain::Grain, Mds}; 4 | 5 | pub(crate) fn generate_mds + Ord, const T: usize>( 6 | grain: &mut Grain, 7 | mut select: usize, 8 | ) -> (Mds, Mds) { 9 | let (xs, ys, mds) = loop { 10 | // Generate two [F; T] arrays of unique field elements. 11 | let (xs, ys) = loop { 12 | let mut vals: Vec<_> = (0..2 * T) 13 | .map(|_| grain.next_field_element_without_rejection()) 14 | .collect(); 15 | 16 | // Check that we have unique field elements. 17 | let mut unique = vals.clone(); 18 | unique.sort_unstable(); 19 | unique.dedup(); 20 | if vals.len() == unique.len() { 21 | let rhs = vals.split_off(T); 22 | break (vals, rhs); 23 | } 24 | }; 25 | 26 | // We need to ensure that the MDS is secure. Instead of checking the MDS against 27 | // the relevant algorithms directly, we witness a fixed number of MDS matrices 28 | // that we need to sample from the given Grain state before obtaining a secure 29 | // matrix. This can be determined out-of-band via the reference implementation in 30 | // Sage. 31 | if select != 0 { 32 | select -= 1; 33 | continue; 34 | } 35 | 36 | // Generate a Cauchy matrix, with elements a_ij in the form: 37 | // a_ij = 1/(x_i + y_j); x_i + y_j != 0 38 | // 39 | // It would be much easier to use the alternate definition: 40 | // a_ij = 1/(x_i - y_j); x_i - y_j != 0 41 | // 42 | // These are clearly equivalent on `y <- -y`, but it is easier to work with the 43 | // negative formulation, because ensuring that xs ∪ ys is unique implies that 44 | // x_i - y_j != 0 by construction (whereas the positive case does not hold). It 45 | // also makes computation of the matrix inverse simpler below (the theorem used 46 | // was formulated for the negative definition). 47 | // 48 | // However, the Poseidon paper and reference impl use the positive formulation, 49 | // and we want to rely on the reference impl for MDS security, so we use the same 50 | // formulation. 51 | let mut mds = [[F::ZERO; T]; T]; 52 | #[allow(clippy::needless_range_loop)] 53 | for i in 0..T { 54 | for j in 0..T { 55 | let sum = xs[i] + ys[j]; 56 | // We leverage the secure MDS selection counter to also check this. 57 | assert!(!sum.is_zero_vartime()); 58 | mds[i][j] = sum.invert().unwrap(); 59 | } 60 | } 61 | 62 | break (xs, ys, mds); 63 | }; 64 | 65 | // Compute the inverse. All square Cauchy matrices have a non-zero determinant and 66 | // thus are invertible. The inverse for a Cauchy matrix of the form: 67 | // 68 | // a_ij = 1/(x_i - y_j); x_i - y_j != 0 69 | // 70 | // has elements b_ij given by: 71 | // 72 | // b_ij = (x_j - y_i) A_j(y_i) B_i(x_j) (Schechter 1959, Theorem 1) 73 | // 74 | // where A_i(x) and B_i(x) are the Lagrange polynomials for xs and ys respectively. 75 | // 76 | // We adapt this to the positive Cauchy formulation by negating ys. 77 | let mut mds_inv = [[F::ZERO; T]; T]; 78 | let l = |xs: &[F], j, x: F| { 79 | let x_j = xs[j]; 80 | xs.iter().enumerate().fold(F::ONE, |acc, (m, x_m)| { 81 | if m == j { 82 | acc 83 | } else { 84 | let denominator: F = x_j - x_m; 85 | // We can invert freely; by construction, the elements of xs are distinct. 86 | acc * (x - x_m) * denominator.invert().unwrap() 87 | } 88 | }) 89 | }; 90 | let neg_ys: Vec<_> = ys.iter().map(|y| -*y).collect(); 91 | for i in 0..T { 92 | for j in 0..T { 93 | mds_inv[i][j] = (xs[j] - neg_ys[i]) * l(&xs, j, neg_ys[i]) * l(&neg_ys, i, xs[j]); 94 | } 95 | } 96 | 97 | (mds, mds_inv) 98 | } 99 | 100 | #[cfg(test)] 101 | mod tests { 102 | use super::super::pasta::Fp; 103 | 104 | use super::{generate_mds, Grain}; 105 | 106 | #[test] 107 | fn poseidon_mds() { 108 | const T: usize = 3; 109 | let mut grain = Grain::new(super::super::grain::SboxType::Pow, T as u16, 8, 56); 110 | let (mds, mds_inv) = generate_mds::(&mut grain, 0); 111 | 112 | // Verify that MDS * MDS^-1 = I. 113 | #[allow(clippy::needless_range_loop)] 114 | for i in 0..T { 115 | for j in 0..T { 116 | let expected = if i == j { Fp::one() } else { Fp::zero() }; 117 | assert_eq!( 118 | (0..T).fold(Fp::zero(), |acc, k| acc + (mds[i][k] * mds_inv[k][j])), 119 | expected 120 | ); 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/p128pow5t3.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use halo2curves::ff::FromUniformBytes; 4 | 5 | use super::{Mds, Spec}; 6 | 7 | /// The trait required for fields can handle a pow5 sbox, 3 field, 2 rate permutation 8 | pub trait P128Pow5T3Constants: FromUniformBytes<64> + Ord { 9 | fn partial_rounds() -> usize { 10 | 56 11 | } 12 | fn round_constants() -> Vec<[Self; 3]>; 13 | fn mds() -> Mds; 14 | fn mds_inv() -> Mds; 15 | } 16 | 17 | /// Poseidon-128 using the $x^5$ S-box, with a width of 3 field elements, and the 18 | /// standard number of rounds for 128-bit security "with margin". 19 | /// 20 | /// The standard specification for this set of parameters (on either of the Pasta 21 | /// fields) uses $R_F = 8, R_P = 56$. This is conveniently an even number of 22 | /// partial rounds, making it easier to construct a Halo 2 circuit. 23 | #[derive(Debug, Copy, Clone)] 24 | pub struct P128Pow5T3 { 25 | _marker: PhantomData, 26 | } 27 | 28 | impl Spec for P128Pow5T3 { 29 | fn full_rounds() -> usize { 30 | 8 31 | } 32 | 33 | fn partial_rounds() -> usize { 34 | Fp::partial_rounds() 35 | } 36 | 37 | fn sbox(val: Fp) -> Fp { 38 | val.pow_vartime([5]) 39 | } 40 | 41 | fn secure_mds() -> usize { 42 | unimplemented!() 43 | } 44 | 45 | fn constants() -> (Vec<[Fp; 3]>, Mds, Mds) { 46 | (Fp::round_constants(), Fp::mds(), Fp::mds_inv()) 47 | } 48 | } 49 | 50 | #[cfg(any(test, feature = "test"))] 51 | #[allow(unused_imports)] 52 | mod tests { 53 | use std::marker::PhantomData; 54 | 55 | use crate::params::Mds; 56 | use halo2curves::ff::{FromUniformBytes, PrimeField}; 57 | 58 | use super::super::pasta::{fp, test_vectors, Fp}; 59 | use crate::primitives::{permute, CachedSpec, ConstantLength, Hash, Spec}; 60 | 61 | /// The same Poseidon specification as poseidon::P128Pow5T3, but constructed 62 | /// such that its constants will be generated at runtime. 63 | #[derive(Debug, Copy, Clone)] 64 | pub struct P128Pow5T3Gen(PhantomData); 65 | 66 | type P128Pow5T3Pasta = super::P128Pow5T3; 67 | 68 | impl P128Pow5T3Gen { 69 | pub fn new() -> Self { 70 | P128Pow5T3Gen(PhantomData::default()) 71 | } 72 | } 73 | 74 | impl + Ord, const SECURE_MDS: usize> Spec 75 | for P128Pow5T3Gen 76 | { 77 | fn full_rounds() -> usize { 78 | 8 79 | } 80 | 81 | fn partial_rounds() -> usize { 82 | 56 83 | } 84 | 85 | fn sbox(val: F) -> F { 86 | val.pow_vartime(&[5]) 87 | } 88 | 89 | fn secure_mds() -> usize { 90 | SECURE_MDS 91 | } 92 | } 93 | 94 | impl CachedSpec for P128Pow5T3Pasta { 95 | fn cached_round_constants() -> &'static [[Fp; 3]] { 96 | &fp::ROUND_CONSTANTS 97 | } 98 | fn cached_mds() -> &'static Mds { 99 | &fp::MDS 100 | } 101 | fn cached_mds_inv() -> &'static Mds { 102 | &fp::MDS_INV 103 | } 104 | } 105 | 106 | #[test] 107 | fn verify_constants() { 108 | fn verify_constants_helper + Ord>( 109 | expected_round_constants: [[F; 3]; 64], 110 | expected_mds: [[F; 3]; 3], 111 | expected_mds_inv: [[F; 3]; 3], 112 | ) { 113 | let (round_constants, mds, mds_inv) = P128Pow5T3Gen::::constants(); 114 | 115 | for (actual, expected) in round_constants 116 | .iter() 117 | .flatten() 118 | .zip(expected_round_constants.iter().flatten()) 119 | { 120 | assert_eq!(actual, expected); 121 | } 122 | 123 | for (actual, expected) in mds.iter().flatten().zip(expected_mds.iter().flatten()) { 124 | assert_eq!(actual, expected); 125 | } 126 | 127 | for (actual, expected) in mds_inv 128 | .iter() 129 | .flatten() 130 | .zip(expected_mds_inv.iter().flatten()) 131 | { 132 | assert_eq!(actual, expected); 133 | } 134 | } 135 | 136 | verify_constants_helper(fp::ROUND_CONSTANTS, fp::MDS, fp::MDS_INV); 137 | //verify_constants_helper(fq::ROUND_CONSTANTS, fq::MDS, fq::MDS_INV); 138 | } 139 | 140 | #[test] 141 | fn test_against_reference() { 142 | { 143 | // , using parameters from 144 | // `generate_parameters_grain.sage 1 0 255 3 8 56 0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001`. 145 | // The test vector is generated by `sage poseidonperm_x5_pallas_3.sage --rust` 146 | 147 | let mut input = [ 148 | Fp::from_raw([ 149 | 0x0000_0000_0000_0000, 150 | 0x0000_0000_0000_0000, 151 | 0x0000_0000_0000_0000, 152 | 0x0000_0000_0000_0000, 153 | ]), 154 | Fp::from_raw([ 155 | 0x0000_0000_0000_0001, 156 | 0x0000_0000_0000_0000, 157 | 0x0000_0000_0000_0000, 158 | 0x0000_0000_0000_0000, 159 | ]), 160 | Fp::from_raw([ 161 | 0x0000_0000_0000_0002, 162 | 0x0000_0000_0000_0000, 163 | 0x0000_0000_0000_0000, 164 | 0x0000_0000_0000_0000, 165 | ]), 166 | ]; 167 | 168 | let expected_output = [ 169 | Fp::from_raw([ 170 | 0xaeb1_bc02_4aec_a456, 171 | 0xf7e6_9a71_d0b6_42a0, 172 | 0x94ef_b364_f966_240f, 173 | 0x2a52_6acd_0b64_b453, 174 | ]), 175 | Fp::from_raw([ 176 | 0x012a_3e96_28e5_b82a, 177 | 0xdcd4_2e7f_bed9_dafe, 178 | 0x76ff_7dae_343d_5512, 179 | 0x13c5_d156_8b4a_a430, 180 | ]), 181 | Fp::from_raw([ 182 | 0x3590_29a1_d34e_9ddd, 183 | 0xf7cf_dfe1_bda4_2c7b, 184 | 0x256f_cd59_7984_561a, 185 | 0x0a49_c868_c697_6544, 186 | ]), 187 | ]; 188 | 189 | permute::, 3, 2>(&mut input, &fp::MDS, &fp::ROUND_CONSTANTS); 190 | assert_eq!(input, expected_output); 191 | } 192 | 193 | /* { 194 | // , using parameters from 195 | // `generate_parameters_grain.sage 1 0 255 3 8 56 0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001`. 196 | // The test vector is generated by `sage poseidonperm_x5_vesta_3.sage --rust` 197 | 198 | let mut input = [ 199 | Fq::from_raw([ 200 | 0x0000_0000_0000_0000, 201 | 0x0000_0000_0000_0000, 202 | 0x0000_0000_0000_0000, 203 | 0x0000_0000_0000_0000, 204 | ]), 205 | Fq::from_raw([ 206 | 0x0000_0000_0000_0001, 207 | 0x0000_0000_0000_0000, 208 | 0x0000_0000_0000_0000, 209 | 0x0000_0000_0000_0000, 210 | ]), 211 | Fq::from_raw([ 212 | 0x0000_0000_0000_0002, 213 | 0x0000_0000_0000_0000, 214 | 0x0000_0000_0000_0000, 215 | 0x0000_0000_0000_0000, 216 | ]), 217 | ]; 218 | 219 | let expected_output = [ 220 | Fq::from_raw([ 221 | 0x0eb0_8ea8_13be_be59, 222 | 0x4d43_d197_3dd3_36c6, 223 | 0xeddd_74f2_2f8f_2ff7, 224 | 0x315a_1f4c_db94_2f7c, 225 | ]), 226 | Fq::from_raw([ 227 | 0xf9f1_26e6_1ea1_65f1, 228 | 0x413e_e0eb_7bbd_2198, 229 | 0x642a_dee0_dd13_aa48, 230 | 0x3be4_75f2_d764_2bde, 231 | ]), 232 | Fq::from_raw([ 233 | 0x14d5_4237_2a7b_a0d9, 234 | 0x5019_bfd4_e042_3fa0, 235 | 0x117f_db24_20d8_ea60, 236 | 0x25ab_8aec_e953_7168, 237 | ]), 238 | ]; 239 | 240 | permute::, 3, 2>(&mut input, &fq::MDS, &fq::ROUND_CONSTANTS); 241 | assert_eq!(input, expected_output); 242 | } 243 | */ 244 | } 245 | 246 | #[test] 247 | fn permute_test_vectors() { 248 | { 249 | let (round_constants, mds, _) = P128Pow5T3Pasta::constants(); 250 | 251 | for tv in test_vectors::fp::permute() { 252 | let mut state = [ 253 | Fp::from_repr(tv.initial_state[0]).unwrap(), 254 | Fp::from_repr(tv.initial_state[1]).unwrap(), 255 | Fp::from_repr(tv.initial_state[2]).unwrap(), 256 | ]; 257 | 258 | permute::(&mut state, &mds, &round_constants); 259 | 260 | for (expected, actual) in tv.final_state.iter().zip(state.iter()) { 261 | assert_eq!(&actual.to_repr(), expected); 262 | } 263 | } 264 | } 265 | /* 266 | { 267 | let (round_constants, mds, _) = super::P128Pow5T3::constants(); 268 | 269 | for tv in crate::poseidon::primitives::test_vectors::fq::permute() { 270 | let mut state = [ 271 | Fq::from_repr(tv.initial_state[0]).unwrap(), 272 | Fq::from_repr(tv.initial_state[1]).unwrap(), 273 | Fq::from_repr(tv.initial_state[2]).unwrap(), 274 | ]; 275 | 276 | permute::(&mut state, &mds, &round_constants); 277 | 278 | for (expected, actual) in tv.final_state.iter().zip(state.iter()) { 279 | assert_eq!(&actual.to_repr(), expected); 280 | } 281 | } 282 | } 283 | */ 284 | } 285 | 286 | #[test] 287 | fn hash_test_vectors() { 288 | for tv in test_vectors::fp::hash() { 289 | let message = [ 290 | Fp::from_repr(tv.input[0]).unwrap(), 291 | Fp::from_repr(tv.input[1]).unwrap(), 292 | ]; 293 | 294 | let result = Hash::<_, P128Pow5T3Pasta, ConstantLength<2>, 3, 2>::init().hash(message); 295 | 296 | assert_eq!(result.to_repr(), tv.output); 297 | } 298 | 299 | /* for tv in crate::poseidon::primitives::test_vectors::fq::hash() { 300 | let message = [ 301 | Fq::from_repr(tv.input[0]).unwrap(), 302 | Fq::from_repr(tv.input[1]).unwrap(), 303 | ]; 304 | 305 | let result = 306 | Hash::<_, super::P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash(message); 307 | 308 | assert_eq!(result.to_repr(), tv.output); 309 | } 310 | */ 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/p128pow5t3_compact.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use halo2curves::ff::{FromUniformBytes, PrimeField}; 4 | 5 | use super::p128pow5t3::P128Pow5T3Constants; 6 | use super::{Mds, Spec}; 7 | 8 | /// Poseidon-128 using the $x^5$ S-box, with a width of 3 field elements, and the 9 | /// standard number of rounds for 128-bit security "with margin". 10 | /// 11 | #[derive(Debug, Copy, Clone)] 12 | pub struct P128Pow5T3Compact { 13 | _marker: PhantomData, 14 | } 15 | 16 | impl + Ord> Spec 17 | for P128Pow5T3Compact 18 | { 19 | fn full_rounds() -> usize { 20 | 8 21 | } 22 | 23 | fn partial_rounds() -> usize { 24 | Fp::partial_rounds() 25 | } 26 | 27 | fn sbox(val: Fp) -> Fp { 28 | // much faster than val.pow_vartime([5]) 29 | let a = val * val; 30 | let b = a * a; 31 | b * val 32 | } 33 | 34 | fn secure_mds() -> usize { 35 | unimplemented!() 36 | } 37 | 38 | fn constants() -> (Vec<[Fp; 3]>, Mds, Mds) { 39 | let (mut rc, mds, inv) = (Fp::round_constants(), Fp::mds(), Fp::mds_inv()); 40 | 41 | let first_partial = Self::full_rounds() / 2; 42 | let after_partials = first_partial + Self::partial_rounds(); 43 | 44 | // Propagate the constants of each partial round into the next. 45 | for i in first_partial..after_partials { 46 | // Extract the constants rc[i][1] and rc[i][2] that do not pass through the S-box. 47 | // Leave the value 0 in their place. 48 | // rc[i][0] stays in place. 49 | let rc_tail = vec_remove_tail(&mut rc[i]); 50 | 51 | // Pass forward through the MDS matrix. 52 | let rc_carry = mat_mul(&mds, &rc_tail); 53 | 54 | // Accumulate the carried constants into the next round. 55 | vec_accumulate(&mut rc[i + 1], &rc_carry); 56 | } 57 | // Now constants have accumulated into the next full round. 58 | 59 | (rc, mds, inv) 60 | } 61 | } 62 | 63 | fn mat_mul(mat: &Mds, input: &[Fp; T]) -> [Fp; T] { 64 | let mut out = [Fp::ZERO; T]; 65 | #[allow(clippy::needless_range_loop)] 66 | for i in 0..T { 67 | for j in 0..T { 68 | out[i] += mat[i][j] * input[j]; 69 | } 70 | } 71 | out 72 | } 73 | 74 | fn vec_accumulate(a: &mut [Fp; T], b: &[Fp; T]) { 75 | for i in 0..T { 76 | a[i] += b[i]; 77 | } 78 | } 79 | 80 | fn vec_remove_tail(a: &mut [Fp; T]) -> [Fp; T] { 81 | let mut tail = [Fp::ZERO; T]; 82 | for i in 1..T { 83 | tail[i] = a[i]; 84 | a[i] = Fp::ZERO; 85 | } 86 | tail 87 | } 88 | -------------------------------------------------------------------------------- /poseidon-base/src/primitives/pasta/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::hash::HashSpec; 2 | use halo2curves::{group::ff::PrimeField, pasta}; 3 | use once_cell::sync::Lazy; 4 | pub use pasta::pallas; 5 | pub use pasta::Fp; 6 | 7 | pub mod fp; 8 | pub mod test_vectors; 9 | 10 | use crate::primitives::p128pow5t3::P128Pow5T3Constants; 11 | use crate::primitives::{CachedSpec, Mds, P128Pow5T3Compact, Spec}; 12 | 13 | impl P128Pow5T3Constants for Fp { 14 | fn round_constants() -> Vec<[Self; 3]> { 15 | fp::ROUND_CONSTANTS.to_vec() 16 | } 17 | fn mds() -> Mds { 18 | fp::MDS 19 | } 20 | fn mds_inv() -> Mds { 21 | fp::MDS_INV 22 | } 23 | } 24 | 25 | impl CachedSpec for HashSpec { 26 | #[cfg(not(feature = "short"))] 27 | fn cached_round_constants() -> &'static [[Fp; 3]] { 28 | &fp::ROUND_CONSTANTS 29 | } 30 | 31 | #[cfg(feature = "short")] 32 | fn cached_round_constants() -> &'static [[Fp; 3]] { 33 | static ROUND_CONSTANTS: Lazy> = Lazy::new(|| P128Pow5T3Compact::constants().0); 34 | &ROUND_CONSTANTS 35 | } 36 | 37 | fn cached_mds() -> &'static Mds { 38 | &fp::MDS 39 | } 40 | fn cached_mds_inv() -> &'static Mds { 41 | &fp::MDS_INV 42 | } 43 | } 44 | 45 | #[allow(dead_code)] 46 | fn sqrt_tonelli_shanks>(f: &F, tm1d2: S) -> subtle::CtOption { 47 | use subtle::{Choice, ConditionallySelectable, ConstantTimeEq}; 48 | 49 | // w = self^((t - 1) // 2) 50 | let w = f.pow_vartime(tm1d2); 51 | 52 | let mut v = F::S; 53 | let mut x = w * f; 54 | let mut b = x * w; 55 | 56 | // Initialize z as the 2^S root of unity. 57 | let mut z = F::ROOT_OF_UNITY; 58 | 59 | for max_v in (1..=F::S).rev() { 60 | let mut k = 1; 61 | let mut tmp = b.square(); 62 | let mut j_less_than_v: Choice = 1.into(); 63 | 64 | for j in 2..max_v { 65 | let tmp_is_one = tmp.ct_eq(&F::ONE); 66 | let squared = F::conditional_select(&tmp, &z, tmp_is_one).square(); 67 | tmp = F::conditional_select(&squared, &tmp, tmp_is_one); 68 | let new_z = F::conditional_select(&z, &squared, tmp_is_one); 69 | j_less_than_v &= !j.ct_eq(&v); 70 | k = u32::conditional_select(&j, &k, tmp_is_one); 71 | z = F::conditional_select(&z, &new_z, j_less_than_v); 72 | } 73 | 74 | let result = x * z; 75 | x = F::conditional_select(&result, &x, b.ct_eq(&F::ONE)); 76 | z = z.square(); 77 | b *= z; 78 | v = k; 79 | } 80 | 81 | subtle::CtOption::new( 82 | x, 83 | (x * x).ct_eq(f), // Only return Some if it's the square root. 84 | ) 85 | } 86 | -------------------------------------------------------------------------------- /poseidon-circuit/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "poseidon-circuit" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | ff.workspace = true 8 | halo2_proofs.workspace = true 9 | thiserror.workspace = true 10 | log.workspace = true 11 | poseidon-base = { path = "../poseidon-base" } 12 | rand_xorshift.workspace = true 13 | rand.workspace = true 14 | 15 | [features] 16 | default = ["halo2_proofs/parallel_syn", "short"] 17 | # Use an implementation using fewer rows (8) per permutation. 18 | short = ["poseidon-base/short"] 19 | # printout the layout of circuits for demo and some unittests 20 | print_layout = ["halo2_proofs/dev-graph"] 21 | legacy = [] 22 | # "halo2_proofs/parallel_syn" is turned on by default for compilation 23 | # "parallel_syn" can be turned on/off via `zkevm-circuits` 24 | parallel_syn = ["halo2_proofs/parallel_syn"] 25 | 26 | [dev-dependencies] 27 | bencher.workspace = true 28 | lazy_static.workspace = true 29 | rand.workspace = true 30 | rand_chacha.workspace = true 31 | subtle.workspace = true 32 | poseidon-base = { path = "../poseidon-base", features = ["test"] } 33 | 34 | [[bench]] 35 | name = "hash" 36 | harness = false 37 | -------------------------------------------------------------------------------- /poseidon-circuit/benches/hash.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate bencher; 3 | 4 | use bencher::Bencher; 5 | use halo2_proofs::arithmetic::Field; 6 | use halo2_proofs::halo2curves::bn256::Fr; 7 | use lazy_static::lazy_static; 8 | use poseidon_base::primitives::{ConstantLengthIden3, Hash, P128Pow5T3}; 9 | use rand::SeedableRng; 10 | use rand_chacha::ChaCha8Rng; 11 | 12 | lazy_static! { 13 | static ref RNDFRS: [Fr; 16] = { 14 | let rng = ChaCha8Rng::from_seed([101u8; 32]); 15 | [(); 16].map(|_| Fr::random(rng.clone())) 16 | }; 17 | } 18 | 19 | macro_rules! hashes { 20 | ( $fname:ident, $n:expr ) => { 21 | fn $fname(bench: &mut Bencher) { 22 | bench.iter(|| { 23 | Hash::, ConstantLengthIden3<$n>, 3, 2>::init().hash( 24 | Vec::from(&RNDFRS.as_slice()[..$n]).try_into().unwrap(), 25 | Fr::zero(), 26 | ) 27 | }); 28 | } 29 | }; 30 | } 31 | 32 | hashes!(h02, 2); 33 | hashes!(h03, 3); 34 | hashes!(h04, 4); 35 | hashes!(h05, 5); 36 | hashes!(h06, 6); 37 | hashes!(h07, 7); 38 | 39 | fn vec_ref(bench: &mut Bencher) { 40 | bench.iter(|| Vec::from(&RNDFRS.as_slice()[..8])); 41 | } 42 | 43 | fn init_ref(bench: &mut Bencher) { 44 | bench.iter(|| Hash::, ConstantLengthIden3<3>, 3, 2>::init()); 45 | } 46 | 47 | benchmark_group!( 48 | hashes_bench, 49 | h02, 50 | h03, 51 | h04, 52 | h05, 53 | h06, 54 | h07, 55 | vec_ref, 56 | init_ref 57 | ); 58 | benchmark_main!(hashes_bench); 59 | -------------------------------------------------------------------------------- /poseidon-circuit/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! mpt demo circuits 2 | // 3 | 4 | #![allow(dead_code)] 5 | #![allow(unused_macros)] 6 | #![deny(missing_docs)] 7 | #![deny(unsafe_code)] 8 | 9 | pub mod hash; 10 | pub mod poseidon; 11 | 12 | pub use halo2_proofs::halo2curves::bn256::Fr as Bn256Fr; 13 | pub use hash::{Hashable, HASHABLE_DOMAIN_SPEC}; 14 | 15 | /// a default step can be compatible with codehash circuit 16 | pub const DEFAULT_STEP: usize = 62; 17 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon.rs: -------------------------------------------------------------------------------- 1 | //! The Poseidon algebraic hash function. 2 | 3 | use std::convert::TryInto; 4 | use std::fmt; 5 | use std::marker::PhantomData; 6 | 7 | use ff::{Field, FromUniformBytes}; 8 | use halo2_proofs::{ 9 | circuit::{AssignedCell, Chip, Layouter}, 10 | plonk::{ConstraintSystem, Error}, 11 | }; 12 | 13 | use poseidon_base::primitives::{ 14 | Absorbing, ConstantLength, Domain, Spec, SpongeMode, Squeezing, State, 15 | }; 16 | 17 | mod pow5; 18 | pub use pow5::{Pow5Chip, Pow5Config, StateWord, Var}; 19 | 20 | mod septidon; 21 | pub use poseidon_base::params::CachedConstants; 22 | pub use septidon::SeptidonChip; 23 | 24 | use std::fmt::Debug as DebugT; 25 | 26 | /// A word from the padded input to a Poseidon sponge. 27 | #[derive(Clone, Debug)] 28 | pub enum PaddedWord { 29 | /// A message word provided by the prover. 30 | Message(AssignedCell), 31 | /// A padding word, that will be fixed in the circuit parameters. 32 | Padding(F), 33 | } 34 | 35 | /// This trait is the interface to chips that implement a permutation. 36 | pub trait PermuteChip< 37 | F: FromUniformBytes<64> + Ord, 38 | S: Spec, 39 | const T: usize, 40 | const RATE: usize, 41 | >: Chip + Clone + DebugT + PoseidonInstructions 42 | { 43 | /// Configure the permutation chip. 44 | fn configure(meta: &mut ConstraintSystem) -> Self::Config; 45 | 46 | /// Get a chip from its config. 47 | fn construct(config: Self::Config) -> Self; 48 | } 49 | 50 | /// The set of circuit instructions required to use the Poseidon permutation. 51 | pub trait PoseidonInstructions< 52 | F: FromUniformBytes<64> + Ord, 53 | S: Spec, 54 | const T: usize, 55 | const RATE: usize, 56 | >: Chip 57 | { 58 | /// Variable representing the word over which the Poseidon permutation operates. 59 | type Word: Clone 60 | + fmt::Debug 61 | + From> 62 | + Into> 63 | + Send 64 | + Sync; 65 | 66 | /// Applies the Poseidon permutation to the given state. 67 | fn permute( 68 | &self, 69 | layouter: &mut impl Layouter, 70 | initial_states: &State, 71 | ) -> Result, Error>; 72 | 73 | /// Applies the Poseidon permutation to the given states. 74 | fn permute_batch( 75 | &self, 76 | layouter: &mut impl Layouter, 77 | initial_states: &[State], 78 | ) -> Result>, Error> { 79 | initial_states 80 | .iter() 81 | .map(|initial_state| self.permute(layouter, initial_state)) 82 | .collect::, Error>>() 83 | } 84 | } 85 | 86 | /// The set of circuit instructions required to use the [`Sponge`] and [`Hash`] gadgets. 87 | /// 88 | /// [`Hash`]: self::Hash 89 | pub trait PoseidonSpongeInstructions< 90 | F: FromUniformBytes<64> + Ord, 91 | S: Spec, 92 | D: Domain, 93 | const T: usize, 94 | const RATE: usize, 95 | >: PoseidonInstructions 96 | { 97 | /// Returns the initial empty state for the given domain. 98 | fn initial_state(&self, layouter: &mut impl Layouter) 99 | -> Result, Error>; 100 | 101 | /// Adds the given input to the state. 102 | fn add_input( 103 | &self, 104 | layouter: &mut impl Layouter, 105 | initial_state: &State, 106 | input: &Absorbing, RATE>, 107 | ) -> Result, Error>; 108 | 109 | /// Extracts sponge output from the given state. 110 | fn get_output(state: &State) -> Squeezing; 111 | } 112 | 113 | /// A word over which the Poseidon permutation operates. 114 | #[derive(Debug)] 115 | pub struct Word< 116 | F: FromUniformBytes<64> + Ord, 117 | PoseidonChip: PoseidonInstructions, 118 | S: Spec, 119 | const T: usize, 120 | const RATE: usize, 121 | > { 122 | inner: PoseidonChip::Word, 123 | } 124 | 125 | impl< 126 | F: FromUniformBytes<64> + Ord, 127 | PoseidonChip: PoseidonInstructions, 128 | S: Spec, 129 | const T: usize, 130 | const RATE: usize, 131 | > Word 132 | { 133 | /// The word contained in this gadget. 134 | pub fn inner(&self) -> PoseidonChip::Word { 135 | self.inner.clone() 136 | } 137 | 138 | /// Construct a [`Word`] gadget from the inner word. 139 | pub fn from_inner(inner: PoseidonChip::Word) -> Self { 140 | Self { inner } 141 | } 142 | } 143 | 144 | fn poseidon_sponge< 145 | F: FromUniformBytes<64> + Ord, 146 | PoseidonChip: PoseidonSpongeInstructions, 147 | S: Spec, 148 | D: Domain, 149 | const T: usize, 150 | const RATE: usize, 151 | >( 152 | chip: &PoseidonChip, 153 | mut layouter: impl Layouter, 154 | state: &mut State, 155 | input: Option<&Absorbing, RATE>>, 156 | ) -> Result, Error> { 157 | if let Some(input) = input { 158 | *state = chip.add_input(&mut layouter, state, input)?; 159 | } 160 | *state = chip.permute(&mut layouter, state)?; 161 | Ok(PoseidonChip::get_output(state)) 162 | } 163 | 164 | /// A Poseidon sponge. 165 | #[derive(Debug)] 166 | pub struct Sponge< 167 | F: FromUniformBytes<64> + Ord, 168 | PoseidonChip: PoseidonSpongeInstructions, 169 | S: Spec, 170 | M: SpongeMode, 171 | D: Domain, 172 | const T: usize, 173 | const RATE: usize, 174 | > { 175 | chip: PoseidonChip, 176 | mode: M, 177 | state: State, 178 | _marker: PhantomData, 179 | } 180 | 181 | impl< 182 | F: FromUniformBytes<64> + Ord, 183 | PoseidonChip: PoseidonSpongeInstructions, 184 | S: Spec, 185 | D: Domain, 186 | const T: usize, 187 | const RATE: usize, 188 | > Sponge, RATE>, D, T, RATE> 189 | { 190 | /// Constructs a new duplex sponge for the given Poseidon specification. 191 | pub fn new(chip: PoseidonChip, mut layouter: impl Layouter) -> Result { 192 | chip.initial_state(&mut layouter).map(|state| Sponge { 193 | chip, 194 | mode: Absorbing( 195 | (0..RATE) 196 | .map(|_| None) 197 | .collect::>() 198 | .try_into() 199 | .unwrap(), 200 | ), 201 | state, 202 | _marker: PhantomData::default(), 203 | }) 204 | } 205 | 206 | /// Absorbs an element into the sponge. 207 | pub fn absorb( 208 | &mut self, 209 | mut layouter: impl Layouter, 210 | value: PaddedWord, 211 | ) -> Result<(), Error> { 212 | for entry in self.mode.0.iter_mut() { 213 | if entry.is_none() { 214 | *entry = Some(value); 215 | return Ok(()); 216 | } 217 | } 218 | 219 | // We've already absorbed as many elements as we can 220 | let _ = poseidon_sponge( 221 | &self.chip, 222 | layouter.namespace(|| "PoseidonSponge"), 223 | &mut self.state, 224 | Some(&self.mode), 225 | )?; 226 | self.mode = Absorbing::init_with(value); 227 | 228 | Ok(()) 229 | } 230 | 231 | /// Transitions the sponge into its squeezing state. 232 | #[allow(clippy::type_complexity)] 233 | pub fn finish_absorbing( 234 | mut self, 235 | mut layouter: impl Layouter, 236 | ) -> Result, D, T, RATE>, Error> 237 | { 238 | let mode = poseidon_sponge( 239 | &self.chip, 240 | layouter.namespace(|| "PoseidonSponge"), 241 | &mut self.state, 242 | Some(&self.mode), 243 | )?; 244 | 245 | Ok(Sponge { 246 | chip: self.chip, 247 | mode, 248 | state: self.state, 249 | _marker: PhantomData::default(), 250 | }) 251 | } 252 | } 253 | 254 | impl< 255 | F: FromUniformBytes<64> + Ord, 256 | PoseidonChip: PoseidonSpongeInstructions, 257 | S: Spec, 258 | D: Domain, 259 | const T: usize, 260 | const RATE: usize, 261 | > Sponge, D, T, RATE> 262 | { 263 | /// Squeezes an element from the sponge. 264 | pub fn squeeze(&mut self, mut layouter: impl Layouter) -> Result, Error> { 265 | loop { 266 | for entry in self.mode.0.iter_mut() { 267 | if let Some(inner) = entry.take() { 268 | return Ok(inner.into()); 269 | } 270 | } 271 | 272 | // We've already squeezed out all available elements 273 | self.mode = poseidon_sponge( 274 | &self.chip, 275 | layouter.namespace(|| "PoseidonSponge"), 276 | &mut self.state, 277 | None, 278 | )?; 279 | } 280 | } 281 | } 282 | 283 | /// A Poseidon hash function, built around a sponge. 284 | #[derive(Debug)] 285 | pub struct Hash< 286 | F: FromUniformBytes<64> + Ord, 287 | PoseidonChip: PoseidonSpongeInstructions, 288 | S: Spec, 289 | D: Domain, 290 | const T: usize, 291 | const RATE: usize, 292 | > { 293 | sponge: Sponge, RATE>, D, T, RATE>, 294 | } 295 | 296 | impl< 297 | F: FromUniformBytes<64> + Ord, 298 | PoseidonChip: PoseidonSpongeInstructions, 299 | S: Spec, 300 | D: Domain, 301 | const T: usize, 302 | const RATE: usize, 303 | > Hash 304 | { 305 | /// Initializes a new hasher. 306 | pub fn init(chip: PoseidonChip, layouter: impl Layouter) -> Result { 307 | Sponge::new(chip, layouter).map(|sponge| Hash { sponge }) 308 | } 309 | } 310 | 311 | impl< 312 | F: FromUniformBytes<64> + Ord, 313 | PoseidonChip: PoseidonSpongeInstructions, T, RATE>, 314 | S: Spec, 315 | const T: usize, 316 | const RATE: usize, 317 | const L: usize, 318 | > Hash, T, RATE> 319 | { 320 | /// Hashes the given input. 321 | pub fn hash( 322 | mut self, 323 | mut layouter: impl Layouter, 324 | message: [AssignedCell; L], 325 | ) -> Result, Error> { 326 | for (i, value) in message 327 | .into_iter() 328 | .map(PaddedWord::Message) 329 | .chain( as Domain>::padding(L).map(PaddedWord::Padding)) 330 | .enumerate() 331 | { 332 | self.sponge 333 | .absorb(layouter.namespace(|| format!("absorb_{i}")), value)?; 334 | } 335 | self.sponge 336 | .finish_absorbing(layouter.namespace(|| "finish absorbing"))? 337 | .squeeze(layouter.namespace(|| "squeeze")) 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/pow5.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryInto; 2 | use std::iter; 3 | 4 | use ff::{FromUniformBytes, PrimeField}; 5 | use halo2_proofs::{ 6 | circuit::{AssignedCell, Cell, Chip, Layouter, Region, Value}, 7 | plonk::{Advice, Any, Column, ConstraintSystem, Error, Expression, Fixed, Selector}, 8 | poly::Rotation, 9 | }; 10 | use poseidon_base::primitives::{Absorbing, Domain, Mds, Spec, Squeezing, State}; 11 | 12 | use super::{PaddedWord, PermuteChip, PoseidonInstructions, PoseidonSpongeInstructions}; 13 | 14 | /// Trait for a variable in the circuit. 15 | pub trait Var: Clone + std::fmt::Debug + From> { 16 | /// The cell at which this variable was allocated. 17 | fn cell(&self) -> Cell; 18 | 19 | /// The value allocated to this variable. 20 | fn value(&self) -> Value; 21 | } 22 | 23 | impl Var for AssignedCell { 24 | fn cell(&self) -> Cell { 25 | self.cell() 26 | } 27 | 28 | fn value(&self) -> Value { 29 | self.value().cloned() 30 | } 31 | } 32 | 33 | /// Configuration for a [`Pow5Chip`]. 34 | #[derive(Clone, Debug)] 35 | pub struct Pow5Config { 36 | pub(crate) state: [Column; WIDTH], 37 | partial_sbox: Column, 38 | rc_a: [Column; WIDTH], 39 | rc_b: [Column; WIDTH], 40 | s_full: Selector, 41 | s_partial: Selector, 42 | s_partial_single: Selector, 43 | s_pad_and_add: Selector, 44 | 45 | half_full_rounds: usize, 46 | half_partial_rounds: usize, 47 | alpha: [u64; 4], 48 | round_constants: Vec<[F; WIDTH]>, 49 | m_reg: Mds, 50 | m_inv: Mds, 51 | } 52 | 53 | /// A Poseidon chip using an $x^5$ S-Box. 54 | /// 55 | /// The chip is implemented using a single round per row for full rounds, and two rounds 56 | /// per row for partial rounds. 57 | #[derive(Clone, Debug)] 58 | pub struct Pow5Chip { 59 | config: Pow5Config, 60 | } 61 | 62 | impl + Ord, const WIDTH: usize, const RATE: usize> 63 | Pow5Chip 64 | { 65 | /// Configures this chip for use in a circuit. 66 | /// 67 | /// # Side-effects 68 | /// 69 | /// All columns in `state` will be equality-enabled. 70 | // 71 | // TODO: Does the rate need to be hard-coded here, or only the width? It probably 72 | // needs to be known wherever we implement the hashing gadget, but it isn't strictly 73 | // necessary for the permutation. 74 | pub fn configure>( 75 | meta: &mut ConstraintSystem, 76 | state: [Column; WIDTH], 77 | partial_sbox: Column, 78 | rc_a: [Column; WIDTH], 79 | rc_b: [Column; WIDTH], 80 | ) -> Pow5Config { 81 | assert_eq!(RATE, WIDTH - 1); 82 | // Generate constants for the Poseidon permutation. 83 | // This gadget requires R_F and R_P to be even. 84 | assert!(S::full_rounds() & 1 == 0); 85 | //assert!(S::partial_rounds() & 1 == 0); 86 | let half_full_rounds = S::full_rounds() / 2; 87 | let half_partial_rounds = S::partial_rounds() / 2; 88 | let (round_constants, m_reg, m_inv) = S::constants(); 89 | 90 | // This allows state words to be initialized (by constraining them equal to fixed 91 | // values), and used in a permutation from an arbitrary region. rc_a is used in 92 | // every permutation round, while rc_b is empty in the initial and final full 93 | // rounds, so we use rc_b as "scratch space" for fixed values (enabling potential 94 | // layouter optimisations). 95 | for column in iter::empty() 96 | .chain(state.iter().cloned().map(Column::::from)) 97 | .chain(rc_b.iter().cloned().map(Column::::from)) 98 | { 99 | meta.enable_equality(column); 100 | } 101 | 102 | let s_full = meta.complex_selector(); 103 | let s_partial = meta.complex_selector(); 104 | let s_partial_single = meta.complex_selector(); 105 | let s_pad_and_add = meta.complex_selector(); 106 | 107 | let alpha = [5, 0, 0, 0]; 108 | let pow_5 = |v: Expression| { 109 | let v2 = v.clone() * v.clone(); 110 | v2.clone() * v2 * v 111 | }; 112 | 113 | meta.create_gate("full round", |meta| { 114 | let s_full = meta.query_selector(s_full); 115 | 116 | (0..WIDTH) 117 | .map(|next_idx| { 118 | let state_next = meta.query_advice(state[next_idx], Rotation::next()); 119 | let expr = (0..WIDTH) 120 | .map(|idx| { 121 | let state_cur = meta.query_advice(state[idx], Rotation::cur()); 122 | let rc_a = meta.query_fixed(rc_a[idx], Rotation::cur()); 123 | pow_5(state_cur + rc_a) * m_reg[next_idx][idx] 124 | }) 125 | .reduce(|acc, term| acc + term) 126 | .expect("WIDTH > 0"); 127 | s_full.clone() * (expr - state_next) 128 | }) 129 | .collect::>() 130 | }); 131 | 132 | meta.create_gate("partial rounds", |meta| { 133 | let cur_0 = meta.query_advice(state[0], Rotation::cur()); 134 | let mid_0 = meta.query_advice(partial_sbox, Rotation::cur()); 135 | 136 | let rc_a0 = meta.query_fixed(rc_a[0], Rotation::cur()); 137 | let rc_b0 = meta.query_fixed(rc_b[0], Rotation::cur()); 138 | 139 | let s_partial = meta.query_selector(s_partial); 140 | 141 | use halo2_proofs::plonk::VirtualCells; 142 | let mid = |idx: usize, meta: &mut VirtualCells| { 143 | let mid = mid_0.clone() * m_reg[idx][0]; 144 | (1..WIDTH).fold(mid, |acc, cur_idx| { 145 | let cur = meta.query_advice(state[cur_idx], Rotation::cur()); 146 | let rc_a = meta.query_fixed(rc_a[cur_idx], Rotation::cur()); 147 | acc + (cur + rc_a) * m_reg[idx][cur_idx] 148 | }) 149 | }; 150 | 151 | let next = |idx: usize, meta: &mut VirtualCells| { 152 | (0..WIDTH) 153 | .map(|next_idx| { 154 | let next = meta.query_advice(state[next_idx], Rotation::next()); 155 | next * m_inv[idx][next_idx] 156 | }) 157 | .reduce(|acc, next| acc + next) 158 | .expect("WIDTH > 0") 159 | }; 160 | 161 | let partial_round_linear = |idx: usize, meta: &mut VirtualCells| { 162 | let rc_b = meta.query_fixed(rc_b[idx], Rotation::cur()); 163 | mid(idx, meta) + rc_b - next(idx, meta) 164 | }; 165 | 166 | std::iter::empty() 167 | // state[0] round a 168 | .chain(Some(pow_5(cur_0 + rc_a0) - mid_0.clone())) 169 | // state[0] round b 170 | .chain(Some(pow_5(mid(0, meta) + rc_b0) - next(0, meta))) 171 | .chain((1..WIDTH).map(|idx| partial_round_linear(idx, meta))) 172 | .map(|exp| s_partial.clone() * exp) 173 | .collect::>() 174 | }); 175 | 176 | meta.create_gate("partial round single", |meta| { 177 | let s_partial_single = meta.query_selector(s_partial_single); 178 | 179 | (0..WIDTH) 180 | .map(|next_idx| { 181 | let state_next = meta.query_advice(state[next_idx], Rotation::next()); 182 | let cur_0 = meta.query_advice(state[0], Rotation::cur()); 183 | let rc_a0 = meta.query_fixed(rc_a[0], Rotation::cur()); 184 | 185 | let expr = pow_5(cur_0 + rc_a0) * m_reg[next_idx][0]; 186 | let expr = expr 187 | + (1..WIDTH) 188 | .map(|idx| { 189 | let state_cur = meta.query_advice(state[idx], Rotation::cur()); 190 | let rc_a = meta.query_fixed(rc_a[idx], Rotation::cur()); 191 | (state_cur + rc_a) * m_reg[next_idx][idx] 192 | }) 193 | .reduce(|acc, term| acc + term) 194 | .expect("WIDTH > 0"); 195 | s_partial_single.clone() * (expr - state_next) 196 | }) 197 | .collect::>() 198 | }); 199 | 200 | meta.create_gate("pad-and-add", |meta| { 201 | let initial_state_rate = meta.query_advice(state[RATE], Rotation::prev()); 202 | let output_state_rate = meta.query_advice(state[RATE], Rotation::next()); 203 | 204 | let s_pad_and_add = meta.query_selector(s_pad_and_add); 205 | 206 | let pad_and_add = |idx: usize| { 207 | let initial_state = meta.query_advice(state[idx], Rotation::prev()); 208 | let input = meta.query_advice(state[idx], Rotation::cur()); 209 | let output_state = meta.query_advice(state[idx], Rotation::next()); 210 | 211 | // We pad the input by storing the required padding in fixed columns and 212 | // then constraining the corresponding input columns to be equal to it. 213 | initial_state + input - output_state 214 | }; 215 | 216 | (0..RATE) 217 | .map(pad_and_add) 218 | // The capacity element is never altered by the input. 219 | .chain(Some(initial_state_rate - output_state_rate)) 220 | .map(|exp| s_pad_and_add.clone() * exp) 221 | .collect::>() 222 | }); 223 | 224 | Pow5Config { 225 | state, 226 | partial_sbox, 227 | rc_a, 228 | rc_b, 229 | s_full, 230 | s_partial, 231 | s_partial_single, 232 | s_pad_and_add, 233 | half_full_rounds, 234 | half_partial_rounds, 235 | alpha, 236 | round_constants, 237 | m_reg, 238 | m_inv, 239 | } 240 | } 241 | 242 | /// Construct a [`Pow5Chip`]. 243 | pub fn construct(config: Pow5Config) -> Self { 244 | Pow5Chip { config } 245 | } 246 | } 247 | 248 | impl + Ord, const WIDTH: usize, const RATE: usize> Chip 249 | for Pow5Chip 250 | { 251 | type Config = Pow5Config; 252 | type Loaded = (); 253 | 254 | fn config(&self) -> &Self::Config { 255 | &self.config 256 | } 257 | 258 | fn loaded(&self) -> &Self::Loaded { 259 | &() 260 | } 261 | } 262 | 263 | impl + Ord, S: Spec> PermuteChip 264 | for Pow5Chip 265 | { 266 | fn configure(meta: &mut ConstraintSystem) -> Self::Config { 267 | let state = [0; 3].map(|_| meta.advice_column()); 268 | let partial_sbox = meta.advice_column(); 269 | let constants = [0; 6].map(|_| meta.fixed_column()); 270 | 271 | Pow5Chip::configure::( 272 | meta, 273 | state, 274 | partial_sbox, 275 | constants[..3].try_into().unwrap(), //rc_a 276 | constants[3..].try_into().unwrap(), //rc_b 277 | ) 278 | } 279 | 280 | fn construct(config: Self::Config) -> Self { 281 | Self::construct(config) 282 | } 283 | } 284 | 285 | impl< 286 | F: FromUniformBytes<64> + Ord, 287 | S: Spec, 288 | const WIDTH: usize, 289 | const RATE: usize, 290 | > PoseidonInstructions for Pow5Chip 291 | { 292 | type Word = StateWord; 293 | 294 | fn permute( 295 | &self, 296 | layouter: &mut impl Layouter, 297 | initial_state: &State, 298 | ) -> Result, Error> { 299 | let config = self.config(); 300 | 301 | layouter.assign_region( 302 | || "permute state", 303 | |mut region| { 304 | // Load the initial state into this region. 305 | let state = Pow5State::load(&mut region, config, initial_state)?; 306 | 307 | let state = (0..config.half_full_rounds).fold(Ok(state), |res, r| { 308 | res.and_then(|state| state.full_round(&mut region, config, r, r)) 309 | })?; 310 | 311 | let state = (0..config.half_partial_rounds).fold(Ok(state), |res, r| { 312 | res.and_then(|state| { 313 | state.partial_round( 314 | &mut region, 315 | config, 316 | config.half_full_rounds + 2 * r, 317 | config.half_full_rounds + r, 318 | ) 319 | }) 320 | })?; 321 | 322 | let state = if config.half_partial_rounds * 2 < S::partial_rounds() { 323 | state.partial_round_single( 324 | &mut region, 325 | config, 326 | config.half_full_rounds + 2 * config.half_partial_rounds, 327 | config.half_full_rounds + config.half_partial_rounds, 328 | ) 329 | } else { 330 | Ok(state) 331 | }?; 332 | 333 | let odd_offset = S::partial_rounds() & 1; 334 | 335 | let state = (0..config.half_full_rounds).fold(Ok(state), |res, r| { 336 | res.and_then(|state| { 337 | state.full_round( 338 | &mut region, 339 | config, 340 | config.half_full_rounds 341 | + 2 * config.half_partial_rounds 342 | + odd_offset 343 | + r, 344 | config.half_full_rounds + config.half_partial_rounds + odd_offset + r, 345 | ) 346 | }) 347 | })?; 348 | 349 | Ok(state.0) 350 | }, 351 | ) 352 | } 353 | } 354 | 355 | impl< 356 | F: FromUniformBytes<64> + Ord, 357 | S: Spec, 358 | D: Domain, 359 | const WIDTH: usize, 360 | const RATE: usize, 361 | > PoseidonSpongeInstructions for Pow5Chip 362 | { 363 | fn initial_state( 364 | &self, 365 | layouter: &mut impl Layouter, 366 | ) -> Result, Error> { 367 | let config = self.config(); 368 | let state = layouter.assign_region( 369 | || format!("initial state for domain {}", D::name()), 370 | |mut region| { 371 | let mut state = Vec::with_capacity(WIDTH); 372 | let mut load_state_word = |i: usize, value: F| -> Result<_, Error> { 373 | let var = region.assign_advice_from_constant( 374 | || format!("state_{i}"), 375 | config.state[i], 376 | 0, 377 | value, 378 | )?; 379 | state.push(StateWord(var)); 380 | 381 | Ok(()) 382 | }; 383 | 384 | for i in 0..RATE { 385 | load_state_word(i, F::ZERO)?; 386 | } 387 | load_state_word(RATE, D::initial_capacity_element())?; 388 | 389 | Ok(state) 390 | }, 391 | )?; 392 | 393 | Ok(state.try_into().unwrap()) 394 | } 395 | 396 | fn add_input( 397 | &self, 398 | layouter: &mut impl Layouter, 399 | initial_state: &State, 400 | input: &Absorbing, RATE>, 401 | ) -> Result, Error> { 402 | let config = self.config(); 403 | layouter.assign_region( 404 | || format!("add input for domain {}", D::name()), 405 | |mut region| { 406 | config.s_pad_and_add.enable(&mut region, 1)?; 407 | 408 | // Load the initial state into this region. 409 | let load_state_word = |i: usize| { 410 | initial_state[i] 411 | .0 412 | .copy_advice( 413 | || format!("load state_{i}"), 414 | &mut region, 415 | config.state[i], 416 | 0, 417 | ) 418 | .map(StateWord) 419 | }; 420 | let initial_state: Result, Error> = 421 | (0..WIDTH).map(load_state_word).collect(); 422 | let initial_state = initial_state?; 423 | 424 | // Load the input into this region. 425 | let load_input_word = |i: usize| { 426 | let constraint_var = match input.0[i].clone() { 427 | Some(PaddedWord::Message(word)) => word, 428 | Some(PaddedWord::Padding(padding_value)) => region.assign_fixed( 429 | || format!("load pad_{i}"), 430 | config.rc_b[i], 431 | 1, 432 | || Value::known(padding_value), 433 | )?, 434 | _ => panic!("Input is not padded"), 435 | }; 436 | constraint_var 437 | .copy_advice( 438 | || format!("load input_{i}"), 439 | &mut region, 440 | config.state[i], 441 | 1, 442 | ) 443 | .map(StateWord) 444 | }; 445 | let input: Result, Error> = (0..RATE).map(load_input_word).collect(); 446 | let input = input?; 447 | 448 | // Constrain the output. 449 | let constrain_output_word = |i: usize| { 450 | region 451 | .assign_advice( 452 | || format!("load output_{i}"), 453 | config.state[i], 454 | 2, 455 | || { 456 | if let Some(inp) = input.get(i) { 457 | initial_state[i].value() + inp.value() 458 | } else { 459 | initial_state[i].value() 460 | } 461 | }, 462 | ) 463 | .map(StateWord) 464 | }; 465 | 466 | let output: Result, Error> = (0..WIDTH).map(constrain_output_word).collect(); 467 | output.map(|output| output.try_into().unwrap()) 468 | }, 469 | ) 470 | } 471 | 472 | fn get_output(state: &State) -> Squeezing { 473 | Squeezing( 474 | state[..RATE] 475 | .iter() 476 | .map(|word| Some(word.clone())) 477 | .collect::>() 478 | .try_into() 479 | .unwrap(), 480 | ) 481 | } 482 | } 483 | 484 | /// A word in the Poseidon state. 485 | #[derive(Clone, Debug)] 486 | pub struct StateWord(pub AssignedCell); 487 | 488 | impl From> for AssignedCell { 489 | fn from(state_word: StateWord) -> AssignedCell { 490 | state_word.0 491 | } 492 | } 493 | 494 | impl From> for StateWord { 495 | fn from(cell_value: AssignedCell) -> StateWord { 496 | StateWord(cell_value) 497 | } 498 | } 499 | 500 | impl Var for StateWord { 501 | fn cell(&self) -> Cell { 502 | self.0.cell() 503 | } 504 | 505 | fn value(&self) -> Value { 506 | self.0.value().cloned() 507 | } 508 | } 509 | 510 | #[derive(Debug)] 511 | struct Pow5State([StateWord; WIDTH]); 512 | 513 | impl Pow5State { 514 | fn full_round( 515 | self, 516 | region: &mut Region, 517 | config: &Pow5Config, 518 | round: usize, 519 | offset: usize, 520 | ) -> Result { 521 | Self::round(region, config, round, offset, config.s_full, |_| { 522 | let q = 523 | self.0.iter().enumerate().map(|(idx, word)| { 524 | word.value() + Value::known(config.round_constants[round][idx]) 525 | }); 526 | let r: Vec> = q.map(|q| q.map(|q| q.pow(&config.alpha))).collect(); 527 | let m = &config.m_reg; 528 | let state = m.iter().map(|m_i| { 529 | r.iter() 530 | .enumerate() 531 | .fold(Value::known(F::ZERO), |acc, (j, r_j)| { 532 | acc + Value::known(m_i[j]) * r_j 533 | }) 534 | }); 535 | 536 | Ok((round + 1, state.collect::>().try_into().unwrap())) 537 | }) 538 | } 539 | 540 | fn partial_round_single( 541 | self, 542 | region: &mut Region, 543 | config: &Pow5Config, 544 | round: usize, 545 | offset: usize, 546 | ) -> Result { 547 | Self::round( 548 | region, 549 | config, 550 | round, 551 | offset, 552 | config.s_partial_single, 553 | |_| { 554 | let r: Vec> = self 555 | .0 556 | .iter() 557 | .enumerate() 558 | .map(|(idx, word)| { 559 | word.value() 560 | .map(|v| v + config.round_constants[round][idx]) 561 | .map(|v| if idx == 0 { v.pow(&config.alpha) } else { v }) 562 | }) 563 | .collect(); 564 | 565 | let m = &config.m_reg; 566 | let state = m.iter().map(|m_i| { 567 | r.iter() 568 | .enumerate() 569 | .fold(Value::known(F::ZERO), |acc, (j, r_j)| { 570 | acc + Value::known(m_i[j]) * r_j 571 | }) 572 | }); 573 | 574 | Ok((round + 1, state.collect::>().try_into().unwrap())) 575 | }, 576 | ) 577 | } 578 | 579 | fn partial_round( 580 | self, 581 | region: &mut Region, 582 | config: &Pow5Config, 583 | round: usize, 584 | offset: usize, 585 | ) -> Result { 586 | Self::round(region, config, round, offset, config.s_partial, |region| { 587 | let m = &config.m_reg; 588 | let p: Vec<_> = self.0.iter().map(|word| word.value()).collect(); 589 | 590 | let r_0 = (p[0] + Value::known(config.round_constants[round][0])) 591 | .map(|v| v.pow(&config.alpha)); 592 | let r_i = p[1..] 593 | .iter() 594 | .enumerate() 595 | .map(|(i, p_i)| Value::known(config.round_constants[round][i + 1]) + p_i); 596 | let r: Vec<_> = Some(r_0).into_iter().chain(r_i).collect(); 597 | 598 | region.assign_advice( 599 | || format!("round_{round} partial_sbox"), 600 | config.partial_sbox, 601 | offset, 602 | || r[0], 603 | )?; 604 | 605 | let p_mid: Vec<_> = m 606 | .iter() 607 | .map(|m_i| { 608 | m_i.iter() 609 | .zip(r.iter()) 610 | .fold(Value::known(F::ZERO), |acc, (m_ij, r_j)| { 611 | acc + Value::known(*m_ij) * r_j 612 | }) 613 | }) 614 | .collect(); 615 | 616 | // Load the second round constants. 617 | let mut load_round_constant = |i: usize| { 618 | region.assign_fixed( 619 | || format!("round_{} rc_{}", round + 1, i), 620 | config.rc_b[i], 621 | offset, 622 | || Value::known(config.round_constants[round + 1][i]), 623 | ) 624 | }; 625 | for i in 0..WIDTH { 626 | load_round_constant(i)?; 627 | } 628 | 629 | let r_0 = (p_mid[0] + Value::known(config.round_constants[round + 1][0])) 630 | .map(|v| v.pow(&config.alpha)); 631 | let r_i = p_mid[1..] 632 | .iter() 633 | .enumerate() 634 | .map(|(i, p_i)| Value::known(config.round_constants[round + 1][i + 1]) + p_i); 635 | let r_mid: Vec<_> = Some(r_0).into_iter().chain(r_i).collect(); 636 | 637 | let state: Vec<_> = m 638 | .iter() 639 | .map(|m_i| { 640 | m_i.iter() 641 | .zip(r_mid.iter()) 642 | .fold(Value::known(F::ZERO), |acc, (m_ij, r_j)| { 643 | acc + Value::known(*m_ij) * r_j 644 | }) 645 | }) 646 | .collect(); 647 | 648 | Ok((round + 2, state.try_into().unwrap())) 649 | }) 650 | } 651 | 652 | fn load( 653 | region: &mut Region, 654 | config: &Pow5Config, 655 | initial_state: &State, WIDTH>, 656 | ) -> Result { 657 | let load_state_word = |i: usize| { 658 | initial_state[i] 659 | .0 660 | .copy_advice(|| format!("load state_{i}"), region, config.state[i], 0) 661 | .map(StateWord) 662 | }; 663 | 664 | let state: Result, _> = (0..WIDTH).map(load_state_word).collect(); 665 | state.map(|state| Pow5State(state.try_into().unwrap())) 666 | } 667 | 668 | fn round( 669 | region: &mut Region, 670 | config: &Pow5Config, 671 | round: usize, 672 | offset: usize, 673 | round_gate: Selector, 674 | round_fn: impl FnOnce(&mut Region) -> Result<(usize, [Value; WIDTH]), Error>, 675 | ) -> Result { 676 | // Enable the required gate. 677 | round_gate.enable(region, offset)?; 678 | 679 | // Load the round constants. 680 | let mut load_round_constant = |i: usize| { 681 | region.assign_fixed( 682 | || format!("round_{round} rc_{i}"), 683 | config.rc_a[i], 684 | offset, 685 | || Value::known(config.round_constants[round][i]), 686 | ) 687 | }; 688 | for i in 0..WIDTH { 689 | load_round_constant(i)?; 690 | } 691 | 692 | // Compute the next round's state. 693 | let (next_round, next_state) = round_fn(region)?; 694 | 695 | let next_state_word = |i: usize| { 696 | let value = next_state[i]; 697 | let var = region.assign_advice( 698 | || format!("round_{next_round} state_{i}"), 699 | config.state[i], 700 | offset + 1, 701 | || value, 702 | )?; 703 | Ok(StateWord(var)) 704 | }; 705 | 706 | let next_state: Result, _> = (0..WIDTH).map(next_state_word).collect(); 707 | next_state.map(|next_state| Pow5State(next_state.try_into().unwrap())) 708 | } 709 | } 710 | 711 | #[cfg(test)] 712 | mod tests { 713 | use halo2_proofs::halo2curves::group::ff::{Field, PrimeField}; 714 | use halo2_proofs::{ 715 | circuit::{Layouter, SimpleFloorPlanner, Value}, 716 | dev::MockProver, 717 | plonk::{Circuit, ConstraintSystem, Error}, 718 | }; 719 | use poseidon_base::primitives::{ 720 | self as poseidon, 721 | pasta::{test_vectors, Fp}, 722 | ConstantLength, P128Pow5T3, Spec, 723 | }; 724 | use rand::rngs::OsRng; 725 | 726 | use super::{PoseidonInstructions, Pow5Chip, Pow5Config, StateWord}; 727 | use crate::poseidon::Hash; 728 | use std::convert::TryInto; 729 | use std::marker::PhantomData; 730 | 731 | type OrchardNullifier = P128Pow5T3; 732 | 733 | struct PermuteCircuit, const WIDTH: usize, const RATE: usize>( 734 | PhantomData, 735 | ); 736 | 737 | impl, const WIDTH: usize, const RATE: usize> Circuit 738 | for PermuteCircuit 739 | { 740 | type Config = Pow5Config; 741 | type FloorPlanner = SimpleFloorPlanner; 742 | 743 | fn without_witnesses(&self) -> Self { 744 | PermuteCircuit::(PhantomData) 745 | } 746 | 747 | fn configure(meta: &mut ConstraintSystem) -> Pow5Config { 748 | let state = (0..WIDTH).map(|_| meta.advice_column()).collect::>(); 749 | let partial_sbox = meta.advice_column(); 750 | 751 | let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::>(); 752 | let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::>(); 753 | 754 | Pow5Chip::configure::( 755 | meta, 756 | state.try_into().unwrap(), 757 | partial_sbox, 758 | rc_a.try_into().unwrap(), 759 | rc_b.try_into().unwrap(), 760 | ) 761 | } 762 | 763 | fn synthesize( 764 | &self, 765 | config: Pow5Config, 766 | mut layouter: impl Layouter, 767 | ) -> Result<(), Error> { 768 | let initial_state = layouter.assign_region( 769 | || "prepare initial state", 770 | |mut region| { 771 | let state_word = |i: usize| { 772 | let var = region.assign_advice( 773 | || format!("load state_{}", i), 774 | config.state[i], 775 | 0, 776 | || Value::known(Fp::from(i as u64)), 777 | )?; 778 | Ok(StateWord(var)) 779 | }; 780 | 781 | let state: Result, Error> = (0..WIDTH).map(state_word).collect(); 782 | Ok(state?.try_into().unwrap()) 783 | }, 784 | )?; 785 | 786 | let chip = Pow5Chip::construct(config.clone()); 787 | let final_state = as PoseidonInstructions< 788 | Fp, 789 | S, 790 | WIDTH, 791 | RATE, 792 | >>::permute(&chip, &mut layouter, &initial_state)?; 793 | 794 | // For the purpose of this test, compute the real final state inline. 795 | let mut expected_final_state = (0..WIDTH) 796 | .map(|idx| Fp::from(idx as u64)) 797 | .collect::>() 798 | .try_into() 799 | .unwrap(); 800 | let (round_constants, mds, _) = S::constants(); 801 | poseidon::permute::<_, S, WIDTH, RATE>( 802 | &mut expected_final_state, 803 | &mds, 804 | &round_constants, 805 | ); 806 | 807 | layouter.assign_region( 808 | || "constrain final state", 809 | |mut region| { 810 | let mut final_state_word = |i: usize| { 811 | let var = region.assign_advice( 812 | || format!("load final_state_{}", i), 813 | config.state[i], 814 | 0, 815 | || Value::known(expected_final_state[i]), 816 | )?; 817 | region.constrain_equal(final_state[i].0.cell(), var.cell()) 818 | }; 819 | 820 | for i in 0..(WIDTH) { 821 | final_state_word(i)?; 822 | } 823 | 824 | Ok(()) 825 | }, 826 | ) 827 | } 828 | } 829 | 830 | #[test] 831 | fn poseidon_permute() { 832 | let k = 6; 833 | let circuit = PermuteCircuit::(PhantomData); 834 | let prover = MockProver::run(k, &circuit, vec![]).unwrap(); 835 | assert_eq!(prover.verify(), Ok(())) 836 | } 837 | 838 | struct HashCircuit< 839 | S: Spec, 840 | const WIDTH: usize, 841 | const RATE: usize, 842 | const L: usize, 843 | > { 844 | message: Option<[Fp; L]>, 845 | // For the purpose of this test, witness the result. 846 | // TODO: Move this into an instance column. 847 | output: Option, 848 | _spec: PhantomData, 849 | } 850 | 851 | impl, const WIDTH: usize, const RATE: usize, const L: usize> 852 | Circuit for HashCircuit 853 | { 854 | type Config = Pow5Config; 855 | type FloorPlanner = SimpleFloorPlanner; 856 | 857 | fn without_witnesses(&self) -> Self { 858 | Self { 859 | message: None, 860 | output: None, 861 | _spec: PhantomData, 862 | } 863 | } 864 | 865 | fn configure(meta: &mut ConstraintSystem) -> Pow5Config { 866 | let state = (0..WIDTH).map(|_| meta.advice_column()).collect::>(); 867 | let partial_sbox = meta.advice_column(); 868 | 869 | let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::>(); 870 | let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::>(); 871 | 872 | meta.enable_constant(rc_b[0]); 873 | 874 | Pow5Chip::configure::( 875 | meta, 876 | state.try_into().unwrap(), 877 | partial_sbox, 878 | rc_a.try_into().unwrap(), 879 | rc_b.try_into().unwrap(), 880 | ) 881 | } 882 | 883 | fn synthesize( 884 | &self, 885 | config: Pow5Config, 886 | mut layouter: impl Layouter, 887 | ) -> Result<(), Error> { 888 | let chip = Pow5Chip::construct(config.clone()); 889 | 890 | let message = layouter.assign_region( 891 | || "load message", 892 | |mut region| { 893 | let message_word = |i: usize| { 894 | let value = self.message.map(|message_vals| message_vals[i]); 895 | region.assign_advice( 896 | || format!("load message_{}", i), 897 | config.state[i], 898 | 0, 899 | || { 900 | if let Some(v) = value { 901 | Value::known(v) 902 | } else { 903 | Value::unknown() 904 | } 905 | }, 906 | ) 907 | }; 908 | 909 | let message: Result, Error> = (0..L).map(message_word).collect(); 910 | Ok(message?.try_into().unwrap()) 911 | }, 912 | )?; 913 | 914 | let hasher = Hash::<_, _, S, ConstantLength, WIDTH, RATE>::init( 915 | chip, 916 | layouter.namespace(|| "init"), 917 | )?; 918 | let output = hasher.hash(layouter.namespace(|| "hash"), message)?; 919 | 920 | layouter.assign_region( 921 | || "constrain output", 922 | |mut region| { 923 | let expected_var = region.assign_advice( 924 | || "load output", 925 | config.state[0], 926 | 0, 927 | || { 928 | if let Some(v) = self.output { 929 | Value::known(v) 930 | } else { 931 | Value::unknown() 932 | } 933 | }, 934 | )?; 935 | region.constrain_equal(output.cell(), expected_var.cell()) 936 | }, 937 | ) 938 | } 939 | } 940 | 941 | #[test] 942 | fn poseidon_hash() { 943 | let rng = OsRng; 944 | 945 | let message = [Fp::random(rng), Fp::random(rng)]; 946 | let output = 947 | poseidon::Hash::<_, OrchardNullifier, ConstantLength<2>, 3, 2>::init().hash(message); 948 | 949 | let k = 6; 950 | let circuit = HashCircuit:: { 951 | message: Some(message), 952 | output: Some(output), 953 | _spec: PhantomData, 954 | }; 955 | let prover = MockProver::run(k, &circuit, vec![]).unwrap(); 956 | assert_eq!(prover.verify(), Ok(())) 957 | } 958 | 959 | #[test] 960 | fn poseidon_hash_longer_input() { 961 | let rng = OsRng; 962 | 963 | let message = [Fp::random(rng), Fp::random(rng), Fp::random(rng)]; 964 | let output = 965 | poseidon::Hash::<_, OrchardNullifier, ConstantLength<3>, 3, 2>::init().hash(message); 966 | 967 | let k = 7; 968 | let circuit = HashCircuit:: { 969 | message: Some(message), 970 | output: Some(output), 971 | _spec: PhantomData, 972 | }; 973 | let prover = MockProver::run(k, &circuit, vec![]).unwrap(); 974 | assert_eq!(prover.verify(), Ok(())) 975 | } 976 | 977 | #[test] 978 | fn hash_test_vectors() { 979 | for tv in test_vectors::fp::hash() { 980 | let message = [ 981 | Fp::from_repr(tv.input[0]).unwrap(), 982 | Fp::from_repr(tv.input[1]).unwrap(), 983 | ]; 984 | let output = poseidon::Hash::<_, OrchardNullifier, ConstantLength<2>, 3, 2>::init() 985 | .hash(message); 986 | 987 | let k = 6; 988 | let circuit = HashCircuit:: { 989 | message: Some(message), 990 | output: Some(output), 991 | _spec: PhantomData, 992 | }; 993 | let prover = MockProver::run(k, &circuit, vec![]).unwrap(); 994 | assert_eq!(prover.verify(), Ok(())); 995 | } 996 | } 997 | 998 | #[cfg(feature = "print_layout")] 999 | #[test] 1000 | fn print_poseidon_chip() { 1001 | use plotters::prelude::*; 1002 | 1003 | let root = 1004 | BitMapBackend::new("layouts/poseidon-chip-layout.png", (1024, 768)).into_drawing_area(); 1005 | root.fill(&WHITE).unwrap(); 1006 | let root = root 1007 | .titled("Poseidon Chip Layout", ("sans-serif", 60)) 1008 | .unwrap(); 1009 | 1010 | let circuit = HashCircuit:: { 1011 | message: None, 1012 | output: None, 1013 | _spec: PhantomData, 1014 | }; 1015 | halo2_proofs::dev::CircuitLayout::default() 1016 | .render(6, &circuit, &root) 1017 | .unwrap(); 1018 | } 1019 | } 1020 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon.rs: -------------------------------------------------------------------------------- 1 | //! An implementation using septuple rounds. 2 | //! See: src/README.md 3 | 4 | mod control; 5 | mod full_round; 6 | mod instruction; 7 | mod loop_chip; 8 | mod params; 9 | mod septidon_chip; 10 | mod septuple_round; 11 | mod state; 12 | #[cfg(test)] 13 | mod tests; 14 | mod transition_round; 15 | mod util; 16 | 17 | pub use septidon_chip::SeptidonChip; 18 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/control.rs: -------------------------------------------------------------------------------- 1 | use super::params::GATE_DEGREE_5; 2 | use super::util::query; 3 | 4 | use ff::PrimeField; 5 | use halo2_proofs::circuit::{Region, Value}; 6 | use halo2_proofs::plonk::{Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}; 7 | use halo2_proofs::poly::Rotation; 8 | 9 | #[derive(Clone, Debug)] 10 | pub struct ControlChip { 11 | is_last: Column, 12 | } 13 | 14 | pub struct ControlSignals { 15 | // Signals that control the switches between steps of the permutation. 16 | pub break_full_rounds: Expression, 17 | pub transition_round: Expression, 18 | pub break_partial_rounds: Expression, 19 | 20 | // A selector that can disable all chips on all rows. 21 | pub selector: Expression, 22 | } 23 | 24 | impl ControlChip { 25 | pub fn configure(cs: &mut ConstraintSystem) -> (Self, ControlSignals) { 26 | let is_last = cs.fixed_column(); 27 | 28 | let signals = query(cs, |meta| { 29 | let signal_middle = meta.query_fixed(is_last, Rotation(4)); // Seen from the middle row. 30 | let signal_last = meta.query_fixed(is_last, Rotation::cur()); 31 | let middle_or_last = signal_middle.clone() + signal_last.clone(); // Assume no overlap. 32 | 33 | ControlSignals { 34 | break_full_rounds: middle_or_last, 35 | transition_round: signal_middle, 36 | break_partial_rounds: signal_last, 37 | selector: Self::derive_selector(is_last, meta), 38 | } 39 | }); 40 | 41 | let chip = Self { is_last }; 42 | (chip, signals) 43 | } 44 | 45 | /// Assign the fixed positions of the last row of permutations for a new region. 46 | pub fn assign(&self, region: &mut Region<'_, F>) -> Result<(), Error> { 47 | self.assign_with_offset(region, 0) 48 | } 49 | 50 | /// Assign the fixed positions of the last row of permutations. 51 | pub fn assign_with_offset( 52 | &self, 53 | region: &mut Region<'_, F>, 54 | begin_offset: usize, 55 | ) -> Result<(), Error> { 56 | region.assign_fixed( 57 | || "", 58 | self.is_last, 59 | 7 + begin_offset, 60 | || Value::known(F::ONE), 61 | )?; 62 | Ok(()) 63 | } 64 | 65 | fn derive_selector( 66 | is_last: Column, 67 | meta: &mut VirtualCells<'_, F>, 68 | ) -> Expression { 69 | if GATE_DEGREE_5 { 70 | // Variant with no selector. Do not disable gates, do not increase the gate degree. 71 | Expression::Constant(F::ONE) 72 | } else { 73 | // Variant with a selector enabled on all rows of valid permutations. 74 | // Detect is_last=1, seen from its own row or up to 7 rows below. 75 | (0..8_i32) 76 | .map(|i| meta.query_fixed(is_last, Rotation(i))) 77 | .reduce(|acc, x| acc + x) 78 | .unwrap() // Boolean any. 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/full_round.rs: -------------------------------------------------------------------------------- 1 | use super::loop_chip::LoopBody; 2 | use super::params::{mds, CachedConstants}; 3 | use super::state::{Cell, FullState, SBox}; 4 | use super::util::{join_values, matmul, query, split_values}; 5 | use halo2_proofs::circuit::{Region, Value}; 6 | //use halo2_proofs::halo2curves::bn256::Fr as F; 7 | use halo2_proofs::plonk::{ConstraintSystem, Error, Expression, VirtualCells}; 8 | 9 | #[derive(Clone, Debug)] 10 | pub struct FullRoundChip(pub FullState); 11 | 12 | impl FullRoundChip { 13 | pub fn configure(cs: &mut ConstraintSystem) -> (Self, LoopBody) { 14 | let chip = Self(FullState::configure(cs)); 15 | 16 | let loop_body = query(cs, |meta| { 17 | let next_state = chip.0.map(|sbox| sbox.input.query(meta, 1)); 18 | let output = chip.full_round_expr(meta); 19 | LoopBody { next_state, output } 20 | }); 21 | 22 | (chip, loop_body) 23 | } 24 | 25 | fn full_round_expr( 26 | &self, 27 | meta: &mut VirtualCells<'_, F>, 28 | ) -> [Expression; 3] { 29 | let sbox_out = self.0.map(|sbox: &SBox| sbox.output_expr(meta)); 30 | matmul::expr(mds(), sbox_out) 31 | } 32 | 33 | pub fn input_cells(&self) -> [Cell; 3] { 34 | self.0.map(|sbox| sbox.input.clone()) 35 | } 36 | 37 | /// Assign the witness. 38 | pub fn assign( 39 | &self, 40 | region: &mut Region<'_, F>, 41 | offset: usize, 42 | round_constants: [F; 3], 43 | input: [Value; 3], 44 | ) -> Result<[Value; 3], Error> { 45 | let mut sbox_out = [Value::unknown(); 3]; 46 | for i in 0..3 { 47 | let sbox: &SBox = &self.0 .0[i]; 48 | sbox_out[i] = sbox.assign(region, offset, round_constants[i], input[i])?; 49 | } 50 | let output = join_values(sbox_out).map(|sbox_out| matmul::value(mds(), sbox_out)); 51 | Ok(split_values(output)) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/instruction.rs: -------------------------------------------------------------------------------- 1 | use super::super::{PermuteChip, PoseidonInstructions, StateWord, Var}; 2 | use super::{util::map_array, SeptidonChip}; 3 | use ff::PrimeField; 4 | use halo2_proofs::circuit::{Region, Value}; 5 | use halo2_proofs::{ 6 | circuit::{Chip, Layouter}, 7 | plonk::{ConstraintSystem, Error}, 8 | }; 9 | use poseidon_base::{ 10 | params::CachedConstants, 11 | primitives::{Spec, State}, 12 | }; 13 | 14 | const WIDTH: usize = 3; 15 | const RATE: usize = 2; 16 | 17 | impl> PermuteChip for SeptidonChip { 18 | fn configure(meta: &mut ConstraintSystem) -> Self::Config { 19 | let chip = Self::configure(meta); 20 | 21 | // Enable equality on the input/output columns, required by the function permute. 22 | for cell in chip.initial_state_cells() { 23 | meta.enable_equality(cell.column); 24 | } 25 | for cell in chip.final_state_cells() { 26 | meta.enable_equality(cell.column); 27 | } 28 | 29 | chip 30 | } 31 | 32 | fn construct(config: Self::Config) -> Self { 33 | config 34 | } 35 | } 36 | 37 | impl> PoseidonInstructions 38 | for SeptidonChip 39 | { 40 | type Word = StateWord; 41 | 42 | fn permute( 43 | &self, 44 | layouter: &mut impl Layouter, 45 | initial_state: &State, 46 | ) -> Result, Error> { 47 | layouter.assign_region( 48 | || "permute state", 49 | |mut region| { 50 | let region = &mut region; 51 | 52 | // Copy the given initial_state into the permutation chip. 53 | let chip_input = self.initial_state_cells(); 54 | for i in 0..WIDTH { 55 | initial_state[i].0.copy_advice( 56 | || format!("load state_{i}"), 57 | region, 58 | chip_input[i].column, 59 | chip_input[i].offset as usize, 60 | )?; 61 | } 62 | 63 | // Assign the internal witness of the permutation. 64 | let initial_values = map_array(initial_state, |word| word.value()); 65 | let final_values = self.assign_permutation(region, initial_values)?; 66 | 67 | // Return the cells containing the final state. 68 | let chip_output = self.final_state_cells(); 69 | let final_state: Vec> = (0..WIDTH) 70 | .map(|i| { 71 | region 72 | .assign_advice( 73 | || format!("output {i}"), 74 | chip_output[i].column, 75 | chip_output[i].offset as usize, 76 | || final_values[i], 77 | ) 78 | .map(StateWord) 79 | }) 80 | .collect::, _>>()?; 81 | 82 | Ok(final_state.try_into().unwrap()) 83 | }, 84 | ) 85 | } 86 | 87 | fn permute_batch( 88 | &self, 89 | layouter: &mut impl Layouter, 90 | initial_states: &[State], 91 | ) -> Result>, Error> { 92 | let chunks_count = std::thread::available_parallelism() 93 | .map(|e| e.get()) 94 | .unwrap_or(32); 95 | let chunks_len = initial_states.len() / chunks_count + 2; 96 | 97 | let assignments = initial_states 98 | .chunks(chunks_len) 99 | .map(|initial_states| { 100 | let mut is_first_pass = true; 101 | move |mut region: Region<'_, F>| -> Result>, Error> { 102 | let region = &mut region; 103 | let mut final_states = vec![]; 104 | let mut last_offset = 0; 105 | 106 | if is_first_pass { 107 | is_first_pass = false; 108 | let col = self.final_state_cells().first().unwrap().column; 109 | region.assign_advice( 110 | || "First pass dummy assign", 111 | col, 112 | initial_states.len() * 8 - 1, 113 | || Value::known(F::ZERO), 114 | )?; 115 | return Ok(final_states); 116 | } 117 | 118 | for initial_state in initial_states.iter() { 119 | // Copy the given initial_state into the permutation chip. 120 | let chip_input = self.initial_state_cells(); 121 | for i in 0..WIDTH { 122 | initial_state[i].0.copy_advice( 123 | || format!("load state_{i}"), 124 | region, 125 | chip_input[i].column, 126 | last_offset + chip_input[i].offset as usize, 127 | )?; 128 | } 129 | 130 | // Assign the internal witness of the permutation. 131 | let initial_values = map_array(initial_state, |word| word.value()); 132 | let final_values = self.assign_permutation_with_offset( 133 | region, 134 | initial_values, 135 | last_offset, 136 | )?; 137 | 138 | // Return the cells containing the final state. 139 | let chip_output = self.final_state_cells(); 140 | let final_state: Vec> = (0..WIDTH) 141 | .map(|i| { 142 | region 143 | .assign_advice( 144 | || format!("output {i}"), 145 | chip_output[i].column, 146 | last_offset + chip_output[i].offset as usize, 147 | || final_values[i], 148 | ) 149 | .map(StateWord) 150 | }) 151 | .collect::, _>>()?; 152 | 153 | last_offset += 8; 154 | final_states.push(final_state.try_into().unwrap()); 155 | } 156 | Ok(final_states) 157 | } 158 | }) 159 | .collect::>(); 160 | layouter 161 | .assign_regions(|| "permute state", assignments) 162 | .map(|e| e.into_iter().flatten().collect::>()) 163 | } 164 | } 165 | 166 | impl Chip for SeptidonChip { 167 | type Config = Self; 168 | 169 | type Loaded = (); 170 | 171 | fn config(&self) -> &Self::Config { 172 | self 173 | } 174 | 175 | fn loaded(&self) -> &Self::Loaded { 176 | &() 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/loop_chip.rs: -------------------------------------------------------------------------------- 1 | use super::state::Cell; 2 | use super::util::select; 3 | 4 | use ff::PrimeField; 5 | use halo2_proofs::plonk::{ConstraintSystem, Constraints, Expression}; 6 | 7 | #[derive(Clone, Debug)] 8 | pub struct LoopChip {} 9 | 10 | pub struct LoopBody { 11 | pub next_state: [Expression; 3], 12 | /// Cells where the output is, relative to the break signal. 13 | pub output: [Expression; 3], 14 | } 15 | 16 | impl LoopChip { 17 | pub fn configure( 18 | cs: &mut ConstraintSystem, 19 | q: Expression, 20 | body: LoopBody, 21 | break_signal: Expression, 22 | output: [Cell; 3], 23 | ) -> Self { 24 | cs.create_gate("loop", |meta| { 25 | let constraints = (0..3) 26 | .map(|i| { 27 | let destination = select::expr( 28 | break_signal.clone(), 29 | output[i].query(meta, 0), 30 | body.next_state[i].clone(), 31 | ); 32 | 33 | destination - body.output[i].clone() 34 | }) 35 | .collect::>(); 36 | 37 | Constraints::with_selector(q, constraints) 38 | }); 39 | 40 | Self {} 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/params.rs: -------------------------------------------------------------------------------- 1 | /// This implementation can be limited to gate degree 5. However, this mode will not work with 2 | /// blinding or inactive rows. Enable only with a prover that supports assignments to all n rows. 3 | pub const GATE_DEGREE_5: bool = false; 4 | 5 | pub mod sbox { 6 | use super::super::util::pow_5; 7 | 8 | use ff::PrimeField; 9 | use halo2_proofs::plonk::Expression; 10 | 11 | pub fn expr( 12 | input: Expression, 13 | round_constant: Expression, 14 | ) -> Expression { 15 | pow_5::expr(input + round_constant) 16 | } 17 | 18 | pub fn value(input: F, round_constant: F) -> F { 19 | pow_5::value(input + round_constant) 20 | } 21 | } 22 | 23 | pub use poseidon_base::params::*; 24 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/septidon_chip.rs: -------------------------------------------------------------------------------- 1 | use halo2_proofs::circuit::{Region, Value}; 2 | //use halo2_proofs::halo2curves::bn256::Fr as F; 3 | use halo2_proofs::plonk::{ConstraintSystem, Error}; 4 | use poseidon_base::params::{round_constant, CachedConstants}; 5 | 6 | use super::control::ControlChip; 7 | use super::full_round::FullRoundChip; 8 | use super::loop_chip::LoopChip; 9 | use super::septuple_round::SeptupleRoundChip; 10 | use super::state::Cell; 11 | use super::transition_round::TransitionRoundChip; 12 | use super::util::map_array; 13 | 14 | /// The configuration of the permutation chip. 15 | /// 16 | /// ``` 17 | /// use halo2_proofs::halo2curves::bn256::Fr as F; 18 | /// use halo2_proofs::plonk::ConstraintSystem; 19 | /// use poseidon_circuit::poseidon::SeptidonChip; 20 | /// 21 | /// let mut cs = ConstraintSystem::::default(); 22 | /// let config = SeptidonChip::configure(&mut cs); 23 | /// ``` 24 | #[derive(Clone, Debug)] 25 | pub struct SeptidonChip { 26 | control_chip: ControlChip, 27 | 28 | transition_chip: TransitionRoundChip, 29 | 30 | full_round_chip: FullRoundChip, 31 | 32 | partial_round_chip: SeptupleRoundChip, 33 | } 34 | 35 | impl SeptidonChip { 36 | /// Create a new chip. 37 | pub fn configure(cs: &mut ConstraintSystem) -> Self { 38 | let (control_chip, signals) = ControlChip::configure(cs); 39 | let q = || signals.selector.clone(); 40 | 41 | let (full_round_chip, full_round_loop_body) = FullRoundChip::configure(cs); 42 | 43 | let (partial_round_chip, partial_round_loop_body) = SeptupleRoundChip::configure(cs, q()); 44 | 45 | let transition_chip = { 46 | // The output of the transition round is the input of the partial rounds loop. 47 | let output = partial_round_chip.input(); 48 | TransitionRoundChip::configure(cs, signals.transition_round, output) 49 | }; 50 | 51 | { 52 | // The output of full rounds go into the transition round. 53 | let output = transition_chip.input(); 54 | 55 | LoopChip::configure( 56 | cs, 57 | q(), 58 | full_round_loop_body, 59 | signals.break_full_rounds, 60 | output, 61 | ) 62 | }; 63 | 64 | { 65 | // The output of partial rounds go horizontally into the second loop of full rounds, 66 | // which runs parallel to the last 4 partials rounds (indexed [-3; 0]). 67 | let full_round_sboxes = &full_round_chip.0 .0; 68 | let output: [Cell; 3] = [ 69 | full_round_sboxes[0].input.rotated(-3), 70 | full_round_sboxes[1].input.rotated(-3), 71 | full_round_sboxes[2].input.rotated(-3), 72 | ]; 73 | 74 | LoopChip::configure( 75 | cs, 76 | q(), 77 | partial_round_loop_body, 78 | signals.break_partial_rounds, 79 | output, 80 | ) 81 | }; 82 | 83 | Self { 84 | control_chip, 85 | transition_chip, 86 | full_round_chip, 87 | partial_round_chip, 88 | } 89 | } 90 | 91 | /// How many rows are used per permutation. 92 | pub fn height_per_permutation() -> usize { 93 | 8 94 | } 95 | 96 | fn final_offset() -> usize { 97 | Self::height_per_permutation() - 1 98 | } 99 | 100 | /// Return the cells containing the initial state. The parent chip must constrain these cells. 101 | /// Cells are relative to the row 0 of a region of a permutation. 102 | pub fn initial_state_cells(&self) -> [Cell; 3] { 103 | self.full_round_chip.input_cells() 104 | } 105 | 106 | /// Return the cells containing the final state. The parent chip must constrain these cells. 107 | /// Cells are relative to the row 0 of a region of a permutation. 108 | pub fn final_state_cells(&self) -> [Cell; 3] { 109 | let relative_cells = self.transition_chip.input(); 110 | map_array(&relative_cells, |cell| { 111 | cell.rotated(Self::final_offset() as i32) 112 | }) 113 | } 114 | 115 | /// Assign the witness of a permutation into the new region. 116 | pub fn assign_permutation( 117 | &self, 118 | region: &mut Region<'_, F>, 119 | initial_state: [Value; 3], 120 | ) -> Result<[Value; 3], Error> { 121 | self.assign_permutation_with_offset(region, initial_state, 0) 122 | } 123 | 124 | /// Assign the witness of a permutation into the existent region. 125 | pub fn assign_permutation_with_offset( 126 | &self, 127 | region: &mut Region<'_, F>, 128 | initial_state: [Value; 3], 129 | begin_offset: usize, 130 | ) -> Result<[Value; 3], Error> { 131 | self.control_chip.assign_with_offset(region, begin_offset)?; 132 | 133 | let mut state = initial_state; 134 | 135 | // First half of full rounds. 136 | for offset in 0..4 { 137 | state = self.full_round_chip.assign( 138 | region, 139 | offset + begin_offset, 140 | round_constant(offset), 141 | state, 142 | )?; 143 | } 144 | 145 | // First partial round. 146 | // Its round constant is part of the gate (not a fixed column). 147 | let middle_offset = 3; 148 | state = self.transition_chip.assign_first_partial_state( 149 | region, 150 | middle_offset + begin_offset, 151 | state, 152 | )?; 153 | 154 | // The rest of partial rounds. 155 | for offset in 0..8 { 156 | let round_index = 5 + offset * 7; 157 | let round_constants = (round_index..round_index + 7) 158 | .map(|idx| round_constant(idx)[0]) 159 | .collect::>(); 160 | state = self.partial_round_chip.assign( 161 | region, 162 | offset + begin_offset, 163 | &round_constants, 164 | state, 165 | )?; 166 | } 167 | 168 | // The second half of full rounds. 169 | for offset in 4..8 { 170 | state = self.full_round_chip.assign( 171 | region, 172 | offset + begin_offset, 173 | round_constant(offset + 57), 174 | state, 175 | )?; 176 | } 177 | 178 | // Put the final state into its place. 179 | let final_offset = 7; 180 | self.transition_chip 181 | .assign_final_state(region, final_offset + begin_offset, state)?; 182 | 183 | Ok(state) 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/septuple_round.rs: -------------------------------------------------------------------------------- 1 | use super::loop_chip::LoopBody; 2 | use super::params::{mds, CachedConstants}; 3 | use super::state::{Cell, SBox}; 4 | use super::util::{join_values, matmul, query, split_values}; 5 | use halo2_proofs::circuit::{Region, Value}; 6 | //use halo2_proofs::halo2curves::bn256::Fr as F; 7 | use halo2_proofs::plonk::{ConstraintSystem, Constraints, Error, Expression, VirtualCells}; 8 | 9 | #[derive(Clone, Debug)] 10 | pub struct SeptupleRoundChip { 11 | first_sbox: SBox, 12 | first_linears: [Cell; 2], 13 | following_sboxes: [SBox; 6], 14 | } 15 | 16 | impl SeptupleRoundChip { 17 | pub fn configure( 18 | cs: &mut ConstraintSystem, 19 | q: Expression, 20 | ) -> (Self, LoopBody) { 21 | let chip = Self { 22 | first_sbox: SBox::configure(cs), 23 | first_linears: [Cell::configure(cs), Cell::configure(cs)], 24 | following_sboxes: (0..6) 25 | .map(|_| SBox::configure(cs)) 26 | .collect::>() 27 | .try_into() 28 | .unwrap(), 29 | }; 30 | 31 | let input = chip.input(); 32 | let (input_state, next_state) = query(cs, |meta| { 33 | ( 34 | [ 35 | input[0].query(meta, 0), // Not read directly but via first_sbox.output_expr. 36 | input[1].query(meta, 0), 37 | input[2].query(meta, 0), 38 | ], 39 | [ 40 | input[0].query(meta, 1), 41 | input[1].query(meta, 1), 42 | input[2].query(meta, 1), 43 | ], 44 | ) 45 | }); 46 | 47 | let output = { 48 | // The input state is constrained by another chip (TransitionRoundChip). 49 | let mut checked_sbox = &chip.first_sbox; 50 | let mut state = input_state; 51 | 52 | cs.create_gate("septuple_round", |meta| { 53 | let mut constraints = vec![]; 54 | 55 | for sbox_to_check in &chip.following_sboxes { 56 | // Calculate the expression of the next state. 57 | state = Self::partial_round_expr(meta, checked_sbox, &state); 58 | 59 | // Compare the high-degree expression of the state with the equivalent witness. 60 | let witness = sbox_to_check.input_expr(meta); 61 | constraints.push(state[0].clone() - witness.clone()); 62 | // We validated the S-Box input, so we can use next_sbox.output_expr. 63 | checked_sbox = sbox_to_check; 64 | } 65 | 66 | // Output the last round as an expression. 67 | state = Self::partial_round_expr(meta, checked_sbox, &state); 68 | 69 | Constraints::with_selector(q, constraints) 70 | }); 71 | state 72 | }; 73 | 74 | let loop_body = LoopBody { next_state, output }; 75 | 76 | (chip, loop_body) 77 | } 78 | 79 | fn partial_round_expr( 80 | meta: &mut VirtualCells<'_, F>, 81 | sbox: &SBox, 82 | input: &[Expression; 3], 83 | ) -> [Expression; 3] { 84 | let sbox_out = [sbox.output_expr(meta), input[1].clone(), input[2].clone()]; 85 | matmul::expr(mds(), sbox_out) 86 | } 87 | 88 | pub fn input(&self) -> [Cell; 3] { 89 | [ 90 | self.first_sbox.input.clone(), 91 | self.first_linears[0].clone(), 92 | self.first_linears[1].clone(), 93 | ] 94 | } 95 | 96 | /// Assign the witness. 97 | pub fn assign( 98 | &self, 99 | region: &mut Region<'_, F>, 100 | offset: usize, 101 | round_constants: &[F], 102 | input: [Value; 3], 103 | ) -> Result<[Value; 3], Error> { 104 | // Assign the first non-S-Box cells. 105 | for i in 0..2 { 106 | self.first_linears[i].assign(region, offset, input[1 + i])?; 107 | } 108 | 109 | let mut state = input; 110 | let mut assign_partial_round = |i: usize, sbox: &SBox| -> Result<(), Error> { 111 | // Assign the following S-Boxes. 112 | state[0] = sbox.assign(region, offset, round_constants[i], state[0])?; 113 | // Apply the matrix. 114 | state = split_values(join_values(state).map(|s| matmul::value(mds(), s))); 115 | Ok(()) 116 | }; 117 | 118 | assign_partial_round(0, &self.first_sbox)?; 119 | 120 | for (i, sbox) in self.following_sboxes.iter().enumerate() { 121 | assign_partial_round(1 + i, sbox)?; 122 | } 123 | 124 | Ok(state) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/state.rs: -------------------------------------------------------------------------------- 1 | use super::params; 2 | use ff::PrimeField; 3 | use halo2_proofs::circuit::{Region, Value}; 4 | use halo2_proofs::plonk::{ 5 | Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells, 6 | }; 7 | use halo2_proofs::poly::Rotation; 8 | 9 | /// Cell remembers the relative position of a cell in the region of a permutation. 10 | /// It can be used in configuration and synthesis. 11 | #[derive(Clone, Debug)] 12 | pub struct Cell { 13 | pub column: Column, 14 | /// An offset relative to the owner of this Cell. 15 | pub offset: i32, 16 | } 17 | 18 | impl Cell { 19 | pub fn configure(cs: &mut ConstraintSystem) -> Self { 20 | Cell { 21 | column: cs.advice_column(), 22 | offset: 0, 23 | } 24 | } 25 | 26 | pub fn new(column: Column, offset: i32) -> Self { 27 | Self { column, offset } 28 | } 29 | 30 | pub fn rotated(&self, offset: i32) -> Self { 31 | Self { 32 | column: self.column, 33 | offset: self.offset + offset, 34 | } 35 | } 36 | 37 | pub fn query(&self, meta: &mut VirtualCells, offset: i32) -> Expression { 38 | meta.query_advice(self.column, Rotation(self.offset + offset)) 39 | } 40 | 41 | pub fn region_offset(&self) -> usize { 42 | assert!(self.offset >= 0); 43 | self.offset as usize 44 | } 45 | 46 | pub fn assign( 47 | &self, 48 | region: &mut Region<'_, F>, 49 | origin_offset: usize, 50 | input: Value, 51 | ) -> Result<(), Error> { 52 | let offset = origin_offset as i32 + self.offset; 53 | assert!(offset >= 0, "cannot assign to a cell outside of its region"); 54 | region.assign_advice(|| "cell", self.column, offset as usize, || input)?; 55 | Ok(()) 56 | } 57 | } 58 | 59 | #[derive(Clone, Debug)] 60 | pub struct SBox { 61 | pub input: Cell, 62 | round_constant: Column, 63 | } 64 | 65 | impl SBox { 66 | pub fn configure(cs: &mut ConstraintSystem) -> Self { 67 | SBox { 68 | input: Cell::configure(cs), 69 | round_constant: cs.fixed_column(), 70 | } 71 | } 72 | 73 | /// Assign the witness of the input. 74 | pub fn assign( 75 | &self, 76 | region: &mut Region<'_, F>, 77 | offset: usize, 78 | round_constant: F, 79 | input: Value, 80 | ) -> Result, Error> { 81 | region.assign_fixed( 82 | || "round_constant", 83 | self.round_constant, 84 | offset + self.input.region_offset(), 85 | || Value::known(round_constant), 86 | )?; 87 | region.assign_advice( 88 | || "initial_state", 89 | self.input.column, 90 | offset + self.input.region_offset(), 91 | || input, 92 | )?; 93 | let output = input.map(|i| params::sbox::value(i, round_constant)); 94 | Ok(output) 95 | } 96 | 97 | pub fn input_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { 98 | self.input.query(meta, 0) 99 | } 100 | 101 | pub fn rc_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { 102 | meta.query_fixed(self.round_constant, Rotation(self.input.offset)) 103 | } 104 | 105 | pub fn output_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { 106 | let input = self.input_expr(meta); 107 | let round_constant = self.rc_expr(meta); 108 | params::sbox::expr(input, round_constant) 109 | } 110 | } 111 | 112 | #[derive(Clone, Debug)] 113 | pub struct FullState(pub [SBox; 3]); 114 | 115 | impl FullState { 116 | pub fn configure(cs: &mut ConstraintSystem) -> Self { 117 | Self([ 118 | SBox::configure(cs), 119 | SBox::configure(cs), 120 | SBox::configure(cs), 121 | ]) 122 | } 123 | 124 | pub fn map(&self, mut f: F) -> [T; 3] 125 | where 126 | F: FnMut(&SBox) -> T, 127 | { 128 | let a = f(&self.0[0]); 129 | let b = f(&self.0[1]); 130 | let c = f(&self.0[2]); 131 | [a, b, c] 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/tests.rs: -------------------------------------------------------------------------------- 1 | use halo2_proofs::circuit::{Layouter, Region, SimpleFloorPlanner, Value}; 2 | use halo2_proofs::dev::MockProver; 3 | use halo2_proofs::halo2curves::bn256::Fr as F; 4 | use halo2_proofs::plonk::{Circuit, ConstraintSystem, Error}; 5 | 6 | use super::{util::join_values, SeptidonChip}; 7 | 8 | #[test] 9 | fn septidon_permutation() { 10 | let k = 5; 11 | let inactive_rows = 6; // Assume default in this test. 12 | 13 | let circuit = TestCircuit { 14 | height: (1 << k) - inactive_rows, 15 | }; 16 | let prover = MockProver::run(k as u32, &circuit, vec![]).unwrap(); 17 | prover.verify_at_rows(0..1, 0..0).unwrap(); 18 | } 19 | 20 | #[derive(Clone)] 21 | struct TestCircuit { 22 | height: usize, 23 | } 24 | 25 | impl Circuit for TestCircuit { 26 | type Config = SeptidonChip; 27 | type FloorPlanner = SimpleFloorPlanner; 28 | 29 | fn without_witnesses(&self) -> Self { 30 | self.clone() 31 | } 32 | 33 | fn configure(cs: &mut ConstraintSystem) -> Self::Config { 34 | SeptidonChip::configure(cs) 35 | } 36 | 37 | fn synthesize( 38 | &self, 39 | config: SeptidonChip, 40 | mut layouter: impl Layouter, 41 | ) -> Result<(), Error> { 42 | use halo2_proofs::dev::unwrap_value; 43 | 44 | let num_permutations = self.height / 8; 45 | 46 | for _ in 0..num_permutations { 47 | let initial_state = [ 48 | Value::known(F::from(0)), 49 | Value::known(F::from(1)), 50 | Value::known(F::from(2)), 51 | ]; 52 | 53 | let final_state = layouter.assign_region( 54 | || "SeptidonChip", 55 | |mut region: Region<'_, F>| config.assign_permutation(&mut region, initial_state), 56 | )?; 57 | 58 | let got = format!("{:?}", unwrap_value(join_values(final_state))); 59 | 60 | // For input 0,1,2. 61 | let expect = "[0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a, 0x0fca49b798923ab0239de1c9e7a4a9a2210312b6a2f616d18b5a87f9b628ae29, 0x0e7ae82e40091e63cbd4f16a6d16310b3729d4b6e138fcf54110e2867045a30c]"; 62 | assert_eq!(got, expect); 63 | } 64 | 65 | Ok(()) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/transition_round.rs: -------------------------------------------------------------------------------- 1 | use super::params; 2 | use super::params::{mds, round_constant, CachedConstants}; 3 | use super::state::Cell; 4 | use super::util::{join_values, matmul, split_values}; 5 | use halo2_proofs::circuit::{Region, Value}; 6 | use halo2_proofs::plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Expression}; 7 | 8 | #[derive(Clone, Debug)] 9 | pub struct TransitionRoundChip { 10 | column: Column, 11 | } 12 | 13 | impl TransitionRoundChip { 14 | pub fn configure( 15 | cs: &mut ConstraintSystem, 16 | signal: Expression, 17 | next_state: [Cell; 3], 18 | ) -> Self { 19 | let chip = Self { 20 | column: cs.advice_column(), 21 | }; 22 | 23 | cs.create_gate("transition round", |meta| { 24 | // The input cells are relative to the signal. 25 | let input = chip.input(); 26 | let input = [ 27 | input[0].query(meta, 0), 28 | input[1].query(meta, 0), 29 | input[2].query(meta, 0), 30 | ]; 31 | 32 | let output = Self::first_partial_round_expr(&input); 33 | 34 | // Get the next_state from the point of view of the signal. 35 | let next_state = [ 36 | next_state[0].query(meta, -3), 37 | next_state[1].query(meta, -3), 38 | next_state[2].query(meta, -3), 39 | ]; 40 | 41 | let constraints = vec![ 42 | output[0].clone() - next_state[0].clone(), 43 | output[1].clone() - next_state[1].clone(), 44 | output[2].clone() - next_state[2].clone(), 45 | ]; 46 | 47 | Constraints::with_selector(signal, constraints) 48 | }); 49 | 50 | chip 51 | } 52 | 53 | // Return an expression of the state after the first partial round given the state before. 54 | // TODO: implement with with degree <= 5 using the helper cell. 55 | fn first_partial_round_expr( 56 | input: &[Expression; 3], 57 | ) -> [Expression; 3] { 58 | let rc = Expression::Constant(Self::round_constant()); 59 | let sbox_out = [ 60 | params::sbox::expr(input[0].clone(), rc), 61 | input[1].clone(), 62 | input[2].clone(), 63 | ]; 64 | matmul::expr(mds(), sbox_out) 65 | } 66 | 67 | fn round_constant() -> F { 68 | round_constant(4)[0] 69 | } 70 | 71 | /// Return the input cells of this round, relative to the signal. 72 | // TODO: rename because it is also used as final state. 73 | pub fn input(&self) -> [Cell; 3] { 74 | // The input to the transition round is vertical in the transition column. 75 | [ 76 | Cell::new(self.column, -2), 77 | Cell::new(self.column, -1), 78 | Cell::new(self.column, 0), 79 | ] 80 | } 81 | 82 | pub fn helper_cell(&self) -> Cell { 83 | Cell::new(self.column, -3) 84 | } 85 | 86 | /// Assign the state of the first partial round, and return the round output. 87 | pub fn assign_first_partial_state( 88 | &self, 89 | region: &mut Region<'_, F>, 90 | middle_break_offset: usize, 91 | input: [Value; 3], 92 | ) -> Result<[Value; 3], Error> { 93 | let output = Self::first_partial_round(&input); 94 | for (value, cell) in input.into_iter().zip(self.input()) { 95 | cell.assign(region, middle_break_offset, value)?; 96 | } 97 | self.helper_cell() 98 | .assign(region, middle_break_offset, Value::known(F::ZERO))?; 99 | Ok(output) 100 | } 101 | 102 | fn first_partial_round(input: &[Value; 3]) -> [Value; 3] { 103 | let sbox_out = [ 104 | input[0].map(|f| params::sbox::value(f, Self::round_constant())), 105 | input[1], 106 | input[2], 107 | ]; 108 | let output = join_values(sbox_out).map(|s| matmul::value(mds(), s)); 109 | split_values(output) 110 | } 111 | 112 | /// Assign the final state. This has the same layout as the first partial state, at another offset. 113 | pub fn assign_final_state( 114 | &self, 115 | region: &mut Region<'_, F>, 116 | final_break_offset: usize, 117 | input: [Value; 3], 118 | ) -> Result<(), Error> { 119 | for (value, cell) in input.into_iter().zip(self.input()) { 120 | cell.assign(region, final_break_offset, value)?; 121 | } 122 | self.helper_cell() 123 | .assign(region, final_break_offset, Value::known(F::ZERO))?; 124 | Ok(()) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /poseidon-circuit/src/poseidon/septidon/util.rs: -------------------------------------------------------------------------------- 1 | use ff::PrimeField; 2 | use halo2_proofs::circuit::Value; 3 | use halo2_proofs::plonk::{ConstraintSystem, Expression, VirtualCells}; 4 | 5 | pub fn map_array(array: &[IN; 3], mut f: FN) -> [OUT; 3] 6 | where 7 | FN: FnMut(&IN) -> OUT, 8 | { 9 | let a = f(&array[0]); 10 | let b = f(&array[1]); 11 | let c = f(&array[2]); 12 | [a, b, c] 13 | } 14 | 15 | /// Helper to make queries to a ConstraintSystem. Escape the "create_gate" closures. 16 | pub fn query( 17 | cs: &mut ConstraintSystem, 18 | f: impl FnOnce(&mut VirtualCells<'_, F>) -> T, 19 | ) -> T { 20 | let mut queries: Option = None; 21 | cs.create_gate("query", |meta| { 22 | queries = Some(f(meta)); 23 | [Expression::Constant(F::ZERO)] 24 | }); 25 | queries.unwrap() 26 | } 27 | 28 | pub fn join_values(values: [Value; 3]) -> Value<[F; 3]> { 29 | values[0] 30 | .zip(values[1]) 31 | .zip(values[2]) 32 | .map(|((v0, v1), v2)| [v0, v1, v2]) 33 | } 34 | 35 | pub fn split_values(values: Value<[F; 3]>) -> [Value; 3] { 36 | [ 37 | values.map(|v| v[0]), 38 | values.map(|v| v[1]), 39 | values.map(|v| v[2]), 40 | ] 41 | } 42 | 43 | pub mod pow_5 { 44 | use super::PrimeField; 45 | use halo2_proofs::plonk::Expression; 46 | 47 | pub fn expr(v: Expression) -> Expression { 48 | let v2 = v.clone() * v.clone(); 49 | v2.clone() * v2 * v 50 | } 51 | 52 | pub fn value(v: F) -> F { 53 | let v2 = v * v; 54 | v2 * v2 * v 55 | } 56 | } 57 | 58 | /// Matrix multiplication expressions and values. 59 | pub mod matmul { 60 | use super::super::params::Mds; 61 | use super::PrimeField; 62 | use halo2_proofs::plonk::Expression; 63 | use std::convert::TryInto; 64 | 65 | /// Multiply a vector of expressions by a constant matrix. 66 | pub fn expr(matrix: &Mds, vector: [Expression; 3]) -> [Expression; 3] { 67 | (0..3) 68 | .map(|next_idx| { 69 | (0..3) 70 | .map(|idx| vector[idx].clone() * matrix[next_idx][idx]) 71 | .reduce(|acc, term| acc + term) 72 | .unwrap() 73 | }) 74 | .collect::>() 75 | .try_into() 76 | .unwrap() 77 | } 78 | 79 | /// Multiply a vector of values by a constant matrix. 80 | pub fn value(matrix: &Mds, vector: [F; 3]) -> [F; 3] { 81 | (0..3) 82 | .map(|next_idx| { 83 | (0..3) 84 | .map(|idx| vector[idx] * matrix[next_idx][idx]) 85 | .reduce(|acc, term| acc + term) 86 | .unwrap() 87 | }) 88 | .collect::>() 89 | .try_into() 90 | .unwrap() 91 | } 92 | } 93 | 94 | /// Returns `when_true` when `selector == 1`, and returns `when_false` when 95 | /// `selector == 0`. `selector` needs to be boolean. 96 | pub mod select { 97 | use ff::PrimeField; 98 | use halo2_proofs::plonk::Expression; 99 | 100 | /// Returns the `when_true` expression when the selector is true, else 101 | /// returns the `when_false` expression. 102 | pub fn expr( 103 | selector: Expression, 104 | when_true: Expression, 105 | when_false: Expression, 106 | ) -> Expression { 107 | let one = Expression::Constant(F::from(1)); 108 | selector.clone() * when_true + (one - selector) * when_false 109 | } 110 | 111 | /// Returns the `when_true` value when the selector is true, else returns 112 | /// the `when_false` value. 113 | pub fn value(selector: F, when_true: F, when_false: F) -> F { 114 | selector * when_true + (F::ONE - selector) * when_false 115 | } 116 | } 117 | 118 | /// Gadget for boolean OR. 119 | pub mod or { 120 | use ff::PrimeField; 121 | use halo2_proofs::plonk::Expression; 122 | 123 | /// Return (a OR b), assuming a and b are boolean expressions. 124 | pub fn expr(a: Expression, b: Expression) -> Expression { 125 | let one = Expression::Constant(F::from(1)); 126 | // a OR b <=> !(!a AND !b) 127 | one.clone() - ((one.clone() - a) * (one - b)) 128 | } 129 | 130 | /// Return (a OR b), assuming a and b are boolean values. 131 | pub fn value(a: F, b: F) -> F { 132 | let one = F::ONE; 133 | // a OR b <=> !(!a AND !b) 134 | one - ((one - a) * (one - b)) 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /poseidon-circuit/tests/hash_proving.rs: -------------------------------------------------------------------------------- 1 | use halo2_proofs::dev::MockProver; 2 | use halo2_proofs::halo2curves::{ 3 | bn256::{Bn256, Fr as Fp, G1Affine}, 4 | group::ff::PrimeField, 5 | }; 6 | use halo2_proofs::plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}; 7 | use halo2_proofs::poly::commitment::ParamsProver; 8 | use halo2_proofs::poly::kzg::commitment::{ 9 | KZGCommitmentScheme, ParamsKZG as Params, ParamsVerifierKZG as ParamsVerifier, 10 | }; 11 | use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; 12 | use halo2_proofs::poly::kzg::strategy::SingleStrategy; 13 | use halo2_proofs::transcript::{ 14 | Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, 15 | }; 16 | use halo2_proofs::{ 17 | circuit::{Layouter, SimpleFloorPlanner}, 18 | plonk::{Circuit, ConstraintSystem, Error}, 19 | }; 20 | use poseidon_circuit::poseidon::Pow5Chip; 21 | use poseidon_circuit::{hash::*, DEFAULT_STEP}; 22 | use rand::SeedableRng; 23 | use rand_chacha::ChaCha8Rng; 24 | 25 | struct TestCircuit(PoseidonHashTable, usize); 26 | 27 | // test circuit derived from table data 28 | impl Circuit for TestCircuit { 29 | type Config = SpongeConfig>; 30 | type FloorPlanner = SimpleFloorPlanner; 31 | 32 | fn without_witnesses(&self) -> Self { 33 | Self(PoseidonHashTable::default(), self.1) 34 | } 35 | 36 | fn configure(meta: &mut ConstraintSystem) -> Self::Config { 37 | let hash_tbl = [0; 6].map(|_| meta.advice_column()); 38 | let q_enable = meta.fixed_column(); 39 | SpongeConfig::configure_sub(meta, (q_enable, hash_tbl), DEFAULT_STEP) 40 | } 41 | 42 | fn synthesize( 43 | &self, 44 | config: Self::Config, 45 | mut layouter: impl Layouter, 46 | ) -> Result<(), Error> { 47 | let chip = 48 | SpongeChip::>::construct(config, &self.0, self.1); 49 | chip.load(&mut layouter) 50 | } 51 | } 52 | 53 | #[test] 54 | fn hash_circuit() { 55 | let message1 = [ 56 | Fp::from_str_vartime("1").unwrap(), 57 | Fp::from_str_vartime("2").unwrap(), 58 | ]; 59 | let message2 = [ 60 | Fp::from_str_vartime("0").unwrap(), 61 | Fp::from_str_vartime("1").unwrap(), 62 | ]; 63 | 64 | let k = 7; 65 | let circuit = TestCircuit( 66 | PoseidonHashTable { 67 | inputs: vec![message1, message2], 68 | ..Default::default() 69 | }, 70 | 3, 71 | ); 72 | let prover = MockProver::run(k, &circuit, vec![]).unwrap(); 73 | assert_eq!(prover.verify(), Ok(())); 74 | } 75 | 76 | #[test] 77 | fn vk_validity() { 78 | use halo2_proofs::SerdeFormat; 79 | 80 | let params = Params::::unsafe_setup(8); 81 | 82 | let circuit = TestCircuit(PoseidonHashTable::default(), 3); 83 | let vk1 = keygen_vk(¶ms, &circuit).unwrap(); 84 | 85 | let mut vk1_buf: Vec = Vec::new(); 86 | vk1.write(&mut vk1_buf, SerdeFormat::RawBytesUnchecked) 87 | .unwrap(); 88 | 89 | let circuit = TestCircuit( 90 | PoseidonHashTable { 91 | inputs: vec![ 92 | [ 93 | Fp::from_str_vartime("1").unwrap(), 94 | Fp::from_str_vartime("2").unwrap(), 95 | ], 96 | [ 97 | Fp::from_str_vartime("0").unwrap(), 98 | Fp::from_str_vartime("1").unwrap(), 99 | ], 100 | ], 101 | ..Default::default() 102 | }, 103 | 3, 104 | ); 105 | let vk2 = keygen_vk(¶ms, &circuit).unwrap(); 106 | 107 | let mut vk2_buf: Vec = Vec::new(); 108 | vk2.write(&mut vk2_buf, SerdeFormat::RawBytesUnchecked) 109 | .unwrap(); 110 | 111 | assert_eq!(vk1_buf, vk2_buf); 112 | } 113 | 114 | #[test] 115 | fn proof_and_verify() { 116 | let k = 8; 117 | 118 | let params = Params::::unsafe_setup(k); 119 | let os_rng = ChaCha8Rng::from_seed([101u8; 32]); 120 | let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); 121 | 122 | let circuit = TestCircuit( 123 | PoseidonHashTable { 124 | inputs: vec![ 125 | [ 126 | Fp::from_str_vartime("1").unwrap(), 127 | Fp::from_str_vartime("2").unwrap(), 128 | ], 129 | [ 130 | Fp::from_str_vartime("30").unwrap(), 131 | Fp::from_str_vartime("1").unwrap(), 132 | ], 133 | [Fp::from_str_vartime("65536").unwrap(), Fp::zero()], 134 | ], 135 | controls: vec![0, 46, 14], 136 | ..Default::default() 137 | }, 138 | 4, 139 | ); 140 | 141 | let prover = MockProver::run(k, &circuit, vec![]).unwrap(); 142 | assert_eq!(prover.verify(), Ok(())); 143 | 144 | let vk = keygen_vk(¶ms, &circuit).unwrap(); 145 | let pk = keygen_pk(¶ms, vk, &circuit).unwrap(); 146 | 147 | create_proof::, ProverSHPLONK<'_, Bn256>, _, _, _, _>( 148 | ¶ms, 149 | &pk, 150 | &[circuit], 151 | &[&[]], 152 | os_rng, 153 | &mut transcript, 154 | ) 155 | .unwrap(); 156 | 157 | let proof_script = transcript.finalize(); 158 | let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof_script[..]); 159 | let verifier_params: ParamsVerifier = params.verifier_params().clone(); 160 | let strategy = SingleStrategy::new(¶ms); 161 | let circuit = TestCircuit(PoseidonHashTable::default(), 4); 162 | let vk = keygen_vk(¶ms, &circuit).unwrap(); 163 | 164 | assert!( 165 | verify_proof::, VerifierSHPLONK<'_, Bn256>, _, _, _>( 166 | &verifier_params, 167 | &vk, 168 | strategy, 169 | &[&[]], 170 | &mut transcript 171 | ) 172 | .is_ok() 173 | ); 174 | } 175 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2024-07-07 -------------------------------------------------------------------------------- /spec/Septidon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scroll-tech/poseidon-circuit/b978cee00aae1e0a1e79e0d74c4683b137f5ea2d/spec/Septidon.png -------------------------------------------------------------------------------- /spec/hash-table.md: -------------------------------------------------------------------------------- 1 | 2 | ## Hash Function 3 | 4 | - Poseidon ([paper](https://eprint.iacr.org/2019/458.pdf)). 5 | - Collision and second preimage resistance target: 128 bits. 6 | - On the BN254 scalar field. 7 | - S-box: x^5. 8 | - Full rounds: 8. 9 | - Partial rounds (S-box on the first "capacity" state): 57. 10 | - Constants: `poseidonperm_x5_254_3`, as generated by the [reference Sage implementation](https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/b5434fd2b2785926dd1dd386efbef167da57c064/code/poseidonperm_x5_254_3.sage) or the equivalent [Rust implementation](https://github.com/scroll-tech/poseidon-circuit/blob/e3841d0828e577b80c9cd84aa71f79adc96756fc/src/poseidon/primitives.rs#L61). 11 | - Capacity: 1 element. 12 | - Rate: 2 elements. 13 | 14 | 15 | ## Interface Table 16 | 17 | The hash circuit exposes a table containing multiple inputs/output pairs. This table can be looked up by the MPT and codehash circuits. The table has four columns: 2 inputs, 1 digest output, 2 for control flags and additional marking. 18 | 19 | | 0: Hash index | 1: Message | 2: Message | 3: Control flag | 4: Head flag | 20 | | --------------- | ---------------- | --------------- | --------------- | ------------ | 21 | | MPT digest | MPT input 1 | MPT input 2 | 0 | 1 | 22 | | | | | | | 23 | | var-len digest | word 0 | word 1 | 2000*(2^64) | 1 | 24 | | var-len digest | word 2 | word 3 | 1968*(2^64) | 0 | 25 | | ... | ... | ... | ... | 0 | 26 | | var-len digest | word W-2 | word W-1 | 16*(2^64) | 0 | 27 | | | | | | | 28 | 29 | 30 | The hash circuit supports two modes: 31 | 32 | ### MPT Mode 33 | 34 | Compute the digest of two message words, as in Merkle trees. This type of entries is identified by the control flag value of 0. 35 | 36 | **Initial capacity:** `0`. 37 | 38 | **Message encoding:** each message word is a field element; that is, each word is a digest from the previous MPT layer. 39 | 40 | ### Var-Len Mode 41 | 42 | Compute the digest of a variable-length message. One such entry is composed of consecutive rows with the same digest value, and where the control flag is not 0. 43 | 44 | **Initial capacity:** `L * 2^64`, with `L` the message length in bytes (before padding). 45 | 46 | **Message encoding:** The message is chunked into `W` words of `STEP/2` bytes. Each word is packed into a field element, least-significant-byte first. The words are given two-by-two on consecutive rows in the table, absorbing `STEP` bytes per row. The control flag on a given row indicates the number of message bytes `R` remaining in the current and following rows (and the value is `R * 2^64`). On the last row, `control <= STEP * 2^64`. 47 | 48 | **Padding:** the message is padded to a multiple of `STEP` bytes with zeros. 49 | 50 | Specifically, `STEP = 32`. 51 | 52 | ### Legacy scheme 53 | 54 | The initial capcity before `scroll-dev-0215` is not multiplied with the domain mark (`2^64`) so they would get different hash results in *var-len* mode. If we wish 55 | to apply the code work under the legacy schema, use `legacy` feature 56 | 57 | ### Head flag 58 | 59 | The head flag is set at each beginning of message, i.e each row under MPT mode and the first row of message in Var-Len mode would be set to 1 60 | 61 | ### Custom row 62 | 63 | 2 Additional row is put at the beginning of hash table: 64 | 65 | 1. A row being filled with 0 for any lookup which is not enabled 66 | 2. A row with `control` and `Message` field being set to 0 and the hash is set to a customed value for representing 67 | the hash of empty message. Currently it is set to equal to `keccak256(nil)` and the indexed hash value must be properly set under challenge API 68 | 69 | ## Internal Table (hash_table_aux) 70 | 71 | | Row | 0: State (capacity) | 1: State (rate) | 2: State (rate) | 3: State-for-next | 4: State-for-next | 5: Hash Out | 72 | | -------- | ------------------- | --------------- | --------------- | ----------------- | ----------------- | ----------- | 73 | | previous | | | | | | | 74 | | current | | | | | | | 75 | 76 | -------------------------------------------------------------------------------- /spec/septidon.md: -------------------------------------------------------------------------------- 1 | # A Poseidon Chip with Septuple Rounds 2 | 3 | This is a circuit for a Poseidon permutation. It uses 8 rows per permutation. It exposes pairs of input/output at fixed 4 | locations, to use with a sponge circuit. It is designed as a set of chips, that can be rearranged to obtain 4, 2, or 5 | even 1 rows per permutation. It can potentially be configured with a max gate degree of 5 for faster proving. 6 | 7 | 8 | **[Design Diagrams](https://miro.com/app/board/uXjVPLsk0oU=/?moveToWidget=3458764546593848776&cot=14)** 9 | 10 | ![diagram](./Septidon.png) 11 | 12 | 13 | # Spec 14 | 15 | ## S-box 16 | 17 | - Config: 18 | - 1 advice column A. 19 | - 1 fixed column C. 20 | - get_input() -> Expr: 21 | Return an expression of degree 1 of the input A. 22 | - get_output() -> Expr: 23 | Return an expression of degree 5 of the output B. 24 | B = (A + C)**5 25 | 26 | ### Partial State = SBox 27 | ### Full State = [SBox; 3] 28 | 29 | ## Full Round 30 | 31 | - Config: 3 S-boxes 32 | - get_input() -> [Expr; 3]: 33 | Return an expression of degree 1 of the full state before the round. 34 | - get_output() -> [Expr; 3]: 35 | Return an expression of degree 5 of the full state after the round. 36 | MDS . [outputs of the S-boxes] 37 | 38 | ## Loop 39 | 40 | Iterate rounds on consecutive rows, with the ability to break the loop. 41 | 42 | - Config: 43 | - A Round config (Full or Partial) where the iteration takes place. 44 | - A Full State where to hold the result after break. [Expr; 3] 45 | - A selector expression indicating when to break. Expr 46 | - get_constraint() -> Expr 47 | An expression that must equal zero. 48 | 49 | The degrees of the result and selector expressions must add up to at most 5. 50 | The loop must break at the end of the circuit. 51 | 52 | 53 | ## Full Rounds Layout 54 | 55 | A layout of 4 Full Rounds and the output of the 4th round. The output is stored vertically in a given column, parallel to the round executions. For the first 4 full rounds, the output is the input of the first partial round. For the last 4 full rounds, the output is the final state. 56 | 57 | Layout: 58 | 59 | Selector | Rounds | Output 60 | ---------|-----------|---------- 61 | 0 | [State 0] | (untouched) 62 | 0 | [State 1] | output.0 63 | 0 | [State 2] | output.1 64 | 1 | [State 3] | output.2 65 | 66 | - Config: 67 | - A selector expression indicating when to output and restart. Expr. 68 | - A Full Round Loop config for initial and intermediate states. 69 | - A column where to hold the output state. 70 | 71 | 72 | ## First Partial Round 73 | 74 | An implementation of the first partial round, with support for a selector. 75 | 76 | - Config: 77 | - A selector indicating where this specific round is enabled. 78 | - 3 cells holding a full state as input. 79 | - The S-Box type is not appropriate here because this works differently. 80 | - 1 cell to hold an intermediate result a_square. 81 | - A Full State where to hold the output. 82 | 83 | a = state.0 + round_constants[4] 84 | a_square = a * a 85 | b = a_square * a_square * a 86 | [output] = MDS . [b, state.1, state.2] 87 | 88 | 89 | ## Transition Layout 90 | 91 | A layout of the first partial round inside of a column. 92 | 93 | Selector | Input | Output 94 | ---------|--------------|--------- 95 | 0 | a_square | [output] 96 | 0 | state.0 | (untouched) 97 | 0 | state.1 | (untouched) 98 | 1 | state.2 | (untouched) 99 | 100 | 101 | ## Septuple Round 102 | 103 | A batch of seven partial rounds, without selectors. 104 | 105 | - Config: 1 Full State, 6 Partial States. 106 | - get_input() -> [Expr; 3]: 107 | Return an expression of degree 1 of the full state before the rounds. 108 | - get_output() -> [Expr; 3]: 109 | Return an expression of degree 5 of the full state after the rounds. 110 | 111 | 112 | ## Septuple Rounds Layout 113 | 114 | A layout of 8 chained Septuple Rounds. Similar to Full Rounds Loop/Layout. 115 | The output is the input of the next Full Rounds Layout. 116 | 117 | 118 | ## Control Chip 119 | 120 | The control chip generates signals for the selectors and switches of other chips. 121 | 122 | - Config: 1 fixed column 123 | - full_rounds_break() -> the signal to interrupt the loops of full rounds. 124 | - partial_rounds_break() -> the signal to interrupt the loops of partial rounds. 125 | - transition_round() -> the signal to run the first partial round. 126 | 127 | 128 | ## Permutation Chip 129 | 130 | A permutation of an initial state into a final state. 131 | 132 | - Config: 133 | - 2 Full States 134 | - 6 Partial States 135 | - 1 Column for the transition to partial rounds, and the final state. 136 | - get_input() -> [Expr; 3]: 137 | Return an expression of degree 1 of the initial full state. 138 | - get_output() -> [Expr; 3]: 139 | Return an expression of degree 1 of the final full state. 140 | 141 | 142 | ## Alternative: 14x-Round 143 | 144 | A batch of 14 partial rounds, without selectors. 145 | 146 | - Config: 1 Full State, 13 Partial States 147 | 148 | ## Alternative: 14x-Rounds Layout 149 | 150 | A layout of 4 chained 14-Rounds. Similar to Full Rounds Loop/Layout. 151 | -------------------------------------------------------------------------------- /spec/types.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scroll-tech/poseidon-circuit/b978cee00aae1e0a1e79e0d74c4683b137f5ea2d/spec/types.pdf --------------------------------------------------------------------------------