miden_crypto/utils/mod.rs
1//! Utilities used in this crate which can also be generally useful downstream.
2
3use alloc::{boxed::Box, string::String, vec::Vec};
4use core::{
5 fmt::{self, Write},
6 mem::{ManuallyDrop, MaybeUninit},
7};
8
9// Re-export serialization traits from miden-serde-utils
10#[cfg(feature = "std")]
11pub use miden_serde_utils::ReadAdapter;
12pub use miden_serde_utils::{
13 BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
14 SliceReader,
15};
16use p3_maybe_rayon::prelude::*;
17
18use crate::{Felt, Word, field::QuotientMap};
19
20// CONSTANTS
21// ================================================================================================
22
23/// The number of byte chunks that can be safely embedded in a field element
24const BINARY_CHUNK_SIZE: usize = 7;
25
26// RE-EXPORTS
27// ================================================================================================
28
29pub use k256::elliptic_curve::zeroize;
30
31// UTILITY FUNCTIONS
32// ================================================================================================
33
34/// Converts a [Word] into hex.
35pub fn word_to_hex(w: &Word) -> Result<String, fmt::Error> {
36 let mut s = String::new();
37
38 for byte in w.iter().flat_map(|&e| e.to_bytes()) {
39 write!(s, "{byte:02x}")?;
40 }
41
42 Ok(s)
43}
44
45/// Writes `bytes` into the formatter as a `0x`-prefixed, lowercase hexadecimal string.
46///
47/// Useful for `Display` implementations that want compact, canonical hex output (e.g. in `tracing`
48/// logs) without allocating an intermediate `String`. This mirrors the format produced by
49/// [`bytes_to_hex_string`], which only accepts fixed-size arrays.
50pub fn write_hex(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
51 write!(f, "0x")?;
52 for byte in bytes {
53 write!(f, "{byte:02x}")?;
54 }
55 Ok(())
56}
57
58pub use miden_field::utils::{HexParseError, bytes_to_hex_string, hex_to_bytes};
59
60/// Reads a fixed-size byte array from `source`, wrapped in [`Zeroizing`](zeroize::Zeroizing) so
61/// the buffer is wiped on drop regardless of how the calling function exits, including `?` early
62/// returns on malformed input.
63///
64/// Deserialization of sensitive material (secret keys, seeds) should read its bytes through this
65/// helper instead of calling `read_array` and remembering a manual `zeroize()` before every
66/// return path.
67///
68/// Note: `ByteReader::read_array` returns the array by value, so the single move into the
69/// wrapper is not wiped. This is the same residual a manual `zeroize()` call has; the helper
70/// closes the error-path leak and removes the per-call-site cleanup, but a fully airtight read
71/// would require `ByteReader` to expose reading into a caller-provided `&mut [u8]`.
72pub(crate) fn read_sensitive_array<const N: usize, R: ByteReader>(
73 source: &mut R,
74) -> Result<zeroize::Zeroizing<[u8; N]>, DeserializationError> {
75 Ok(zeroize::Zeroizing::new(source.read_array()?))
76}
77
78// CONVERSIONS BETWEEN BYTES AND ELEMENTS
79// ================================================================================================
80
81/// Converts a sequence of bytes into vector field elements with padding. This guarantees that no
82/// two sequences or bytes map to the same sequence of field elements.
83///
84/// Packs bytes into chunks of `BINARY_CHUNK_SIZE` and adds padding to the final chunk using a `1`
85/// bit followed by zeros. This ensures the original bytes can be recovered during decoding without
86/// any ambiguity.
87///
88/// Note that by the endianness of the conversion as well as the fact that we are packing at most
89/// `56 = 7 * 8` bits in each field element, the padding above with `1` should never overflow the
90/// field size.
91///
92/// # Arguments
93/// * `bytes` - Byte slice to encode
94///
95/// # Returns
96/// Vector of `Felt` elements with the last element containing padding
97pub fn bytes_to_elements_with_padding(bytes: &[u8]) -> Vec<Felt> {
98 if bytes.is_empty() {
99 return vec![];
100 }
101
102 // determine the number of field elements needed to encode `bytes` when each field element
103 // represents at most 7 bytes.
104 let num_field_elem = bytes.len().div_ceil(BINARY_CHUNK_SIZE);
105
106 // initialize a buffer to receive the little-endian elements.
107 let mut buf = [0_u8; 8];
108
109 // iterate the chunks of bytes, creating a field element from each chunk
110 let last_chunk_idx = num_field_elem - 1;
111
112 bytes
113 .chunks(BINARY_CHUNK_SIZE)
114 .enumerate()
115 .map(|(current_chunk_idx, chunk)| {
116 // copy the chunk into the buffer
117 if current_chunk_idx != last_chunk_idx {
118 buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
119 } else {
120 // on the last iteration, we pad `buf` with a 1 followed by as many 0's as are
121 // needed to fill it
122 buf.fill(0);
123 buf[..chunk.len()].copy_from_slice(chunk);
124 buf[chunk.len()] = 1;
125 }
126
127 Felt::new_unchecked(u64::from_le_bytes(buf))
128 })
129 .collect()
130}
131
132/// Converts a sequence of padded field elements back to the original bytes.
133///
134/// Reconstructs the original byte sequence by removing the padding added by
135/// `bytes_to_elements_with_padding`.
136/// The padding consists of a `1` bit followed by zeros in the final field element.
137/// Any bytes after the last `1` marker in the final field element are ignored and are not
138/// validated to be zero.
139///
140/// Note that by the endianness of the conversion as well as the fact that we are packing at most
141/// `56 = 7 * 8` bits in each field element, the padding above with `1` should never overflow the
142/// field size.
143///
144/// # Arguments
145/// * `felts` - Slice of field elements with padding in the last element
146///
147/// # Returns
148/// * `Some(Vec<u8>)` - The original byte sequence with padding removed
149/// * `None` - If no padding marker (`1` bit) is found
150pub fn padded_elements_to_bytes(felts: &[Felt]) -> Option<Vec<u8>> {
151 let number_felts = felts.len();
152 if number_felts == 0 {
153 return Some(vec![]);
154 }
155
156 let mut result = Vec::with_capacity(number_felts * BINARY_CHUNK_SIZE);
157 for felt in felts.iter().take(number_felts - 1) {
158 let felt_bytes = felt.as_canonical_u64().to_le_bytes();
159 result.extend_from_slice(&felt_bytes[..BINARY_CHUNK_SIZE]);
160 }
161
162 // handle the last field element
163 let felt_bytes = felts[number_felts - 1].as_canonical_u64().to_le_bytes();
164 let pos = felt_bytes.iter().rposition(|entry| *entry == 1_u8)?;
165
166 result.extend_from_slice(&felt_bytes[..pos]);
167 Some(result)
168}
169
170/// Converts field elements to raw byte representation.
171///
172/// Each `Felt` is converted to its full `NUM_BYTES` representation, in little-endian form
173/// and canonical form, without any padding removal or validation. This is the inverse
174/// of `bytes_to_elements_exact`.
175///
176/// # Arguments
177/// * `felts` - Slice of field elements to convert
178///
179/// # Returns
180/// Vector containing the raw bytes from all field elements
181pub fn elements_to_bytes(felts: &[Felt]) -> Vec<u8> {
182 let number_felts = felts.len();
183 let mut result = Vec::with_capacity(number_felts * Felt::NUM_BYTES);
184 for felt in felts.iter().take(number_felts) {
185 let felt_bytes = felt.as_canonical_u64().to_le_bytes();
186 result.extend_from_slice(&felt_bytes);
187 }
188
189 result
190}
191
192/// Converts bytes to field elements with validation.
193///
194/// This function validates that:
195/// - The input bytes length is divisible by `Felt::NUM_BYTES`
196/// - All `Felt::NUM_BYTES`-byte sequences represent valid field elements
197///
198/// # Arguments
199/// * `bytes` - Byte slice that must be a multiple of `Felt::NUM_BYTES` in length
200///
201/// # Returns
202/// `Option<Vec<Felt>>` - Vector of `Felt` elements if all validations pass, or None otherwise
203pub fn bytes_to_elements_exact(bytes: &[u8]) -> Option<Vec<Felt>> {
204 // Check that the length is divisible by NUM_BYTES
205 if !bytes.len().is_multiple_of(Felt::NUM_BYTES) {
206 return None;
207 }
208
209 let mut result = Vec::with_capacity(bytes.len() / Felt::NUM_BYTES);
210
211 for chunk in bytes.chunks_exact(Felt::NUM_BYTES) {
212 let chunk_array: [u8; Felt::NUM_BYTES] =
213 chunk.try_into().expect("should succeed given the length check above");
214
215 let value = u64::from_le_bytes(chunk_array);
216
217 // Validate that the value represents a valid field element
218 let felt = Felt::from_canonical_checked(value)?;
219 result.push(felt);
220 }
221
222 Some(result)
223}
224
225/// Converts bytes to field elements using u32 packing in little-endian format.
226///
227/// Each field element contains a u32 value representing up to 4 bytes. If the byte length
228/// is not a multiple of 4, the final field element is zero-padded.
229///
230/// # Arguments
231/// - `bytes`: The byte slice to convert
232///
233/// # Returns
234/// A vector of field elements, each containing 4 bytes packed in little-endian order.
235///
236/// # Examples
237/// ```rust
238/// # use miden_crypto::{Felt, utils::bytes_to_packed_u32_elements};
239///
240/// let bytes = vec![0x01, 0x02, 0x03, 0x04, 0x05];
241/// let felts = bytes_to_packed_u32_elements(&bytes);
242/// assert_eq!(felts, vec![Felt::new_unchecked(0x04030201), Felt::new_unchecked(0x00000005)]);
243/// ```
244pub fn bytes_to_packed_u32_elements(bytes: &[u8]) -> Vec<Felt> {
245 const BYTES_PER_U32: usize = size_of::<u32>();
246
247 bytes
248 .chunks(BYTES_PER_U32)
249 .map(|chunk| {
250 // Pack up to 4 bytes into a u32 in little-endian format
251 let mut packed = [0u8; BYTES_PER_U32];
252 packed[..chunk.len()].copy_from_slice(chunk);
253 Felt::from_u32(u32::from_le_bytes(packed))
254 })
255 .collect()
256}
257
258// VECTOR FUNCTIONS (ported from Winterfell's winter-utils)
259// ================================================================================================
260
261/// Returns a vector of the specified length with un-initialized memory.
262///
263/// This is usually faster than requesting a vector with initialized memory and is useful when we
264/// overwrite all contents of the vector immediately after memory allocation.
265pub fn uninit_vector<T>(length: usize) -> Vec<MaybeUninit<T>> {
266 Vec::from(Box::new_uninit_slice(length))
267}
268
269/// Converts a fully-initialized `Vec<MaybeUninit<T>>` into `Vec<T>`.
270///
271/// # Safety
272/// All elements must be initialized before calling this function.
273pub unsafe fn assume_init_vec<T>(v: Vec<MaybeUninit<T>>) -> Vec<T> {
274 let mut v = ManuallyDrop::new(v);
275 let ptr = v.as_mut_ptr();
276 let len = v.len();
277 let cap = v.capacity();
278 // SAFETY: caller guarantees all elements are initialized.
279 unsafe { Vec::from_raw_parts(ptr.cast::<T>(), len, cap) }
280}
281
282// GROUPING / UN-GROUPING FUNCTIONS (ported from Winterfell's winter-utils)
283// ================================================================================================
284
285/// Transmutes a slice of `n` elements into a slice of `n` / `N` elements, each of which is
286/// an array of `N` elements.
287///
288/// This function just re-interprets the underlying memory and is thus zero-copy.
289/// # Panics
290/// Panics if `n` is not divisible by `N`.
291pub fn group_slice_elements<T, const N: usize>(source: &[T]) -> &[[T; N]] {
292 let (chunks, remainder) = source.as_chunks::<N>();
293 assert!(remainder.is_empty(), "source length must be divisible by {N}");
294 chunks
295}
296
297/// Transmutes a slice of `n` arrays each of length `N`, into a slice of `N` * `n` elements.
298///
299/// This function just re-interprets the underlying memory and is thus zero-copy.
300pub fn flatten_slice_elements<T, const N: usize>(source: &[[T; N]]) -> &[T] {
301 // SAFETY: [T; N] has the same alignment and memory layout as an array of T.
302 // p3-util's as_base_slice handles the conversion safely.
303 unsafe { p3_util::as_base_slice(source) }
304}
305
306/// Transmutes a vector of `n` arrays each of length `N`, into a vector of `N` * `n` elements.
307///
308/// This function just re-interprets the underlying memory and is thus zero-copy.
309pub fn flatten_vector_elements<T, const N: usize>(source: Vec<[T; N]>) -> Vec<T> {
310 // SAFETY: [T; N] has the same alignment and memory layout as an array of T.
311 // p3-util's flatten_to_base handles the conversion without reallocations.
312 unsafe { p3_util::flatten_to_base(source) }
313}
314
315// TRANSPOSING (ported from Winterfell's winter-utils)
316// ================================================================================================
317
318/// Transposes a slice of `n` elements into a matrix with `N` columns and `n`/`N` rows.
319///
320/// When `concurrent` feature is enabled, the slice will be transposed using multiple threads.
321/// Uses uninit_vector for ~31% speedup at 1024x1024 (benches/transpose.rs).
322///
323/// # Panics
324/// Panics if `n` is not divisible by `N`.
325pub fn transpose_slice<T: Copy + Send + Sync, const N: usize>(source: &[T]) -> Vec<[T; N]> {
326 let row_count = source.len() / N;
327 assert_eq!(
328 row_count * N,
329 source.len(),
330 "source length must be divisible by {}, but was {}",
331 N,
332 source.len()
333 );
334
335 let mut result = uninit_vector::<[T; N]>(row_count);
336 result.par_iter_mut().enumerate().for_each(|(i, slot)| {
337 let row = core::array::from_fn(|j| source[i + j * row_count]);
338 slot.write(row);
339 });
340 // SAFETY: all rows are written above.
341 unsafe { assume_init_vec(result) }
342}