Skip to main content

snarkvm_console_algorithms/bhp/hasher/
hash_uncompressed.rs

1// Copyright (c) 2019-2026 Provable Inc.
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!(
33            input.len() > Self::MIN_BITS,
34            "Inputs to this BHP must be greater than {} bits (window size: {WINDOW_SIZE}, num windows: {NUM_WINDOWS}), actual bits: {}",
35            Self::MIN_BITS,
36            input.len()
37        );
38        // Ensure the input size is within the parameter size,
39        ensure!(
40            input.len() <= Self::MAX_BITS,
41            "Inputs to this BHP cannot exceed {} bits, found {}",
42            Self::MAX_BITS,
43            input.len()
44        );
45
46        // Pad the input to a multiple of `BHP_CHUNK_SIZE` for hashing.
47        let input = if input.len() % BHP_CHUNK_SIZE != 0 {
48            let padding = BHP_CHUNK_SIZE - (input.len() % BHP_CHUNK_SIZE);
49            let mut padded_input = vec![false; input.len() + padding];
50            padded_input[..input.len()].copy_from_slice(input);
51            ensure!((padded_input.len() % BHP_CHUNK_SIZE) == 0, "Input must be a multiple of {BHP_CHUNK_SIZE}");
52            Cow::Owned(padded_input)
53        } else {
54            Cow::Borrowed(input)
55        };
56
57        // 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}
58        // for all i (described in section 5.4.1.7 in the Zcash protocol specification) in batched form: the summand
59        // resulting from each group of BHP_NUM_COMBINED_CHUNKS = 4 bit triplets (c_{i,j,0}, c_{i,j,1}, c_{i,j,2})
60        // has already been precomputed in `combined_bases_lookup`.
61        let sum = input
62            .chunks(WINDOW_SIZE as usize * BHP_CHUNK_SIZE)
63            .zip(self.combined_bases_lookup.iter())
64            .zip(self.bases_lookup.iter())
65            .flat_map(|((window_bits, combined_bases), bases)| {
66                // The number of full BHP_CHUNK_SIZE-bit chunks in the window.
67                // The preprocessed points corresponding to these will be looked
68                // up in combined_bases.
69                let num_combined_bases = window_bits.len() / (BHP_CHUNK_SIZE * BHP_NUM_COMBINED_CHUNKS);
70                // The number of bits in the window belonging to full chunks.
71                let num_combined_bits = num_combined_bases * BHP_CHUNK_SIZE * BHP_NUM_COMBINED_CHUNKS;
72
73                let combined = window_bits[..num_combined_bits]
74                    .chunks_exact(BHP_CHUNK_SIZE * BHP_NUM_COMBINED_CHUNKS)
75                    .zip(combined_bases)
76                    .map(|(combined_chunks_bits, combined_base)| {
77                        // Reconstruct the index as the integer represented by the bits of the combined chunks
78                        // in a suitable order.
79                        let index = combined_chunks_bits.chunks_exact(BHP_CHUNK_SIZE).fold(0, |idx, chunk_bits| {
80                            (idx << BHP_CHUNK_SIZE)
81                                | (chunk_bits[0] as usize)
82                                | (chunk_bits[1] as usize) << 1
83                                | (chunk_bits[2] as usize) << 2
84                        });
85
86                        combined_base[index]
87                    });
88
89                // Trailing bits outside the last BHP_NUM_COMBINED_CHUNKS-chunk
90                // result in lookups `bases` table.
91                let base_offset = num_combined_bases * BHP_NUM_COMBINED_CHUNKS;
92                let trailing = &window_bits[num_combined_bits..];
93                let remainder =
94                    trailing.chunks_exact(BHP_CHUNK_SIZE).enumerate().map(move |(triplet_index, chunk_bits)| {
95                        let idx =
96                            (chunk_bits[0] as usize) | (chunk_bits[1] as usize) << 1 | (chunk_bits[2] as usize) << 2;
97                        bases[base_offset + triplet_index][idx]
98                    });
99
100                combined.chain(remainder)
101            })
102            .sum();
103
104        Ok(sum)
105    }
106}