snarkvm_console_algorithms/bhp/mod.rs
1// Copyright (c) 2019-2025 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
16pub mod hasher;
17use hasher::BHPHasher;
18
19mod commit;
20mod commit_uncompressed;
21mod hash;
22mod hash_uncompressed;
23
24use snarkvm_console_types::prelude::*;
25
26use serde::{Deserialize, Serialize};
27use std::sync::Arc;
28
29const BHP_CHUNK_SIZE: usize = 3;
30
31/// BHP256 is a collision-resistant hash function that processes 256-bit chunks.
32pub type BHP256<E> = BHP<E, 3, 57>; // Supports inputs up to 261 bits (1 u8 + 1 Fq).
33/// BHP512 is a collision-resistant hash function that processes inputs in 512-bit chunks.
34pub type BHP512<E> = BHP<E, 6, 43>; // Supports inputs up to 522 bits (2 u8 + 2 Fq).
35/// BHP768 is a collision-resistant hash function that processes inputs in 768-bit chunks.
36pub type BHP768<E> = BHP<E, 15, 23>; // Supports inputs up to 783 bits (3 u8 + 3 Fq).
37/// BHP1024 is a collision-resistant hash function that processes inputs in 1024-bit chunks.
38pub type BHP1024<E> = BHP<E, 8, 54>; // Supports inputs up to 1044 bits (4 u8 + 4 Fq).
39
40/// BHP is a collision-resistant hash function that takes a variable-length input.
41/// The BHP hash function does *not* behave like a random oracle, see Poseidon for one.
42///
43/// ## Design
44/// The BHP hash function splits the given input into blocks, and processes them iteratively.
45///
46/// The first iteration is initialized as follows:
47/// ```text
48/// DIGEST_0 = BHP([ 0...0 || DOMAIN || LENGTH(INPUT) || INPUT[0..BLOCK_SIZE] ]);
49/// ```
50/// Each subsequent iteration is initialized as follows:
51/// ```text
52/// DIGEST_N+1 = BHP([ DIGEST_N[0..DATA_BITS] || INPUT[(N+1)*BLOCK_SIZE..(N+2)*BLOCK_SIZE] ]);
53/// ```
54#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
55#[serde(bound = "E: Serialize + DeserializeOwned")]
56pub struct BHP<E: Environment, const NUM_WINDOWS: u8, const WINDOW_SIZE: u8> {
57 /// The domain separator for the BHP hash function.
58 domain: Vec<bool>,
59 /// The internal BHP hasher used to process one iteration.
60 hasher: BHPHasher<E, NUM_WINDOWS, WINDOW_SIZE>,
61}
62
63impl<E: Environment, const NUM_WINDOWS: u8, const WINDOW_SIZE: u8> BHP<E, NUM_WINDOWS, WINDOW_SIZE> {
64 /// Initializes a new instance of BHP with the given domain.
65 pub fn setup(domain: &str) -> Result<Self> {
66 // Ensure the given domain is within the allowed size in bits.
67 let num_bits = domain.len().saturating_mul(8);
68 let max_bits = Field::<E>::size_in_data_bits() - 64; // 64 bits encode the length.
69 ensure!(num_bits <= max_bits, "Domain cannot exceed {max_bits} bits, found {num_bits} bits");
70
71 // Initialize the BHP hasher.
72 let hasher = BHPHasher::<E, NUM_WINDOWS, WINDOW_SIZE>::setup(domain)?;
73
74 // Convert the domain into a boolean vector.
75 let mut domain = domain.as_bytes().to_bits_le();
76 // Pad the domain with zeros up to the maximum size in bits.
77 domain.resize(max_bits, false);
78 // Reverse the domain so that it is: [ 0...0 || DOMAIN ].
79 // (For advanced users): This optimizes the initial costs during hashing.
80 domain.reverse();
81
82 Ok(Self { domain, hasher })
83 }
84
85 /// Returns the domain separator for the BHP hash function.
86 pub fn domain(&self) -> &[bool] {
87 &self.domain
88 }
89
90 /// Returns the bases.
91 pub fn bases(&self) -> &Arc<Vec<Vec<Group<E>>>> {
92 self.hasher.bases()
93 }
94
95 /// Returns the random base window.
96 pub fn random_base(&self) -> &Arc<Vec<Group<E>>> {
97 self.hasher.random_base()
98 }
99
100 /// Returns the number of windows.
101 pub fn num_windows(&self) -> u8 {
102 NUM_WINDOWS
103 }
104
105 /// Returns the window size.
106 pub fn window_size(&self) -> u8 {
107 WINDOW_SIZE
108 }
109}