Skip to main content

lib_q_poseidon/
lib.rs

1//! Poseidon hash function optimized for zero-knowledge proofs
2//!
3//! This crate provides a field-native implementation of the Poseidon hash function,
4//! specifically optimized for use in STARK proof systems with `Complex<Mersenne31>`.
5//!
6//! # Design
7//!
8//! Poseidon is an algebraic hash function designed for efficient implementation in
9//! zero-knowledge proof systems. Unlike traditional hashes like SHA-3, Poseidon
10//! operates directly on field elements, making it orders of magnitude more efficient
11//! in circuit constraints.
12//!
13//! # Security
14//!
15//! - Uses conservative round counts based on peer-reviewed research
16//! - MDS matrices generated using secure methods
17//! - Parameters chosen for 128-bit and 256-bit security levels
18//!
19//! # Example
20//!
21//! ```rust,ignore
22//! use lib_q_poseidon::{Poseidon, Poseidon128};
23//! use lib_q_stark_field::extension::Complex;
24//! use lib_q_stark_mersenne31::Mersenne31;
25//!
26//! type Val = Complex<Mersenne31>;
27//!
28//! let hasher = Poseidon128::permutation();
29//! let input = vec![Val::from(1u32), Val::from(2u32)];
30//! let hash = hasher.hash(&input);
31//! ```
32
33#![cfg_attr(not(feature = "std"), no_std)]
34#![deny(unsafe_code)]
35#![deny(unused_qualifications)]
36
37#[cfg(feature = "alloc")]
38extern crate alloc;
39
40#[cfg(feature = "alloc")]
41use alloc::string::{
42    String,
43    ToString,
44};
45
46mod constants;
47#[cfg(feature = "alloc")]
48mod params;
49#[cfg(feature = "alloc")]
50mod permutation;
51#[cfg(feature = "alloc")]
52mod sponge;
53
54// Export constants for AIR constraint generation
55pub use constants::sbox;
56#[cfg(feature = "alloc")]
57pub use constants::{
58    mds_matrix_5x5,
59    mds_matrix_7x7,
60};
61#[cfg(feature = "alloc")]
62pub use constants::{
63    round_constants_128,
64    round_constants_256,
65};
66#[cfg(feature = "alloc")]
67pub use params::{
68    Poseidon128,
69    Poseidon256,
70    PoseidonField,
71    PoseidonParams,
72};
73#[cfg(feature = "alloc")]
74pub use permutation::{
75    PoseidonPermutation,
76    PoseidonState,
77};
78#[cfg(feature = "alloc")]
79pub use sponge::{
80    Poseidon,
81    PoseidonSponge,
82    PoseidonSpongeSqueeze,
83};
84
85#[cfg(feature = "wasm")]
86mod wasm;
87
88/// Error types for Poseidon operations
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum PoseidonError {
91    /// Input size exceeds maximum allowed
92    InputTooLarge { max: usize, actual: usize },
93    /// Invalid parameter configuration
94    #[cfg(feature = "alloc")]
95    InvalidParams { reason: String },
96    /// Internal error during hashing
97    #[cfg(feature = "alloc")]
98    InternalError { reason: String },
99}
100
101impl core::fmt::Display for PoseidonError {
102    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
103        match self {
104            PoseidonError::InputTooLarge { max, actual } => {
105                write!(f, "Input size {} exceeds maximum {}", actual, max)
106            }
107            #[cfg(feature = "alloc")]
108            PoseidonError::InvalidParams { reason } => {
109                write!(f, "Invalid Poseidon parameters: {}", reason)
110            }
111            #[cfg(feature = "alloc")]
112            PoseidonError::InternalError { reason } => {
113                write!(f, "Internal Poseidon error: {}", reason)
114            }
115        }
116    }
117}
118
119#[cfg(feature = "alloc")]
120impl From<PoseidonError> for lib_q_core::Error {
121    fn from(err: PoseidonError) -> Self {
122        lib_q_core::Error::InternalError {
123            operation: "Poseidon hash".into(),
124            details: err.to_string(),
125        }
126    }
127}
128
129#[cfg(not(feature = "alloc"))]
130impl From<PoseidonError> for lib_q_core::Error {
131    fn from(err: PoseidonError) -> Self {
132        match err {
133            PoseidonError::InputTooLarge { .. } => lib_q_core::Error::InternalError {
134                operation: "Poseidon hash",
135                details: "input too large",
136            },
137        }
138    }
139}