p3_symmetric/
compression.rs

1use crate::hasher::CryptographicHasher;
2use crate::permutation::CryptographicPermutation;
3
4/// An `N`-to-1 compression function collision-resistant in a hash tree setting.
5///
6/// Unlike `CompressionFunction`, it may not be collision-resistant in general.
7/// Instead it is only collision-resistant in hash-tree like settings where
8/// the preimage of a non-leaf node must consist of compression outputs.
9pub trait PseudoCompressionFunction<T, const N: usize>: Clone {
10    fn compress(&self, input: [T; N]) -> T;
11}
12
13/// An `N`-to-1 compression function.
14pub trait CompressionFunction<T, const N: usize>: PseudoCompressionFunction<T, N> {}
15
16#[derive(Clone, Debug)]
17pub struct TruncatedPermutation<InnerP, const N: usize, const CHUNK: usize, const WIDTH: usize> {
18    inner_permutation: InnerP,
19}
20
21impl<InnerP, const N: usize, const CHUNK: usize, const WIDTH: usize>
22    TruncatedPermutation<InnerP, N, CHUNK, WIDTH>
23{
24    pub const fn new(inner_permutation: InnerP) -> Self {
25        Self { inner_permutation }
26    }
27}
28
29impl<T, InnerP, const N: usize, const CHUNK: usize, const WIDTH: usize>
30    PseudoCompressionFunction<[T; CHUNK], N> for TruncatedPermutation<InnerP, N, CHUNK, WIDTH>
31where
32    T: Copy + Default,
33    InnerP: CryptographicPermutation<[T; WIDTH]>,
34{
35    fn compress(&self, input: [[T; CHUNK]; N]) -> [T; CHUNK] {
36        debug_assert!(CHUNK * N <= WIDTH);
37        let mut pre = [T::default(); WIDTH];
38        for i in 0..N {
39            pre[i * CHUNK..(i + 1) * CHUNK].copy_from_slice(&input[i]);
40        }
41        let post = self.inner_permutation.permute(pre);
42        post[..CHUNK].try_into().unwrap()
43    }
44}
45
46#[derive(Clone, Debug)]
47pub struct CompressionFunctionFromHasher<H, const N: usize, const CHUNK: usize> {
48    hasher: H,
49}
50
51impl<H, const N: usize, const CHUNK: usize> CompressionFunctionFromHasher<H, N, CHUNK> {
52    pub const fn new(hasher: H) -> Self {
53        Self { hasher }
54    }
55}
56
57impl<T, H, const N: usize, const CHUNK: usize> PseudoCompressionFunction<[T; CHUNK], N>
58    for CompressionFunctionFromHasher<H, N, CHUNK>
59where
60    T: Clone,
61    H: CryptographicHasher<T, [T; CHUNK]>,
62{
63    fn compress(&self, input: [[T; CHUNK]; N]) -> [T; CHUNK] {
64        self.hasher.hash_iter(input.into_iter().flatten())
65    }
66}
67
68impl<T, H, const N: usize, const CHUNK: usize> CompressionFunction<[T; CHUNK], N>
69    for CompressionFunctionFromHasher<H, N, CHUNK>
70where
71    T: Clone,
72    H: CryptographicHasher<T, [T; CHUNK]>,
73{
74}