snarkvm_console_algorithms/bhp/hasher/hash_uncompressed.rs
1// Copyright 2024-2025 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18use std::borrow::Cow;
19
20impl<E: Environment, const NUM_WINDOWS: u8, const WINDOW_SIZE: u8> HashUncompressed
21 for BHPHasher<E, NUM_WINDOWS, WINDOW_SIZE>
22{
23 type Input = bool;
24 type Output = Group<E>;
25
26 /// Returns the BHP hash of the given input as an affine group element.
27 ///
28 /// This uncompressed variant of the BHP hash function is provided to support
29 /// the BHP commitment scheme, as it is typically not used by applications.
30 fn hash_uncompressed(&self, input: &[Self::Input]) -> Result<Self::Output> {
31 // Ensure the input size is at least the window size.
32 ensure!(input.len() > Self::MIN_BITS, "Inputs to this BHP must be greater than {} bits", Self::MIN_BITS);
33 // Ensure the input size is within the parameter size,
34 ensure!(
35 input.len() <= Self::MAX_BITS,
36 "Inputs to this BHP cannot exceed {} bits, found {}",
37 Self::MAX_BITS,
38 input.len()
39 );
40
41 // Pad the input to a multiple of `BHP_CHUNK_SIZE` for hashing.
42 let input = if input.len() % BHP_CHUNK_SIZE != 0 {
43 let padding = BHP_CHUNK_SIZE - (input.len() % BHP_CHUNK_SIZE);
44 let mut padded_input = vec![false; input.len() + padding];
45 padded_input[..input.len()].copy_from_slice(input);
46 ensure!((padded_input.len() % BHP_CHUNK_SIZE) == 0, "Input must be a multiple of {BHP_CHUNK_SIZE}");
47 Cow::Owned(padded_input)
48 } else {
49 Cow::Borrowed(input)
50 };
51
52 // Compute sum of h_i^{sum of (1-2*c_{i,j,2})*(1+c_{i,j,0}+2*c_{i,j,1})*2^{4*(j-1)} for all j in segment}
53 // for all i. Described in section 5.4.1.7 in the Zcash protocol specification.
54 //
55 // Note: `.zip()` is used here (as opposed to `.zip_eq()`) as the input can be less than
56 // `NUM_WINDOWS * WINDOW_SIZE * BHP_CHUNK_SIZE` in length, which is the parameter size here.
57 Ok(input
58 .chunks(WINDOW_SIZE as usize * BHP_CHUNK_SIZE)
59 .zip(&*self.bases_lookup)
60 .flat_map(|(bits, bases)| {
61 bits.chunks(BHP_CHUNK_SIZE).zip(bases).map(|(chunk_bits, base)| {
62 base[(chunk_bits[0] as usize) | (chunk_bits[1] as usize) << 1 | (chunk_bits[2] as usize) << 2]
63 })
64 })
65 .sum())
66 }
67}