-
Notifications
You must be signed in to change notification settings - Fork 31
runtime hash selection with SHA256, Blake3, Keccak support #251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yash25198
wants to merge
19
commits into
main
Choose a base branch
from
ysh/generic-hash-config
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
3bb6761
adds hash configs
yash25198 36ecd63
feat: runtime hash selection with optimizations
yash25198 53bbd93
feat: optimized hash impls
yash25198 56283ce
adds hash bench mark
yash25198 274e1ac
chore: cleanup unused code and fix type annotations
yash25198 026f23e
fix for cargo doc
yash25198 1353c88
fix for cargo fmt
yash25198 dabb29b
adds buffer module
yash25198 1e30a59
adds hash config offset and updates version
yash25198 2c894d9
add macros support for prove and verify functions
yash25198 b067f6d
adds trait aliases to simplify generic bounds
yash25198 2a3ce6f
switches to generic impl
yash25198 1245be6
adds macros for e2e tests
yash25198 2103c10
cargo fmt
yash25198 febd3a0
Merge main into ysh/generic-hash-config
yash25198 4c93f0b
use WHIR built-in hash engines
yash25198 47d623a
removes hash bench
yash25198 5ef4a53
clean up
yash25198 4c7446c
clean up
yash25198 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| //! BLAKE3 hash implementations for Merkle tree construction. | ||
|
|
||
| use { | ||
| crate::FieldElement, | ||
| ark_crypto_primitives::{ | ||
| crh::{CRHScheme, TwoToOneCRHScheme}, | ||
| Error, | ||
| }, | ||
| ark_serialize::CanonicalSerialize, | ||
| rand08::Rng, | ||
| serde::{Deserialize, Serialize}, | ||
| std::{borrow::Borrow, io::Write}, | ||
| whir::crypto::merkle_tree::digest::GenericDigest, | ||
| }; | ||
|
|
||
| pub type Blake3Digest = GenericDigest<32>; | ||
|
|
||
| /// 8-byte length prefix + up to 16 field elements (16 * 32 = 512 bytes). | ||
| const LEAF_BUFFER_SIZE: usize = 528; | ||
|
|
||
| struct StackBuffer { | ||
yash25198 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| buf: [u8; LEAF_BUFFER_SIZE], | ||
| pos: usize, | ||
| } | ||
|
|
||
| impl StackBuffer { | ||
| fn new() -> Self { | ||
| Self { | ||
| buf: [0u8; LEAF_BUFFER_SIZE], | ||
| pos: 0, | ||
| } | ||
| } | ||
|
|
||
| fn as_slice(&self) -> &[u8] { | ||
| &self.buf[..self.pos] | ||
| } | ||
| } | ||
|
|
||
| impl Write for StackBuffer { | ||
| fn write(&mut self, data: &[u8]) -> std::io::Result<usize> { | ||
| let available = LEAF_BUFFER_SIZE - self.pos; | ||
| if data.len() > available { | ||
| return Err(std::io::Error::new( | ||
| std::io::ErrorKind::WriteZero, | ||
| "buffer overflow", | ||
| )); | ||
| } | ||
| self.buf[self.pos..self.pos + data.len()].copy_from_slice(data); | ||
| self.pos += data.len(); | ||
| Ok(data.len()) | ||
| } | ||
|
|
||
| fn flush(&mut self) -> std::io::Result<()> { | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] | ||
| pub struct Blake3LeafHash; | ||
|
|
||
| impl CRHScheme for Blake3LeafHash { | ||
| type Input = [FieldElement]; | ||
| type Output = Blake3Digest; | ||
| type Parameters = (); | ||
|
|
||
| fn setup<R: Rng>(_: &mut R) -> Result<Self::Parameters, Error> { | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn evaluate<T: Borrow<Self::Input>>( | ||
| _: &Self::Parameters, | ||
| input: T, | ||
| ) -> Result<Self::Output, Error> { | ||
| let input = input.borrow(); | ||
| let required_size = 8 + input.len() * 32; | ||
|
|
||
| if required_size <= LEAF_BUFFER_SIZE { | ||
| let mut buf = StackBuffer::new(); | ||
| input.serialize_compressed(&mut buf)?; | ||
| let output: [u8; 32] = blake3::hash(buf.as_slice()).into(); | ||
| Ok(output.into()) | ||
| } else { | ||
| let mut buf = Vec::with_capacity(required_size); | ||
| input.serialize_compressed(&mut buf)?; | ||
| let output: [u8; 32] = blake3::hash(&buf).into(); | ||
| Ok(output.into()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] | ||
| pub struct Blake3Compress; | ||
|
|
||
| impl TwoToOneCRHScheme for Blake3Compress { | ||
| type Input = Blake3Digest; | ||
| type Output = Blake3Digest; | ||
| type Parameters = (); | ||
|
|
||
| fn setup<R: Rng>(_: &mut R) -> Result<Self::Parameters, Error> { | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn evaluate<T: Borrow<Self::Input>>( | ||
| _: &Self::Parameters, | ||
| left_input: T, | ||
| right_input: T, | ||
| ) -> Result<Self::Output, Error> { | ||
| let mut buf = [0u8; 64]; | ||
| buf[..32].copy_from_slice(&left_input.borrow().0); | ||
| buf[32..].copy_from_slice(&right_input.borrow().0); | ||
| let output: [u8; 32] = blake3::hash(&buf).into(); | ||
| Ok(output.into()) | ||
| } | ||
|
|
||
| fn compress<T: Borrow<Self::Output>>( | ||
| parameters: &Self::Parameters, | ||
| left_input: T, | ||
| right_input: T, | ||
| ) -> Result<Self::Output, Error> { | ||
| Self::evaluate(parameters, left_input, right_input) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use { | ||
| super::*, | ||
| ark_crypto_primitives::crh::{CRHScheme, TwoToOneCRHScheme}, | ||
| ark_ff::One, | ||
| whir::crypto::merkle_tree::blake3::{ | ||
| Blake3Compress as WhirCompress, Blake3LeafHash as WhirLeafHash, | ||
| }, | ||
| }; | ||
|
|
||
| #[test] | ||
| fn leaf_hash_matches_whir() { | ||
| let input = vec![ | ||
| FieldElement::one(), | ||
| FieldElement::from(42u64), | ||
| FieldElement::from(123456u64), | ||
| FieldElement::from(999999u64), | ||
| ]; | ||
| let whir = WhirLeafHash::<FieldElement>::evaluate(&(), input.as_slice()).unwrap(); | ||
| let ours = Blake3LeafHash::evaluate(&(), input.as_slice()).unwrap(); | ||
| assert_eq!(whir, ours); | ||
| } | ||
|
|
||
| #[test] | ||
| fn compress_matches_whir() { | ||
| let left: Blake3Digest = [1u8; 32].into(); | ||
| let right: Blake3Digest = [2u8; 32].into(); | ||
| let whir = WhirCompress::evaluate(&(), &left, &right).unwrap(); | ||
| let ours = Blake3Compress::evaluate(&(), &left, &right).unwrap(); | ||
| assert_eq!(whir, ours); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| //! BLAKE3-based Merkle tree configuration. | ||
|
|
||
| use { | ||
| crate::FieldElement, ark_crypto_primitives::merkle_tree::Config, | ||
| whir::crypto::merkle_tree::digest::GenericDigest, | ||
| }; | ||
|
|
||
| pub type Blake3Digest = GenericDigest<32>; | ||
|
|
||
| #[derive(Clone, Debug)] | ||
| pub struct Blake3MerkleConfig; | ||
|
|
||
| impl Config for Blake3MerkleConfig { | ||
| type Leaf = [FieldElement]; | ||
| type LeafDigest = Blake3Digest; | ||
| type LeafInnerDigestConverter = | ||
| ark_crypto_primitives::merkle_tree::IdentityDigestConverter<Blake3Digest>; | ||
| type InnerDigest = Blake3Digest; | ||
| type LeafHash = crate::blake3::Blake3LeafHash; | ||
| type TwoToOneHash = crate::blake3::Blake3Compress; | ||
| } | ||
|
|
||
| impl crate::hash_config::TypedHashConfig for Blake3MerkleConfig { | ||
| const HASH_CONFIG: crate::HashConfig = crate::HashConfig::Blake3; | ||
| type Sponge = crate::blake3::Blake3Sponge; | ||
| type Unit = u8; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| //! BLAKE3-based hash components for ProveKit. | ||
|
|
||
| mod hash; | ||
| mod merkle; | ||
| mod pow; | ||
| mod sponge; | ||
| mod whir; | ||
|
|
||
| pub use { | ||
| hash::{Blake3Compress, Blake3LeafHash}, | ||
| merkle::{Blake3Digest, Blake3MerkleConfig}, | ||
| pow::Blake3PoW, | ||
| sponge::Blake3Sponge, | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| //! BLAKE3-based Proof-of-Work implementation. | ||
| //! | ||
| //! Re-exports the Blake3PoW implementation from spongefish-pow library. | ||
|
|
||
| pub use spongefish_pow::blake3::Blake3PoW; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| //! BLAKE3 sponge for Fiat-Shamir transcripts. | ||
|
||
| //! | ||
| //! This module provides a BLAKE3-based duplex sponge construction | ||
| //! for Fiat-Shamir transformations in WHIR proofs, leveraging BLAKE3's | ||
| //! extendable output function (XOF) capabilities. | ||
|
|
||
| use {blake3, spongefish::duplex_sponge::DuplexSpongeInterface, zeroize::Zeroize}; | ||
|
|
||
| /// BLAKE3 duplex sponge for Fiat-Shamir transcripts. | ||
| /// | ||
| /// This provides a duplex sponge construction using BLAKE3's XOF mode. | ||
| /// BLAKE3 is a modern, fast cryptographic hash function with excellent | ||
| /// performance characteristics. | ||
| /// | ||
| /// - **Performance**: Typically faster than SHA256 and Keccak | ||
| /// - **Security**: 256-bit security level | ||
| /// - **XOF**: Extendable output function for arbitrary-length outputs | ||
| #[derive(Clone)] | ||
| pub struct Blake3Sponge { | ||
| /// Current hasher state for absorbing | ||
| hasher: blake3::Hasher, | ||
| /// Cached output for squeezing | ||
| output_reader: Option<blake3::OutputReader>, | ||
| /// Mode: true = absorbing, false = squeezing | ||
| absorbing: bool, | ||
| } | ||
|
|
||
| impl Default for Blake3Sponge { | ||
| fn default() -> Self { | ||
| Self { | ||
| hasher: blake3::Hasher::new(), | ||
| output_reader: None, | ||
| absorbing: true, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl DuplexSpongeInterface<u8> for Blake3Sponge { | ||
| fn new(iv: [u8; 32]) -> Self { | ||
| let mut hasher = blake3::Hasher::new(); | ||
| hasher.update(&iv); | ||
| Self { | ||
| hasher, | ||
| output_reader: None, | ||
| absorbing: true, | ||
| } | ||
| } | ||
|
|
||
| fn absorb_unchecked(&mut self, input: &[u8]) -> &mut Self { | ||
| // If we were squeezing, finalize that phase and restart | ||
| if !self.absorbing { | ||
| // Ratchet: hash the previous state to get a new starting point | ||
| let prev_hash = if let Some(ref mut reader) = self.output_reader { | ||
| let mut buf = [0u8; 32]; | ||
| reader.fill(&mut buf); | ||
| buf | ||
| } else { | ||
| *self.hasher.finalize().as_bytes() | ||
| }; | ||
|
|
||
| self.hasher = blake3::Hasher::new(); | ||
| self.hasher.update(&prev_hash); | ||
| self.output_reader = None; | ||
| self.absorbing = true; | ||
| } | ||
|
|
||
| self.hasher.update(input); | ||
| self | ||
| } | ||
|
|
||
| fn squeeze_unchecked(&mut self, output: &mut [u8]) -> &mut Self { | ||
| // If we were absorbing, switch to squeezing mode | ||
| if self.absorbing { | ||
| self.output_reader = Some(self.hasher.finalize_xof()); | ||
| self.absorbing = false; | ||
| } | ||
|
|
||
| if let Some(ref mut reader) = self.output_reader { | ||
| reader.fill(output); | ||
| } | ||
| self | ||
| } | ||
|
|
||
| fn ratchet_unchecked(&mut self) -> &mut Self { | ||
| // Finalize current state and restart with the hash as seed | ||
| let hash = if let Some(ref mut reader) = self.output_reader { | ||
| let mut buf = [0u8; 32]; | ||
| reader.fill(&mut buf); | ||
| buf | ||
| } else { | ||
| *self.hasher.finalize().as_bytes() | ||
| }; | ||
|
|
||
| self.hasher = blake3::Hasher::new(); | ||
| self.hasher.update(&hash); | ||
| self.output_reader = None; | ||
| self.absorbing = true; | ||
| self | ||
| } | ||
| } | ||
|
|
||
| impl Zeroize for Blake3Sponge { | ||
| fn zeroize(&mut self) { | ||
| self.hasher = blake3::Hasher::new(); | ||
| self.output_reader = None; | ||
| self.absorbing = true; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
arrayvecunused.