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::String;
42#[cfg(all(feature = "alloc", feature = "std"))]
43use alloc::string::ToString;
44
45mod constants;
46#[cfg(feature = "alloc")]
47mod params;
48#[cfg(feature = "alloc")]
49mod permutation;
50#[cfg(feature = "alloc")]
51mod sponge;
52
53// Export constants for AIR constraint generation
54pub use constants::sbox;
55#[cfg(feature = "alloc")]
56pub use constants::{
57    mds_matrix_5x5,
58    mds_matrix_7x7,
59};
60#[cfg(feature = "alloc")]
61pub use constants::{
62    round_constants_128,
63    round_constants_256,
64};
65#[cfg(feature = "alloc")]
66pub use params::{
67    Poseidon128,
68    Poseidon256,
69    PoseidonField,
70    PoseidonParams,
71};
72#[cfg(feature = "alloc")]
73pub use permutation::{
74    PoseidonPermutation,
75    PoseidonState,
76};
77#[cfg(feature = "alloc")]
78pub use sponge::{
79    Poseidon,
80    PoseidonSponge,
81    PoseidonSpongeSqueeze,
82};
83
84#[cfg(feature = "wasm")]
85pub mod wasm;
86
87/// Error types for Poseidon operations
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum PoseidonError {
90    /// Input size exceeds maximum allowed
91    InputTooLarge { max: usize, actual: usize },
92    /// Invalid parameter configuration
93    #[cfg(feature = "alloc")]
94    InvalidParams { reason: String },
95    /// Internal error during hashing
96    #[cfg(feature = "alloc")]
97    InternalError { reason: String },
98}
99
100impl core::fmt::Display for PoseidonError {
101    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
102        match self {
103            PoseidonError::InputTooLarge { max, actual } => {
104                write!(f, "Input size {} exceeds maximum {}", actual, max)
105            }
106            #[cfg(feature = "alloc")]
107            PoseidonError::InvalidParams { reason } => {
108                write!(f, "Invalid Poseidon parameters: {}", reason)
109            }
110            #[cfg(feature = "alloc")]
111            PoseidonError::InternalError { reason } => {
112                write!(f, "Internal Poseidon error: {}", reason)
113            }
114        }
115    }
116}
117
118#[cfg(all(feature = "alloc", feature = "std"))]
119impl From<PoseidonError> for lib_q_core::Error {
120    fn from(err: PoseidonError) -> Self {
121        lib_q_core::Error::InternalError {
122            operation: "Poseidon hash".into(),
123            details: err.to_string(),
124        }
125    }
126}
127
128#[cfg(all(not(feature = "alloc"), feature = "std"))]
129impl From<PoseidonError> for lib_q_core::Error {
130    fn from(err: PoseidonError) -> Self {
131        match err {
132            PoseidonError::InputTooLarge { .. } => lib_q_core::Error::InternalError {
133                operation: "Poseidon hash",
134                details: "input too large",
135            },
136        }
137    }
138}