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