snarkvm_circuit_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
16mod hasher;
17use hasher::BHPHasher;
18
19mod commit;
20mod commit_uncompressed;
21mod hash;
22mod hash_uncompressed;
23
24#[cfg(all(test, feature = "console"))]
25use snarkvm_circuit_types::environment::assert_scope;
26
27use crate::{Commit, CommitUncompressed, Hash, HashUncompressed};
28use snarkvm_circuit_types::prelude::*;
29
30/// BHP256 is a collision-resistant hash function that processes inputs in 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/// The BHP chunk size (this implementation is for a 3-bit BHP).
40const BHP_CHUNK_SIZE: usize = 3;
41
42/// BHP is a collision-resistant hash function that takes a variable-length input.
43/// The BHP hash function does *not* behave like a random oracle, see Poseidon for one.
44///
45/// ## Design
46/// The BHP hash function splits the given input into blocks, and processes them iteratively.
47///
48/// The first iteration is initialized as follows:
49/// ```text
50/// DIGEST_0 = BHP([ 0...0 || DOMAIN || LENGTH(INPUT) || INPUT[0..BLOCK_SIZE] ]);
51/// ```
52/// Each subsequent iteration is initialized as follows:
53/// ```text
54/// DIGEST_N+1 = BHP([ DIGEST_N[0..DATA_BITS] || INPUT[(N+1)*BLOCK_SIZE..(N+2)*BLOCK_SIZE] ]);
55/// ```
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<Boolean<E>>,
59    /// The internal BHP hasher used to process one iteration.
60    hasher: BHPHasher<E, NUM_WINDOWS, WINDOW_SIZE>,
61}
62
63#[cfg(feature = "console")]
64impl<E: Environment, const NUM_WINDOWS: u8, const WINDOW_SIZE: u8> Inject for BHP<E, NUM_WINDOWS, WINDOW_SIZE> {
65    type Primitive = console::BHP<E::Network, NUM_WINDOWS, WINDOW_SIZE>;
66
67    /// Initializes a new instance of a BHP circuit with the given BHP variant.
68    fn new(_mode: Mode, bhp: Self::Primitive) -> Self {
69        // Ensure the given domain is within the allowed size in bits.
70        let num_bits = bhp.domain().len();
71        let max_bits = E::BaseField::size_in_data_bits() - 64; // 64 bits encode the length.
72        if num_bits > max_bits {
73            E::halt(format!("Domain cannot exceed {max_bits} bits, found {num_bits} bits"))
74        } else if num_bits != max_bits {
75            E::halt(format!("Domain was not padded to {max_bits} bits, found {num_bits} bits"))
76        }
77
78        // Initialize the domain.
79        let domain = Vec::constant(bhp.domain().to_vec());
80
81        // Initialize the BHP hasher.
82        let hasher = BHPHasher::<E, NUM_WINDOWS, WINDOW_SIZE>::constant(bhp);
83
84        Self { domain, hasher }
85    }
86}
87
88#[cfg(all(test, feature = "console"))]
89mod tests {
90    use super::*;
91    use snarkvm_circuit_types::environment::{Circuit, Eject};
92
93    use anyhow::Result;
94
95    const ITERATIONS: usize = 10;
96    const MESSAGE: &str = "BHPCircuit0";
97
98    #[test]
99    fn test_setup_constant() -> Result<()> {
100        for _ in 0..ITERATIONS {
101            let native = console::BHP::<<Circuit as Environment>::Network, 8, 32>::setup(MESSAGE)?;
102            let circuit = BHP::<Circuit, 8, 32>::new(Mode::Constant, native.clone());
103
104            native.bases().iter().zip(circuit.hasher.bases().iter()).for_each(|(native_bases, circuit_bases)| {
105                native_bases.iter().zip(circuit_bases).for_each(|(native_base, circuit_base_lookups)| {
106                    // Check the first circuit base (when converted back to twisted Edwards) matches the native one.
107                    let (circuit_x, circuit_y) = {
108                        let (x_bases, y_bases) = circuit_base_lookups;
109                        // Convert the Montgomery point to a twisted Edwards point.
110                        let edwards_x = &x_bases[0] / &y_bases[0]; // 1 constraint
111                        let edwards_y = (&x_bases[0] - Field::one()) / (&x_bases[0] + Field::one());
112                        (edwards_x, edwards_y)
113                    };
114                    assert_eq!(native_base.to_x_coordinate(), circuit_x.eject_value());
115                    assert_eq!(native_base.to_y_coordinate(), circuit_y.eject_value());
116                })
117            });
118        }
119        Ok(())
120    }
121}