Skip to main content

snarkvm_console_algorithms/bhp/
mod.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
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, OnceLock};
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, 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    /// The Merkle empty hash of this instance, once something has asked for it.
62    ///
63    /// Not serialized, so a deserialized hasher recomputes it from its own domain and bases.
64    #[serde(skip)]
65    empty_hash: OnceLock<Field<E>>,
66}
67
68impl<E: Environment, const NUM_WINDOWS: u8, const WINDOW_SIZE: u8> PartialEq for BHP<E, NUM_WINDOWS, WINDOW_SIZE> {
69    /// Ignores the cached empty hash, which is derived from the domain and bases.
70    fn eq(&self, other: &Self) -> bool {
71        // Destructured so that a new field must be considered here.
72        let Self { domain, hasher, empty_hash: _ } = self;
73        *domain == other.domain && *hasher == other.hasher
74    }
75}
76
77impl<E: Environment, const NUM_WINDOWS: u8, const WINDOW_SIZE: u8> BHP<E, NUM_WINDOWS, WINDOW_SIZE> {
78    /// Initializes a new instance of BHP with the given domain.
79    pub fn setup(domain: &str) -> Result<Self> {
80        // Ensure the given domain is within the allowed size in bits.
81        let num_bits = domain.len().saturating_mul(8);
82        let max_bits = Field::<E>::size_in_data_bits() - 64; // 64 bits encode the length.
83        ensure!(num_bits <= max_bits, "Domain cannot exceed {max_bits} bits, found {num_bits} bits");
84
85        // Initialize the BHP hasher.
86        let hasher = BHPHasher::<E, NUM_WINDOWS, WINDOW_SIZE>::setup(domain)?;
87
88        // Convert the domain into a boolean vector.
89        let mut domain = domain.as_bytes().to_bits_le();
90        // Pad the domain with zeros up to the maximum size in bits.
91        domain.resize(max_bits, false);
92        // Reverse the domain so that it is: [ 0...0 || DOMAIN ].
93        // (For advanced users): This optimizes the initial costs during hashing.
94        domain.reverse();
95
96        Ok(Self { domain, hasher, empty_hash: OnceLock::new() })
97    }
98
99    /// Returns the domain separator for the BHP hash function.
100    pub fn domain(&self) -> &[bool] {
101        &self.domain
102    }
103
104    /// Returns the Merkle empty hash of this instance, computing it on first use.
105    ///
106    /// This is `PathHash::hash_children(0, 0)` from `snarkvm-console-collections`, and
107    /// `test_cached_empty_hash_matches_the_computed_one` checks that the two agree. The
108    /// hash depends on the domain and bases, so it is cached per instance, not per type.
109    pub fn merkle_empty_hash(&self) -> Result<Field<E>> {
110        if let Some(empty_hash) = self.empty_hash.get() {
111            return Ok(*empty_hash);
112        }
113        let mut input = Vec::with_capacity(1 + Field::<E>::size_in_bits() * 2);
114        // Prepend the nodes with a `true` bit.
115        input.push(true);
116        Field::<E>::zero().write_bits_le(&mut input);
117        Field::<E>::zero().write_bits_le(&mut input);
118        let empty_hash = Hash::hash(self, &input)?;
119        Ok(*self.empty_hash.get_or_init(|| empty_hash))
120    }
121
122    /// Returns the bases.
123    pub fn bases(&self) -> &Arc<Vec<Vec<Group<E>>>> {
124        self.hasher.bases()
125    }
126
127    /// Returns the random base window.
128    pub fn random_base(&self) -> &Arc<Vec<Group<E>>> {
129        self.hasher.random_base()
130    }
131
132    /// Returns the number of windows.
133    pub fn num_windows(&self) -> u8 {
134        NUM_WINDOWS
135    }
136
137    /// Returns the window size.
138    pub fn window_size(&self) -> u8 {
139        WINDOW_SIZE
140    }
141}