Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 11 additions & 20 deletions soroban-sdk/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ pub(crate) mod poseidon_params;
pub mod poseidon_sponge;
pub(crate) mod utils;
pub use bn254::Fr as BnScalar;
pub use poseidon2_sponge::Poseidon2Sponge;
pub use poseidon_sponge::PoseidonSponge;
pub use poseidon2_sponge::{Poseidon2Config, Poseidon2Sponge};
pub use poseidon_sponge::{PoseidonConfig, PoseidonSponge};

/// A `BytesN<N>` generated by a cryptographic hash function.
///
Expand Down Expand Up @@ -199,26 +199,17 @@ impl Crypto {
bn254::Bn254::new(self.env())
}

/// Performs a Poseidon hash using a sponge construction
pub fn poseidon_hash(&self, inputs: &Vec<U256>, field: Symbol) -> U256 {
// The initial value for the capacity element initialized with 0 for standard Poseidon
let iv = U256::from_u32(&self.env, 0);
let mut sponge = PoseidonSponge::new(&self.env, iv, field);
for input in inputs.iter() {
sponge.absorb(input);
}
sponge.squeeze()
/// Performs a Poseidon hash using a sponge construction that matches circom's [implementation](https://github.com/iden3/circomlib/blob/35e54ea21da3e8762557234298dbb553c175ea8d/circuits/poseidon.circom)
Comment thread
jayz22 marked this conversation as resolved.
Outdated
pub fn poseidon_hash<const N: usize>(&self, field_type: Symbol, inputs: &[U256; N]) -> U256 {
Comment thread
jayz22 marked this conversation as resolved.
Outdated
let config = PoseidonConfig::new(&self.env, field_type, N as u32);
poseidon_sponge::hash(&self.env, inputs, config)
}

/// Performs a poseidon2 hash with a sponge construction equivalent to the one in the Barretenberg proving system
pub fn poseidon2_hash(&self, inputs: &Vec<U256>, field: Symbol) -> U256 {
// The initial value for the capacity element initialized with `input.len() * 2^24` for Poseidon2
let iv = U256::from_u128(&self.env, (inputs.len() as u128) << 64);
let mut sponge = Poseidon2Sponge::new(&self.env, iv, field);
for input in inputs.iter() {
sponge.absorb(input);
}
sponge.squeeze()
/// Performs a poseidon2 hash with a sponge construction that matches noir's implementation.
/// Uses rate=3 (t=4) to match the noir/barretenberg [implementation](https://github.com/noir-lang/noir/blob/abfee1f54b20984172ba23482f4af160395cfba5/noir_stdlib/src/hash/poseidon2.nr).
pub fn poseidon2_hash<const N: usize>(&self, field_type: Symbol, inputs: &[U256; N]) -> U256 {
let config = Poseidon2Config::new(&self.env, field_type, 3);
poseidon2_sponge::hash(&self.env, inputs, config)
Comment thread
jayz22 marked this conversation as resolved.
Outdated
}
}

Expand Down
Loading
Loading