snarkvm_circuit_program/data/identifier/
from_bits.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
16use super::*;
17
18impl<A: Aleo> FromBits for Identifier<A> {
19    type Boolean = Boolean<A>;
20
21    /// Initializes a new identifier from a list of little-endian bits.
22    fn from_bits_le(bits_le: &[Self::Boolean]) -> Self {
23        // Ensure the number of bits does not exceed the size in bits of the field.
24        // This check is not sufficient to ensure the identifier is of valid size,
25        // the final step checks the byte-aligned field element is within the data capacity.
26        debug_assert!(bits_le.len() <= A::BaseField::size_in_bits(), "Identifier exceeds the maximum bits allowed");
27
28        // Recover the field element from the bits.
29        let field = Field::from_bits_le(bits_le);
30
31        // Eject the bits in **little-endian** form, and determine the number of bytes.
32        let num_bytes = match console::Identifier::<A::Network>::from_bits_le(&bits_le.eject_value()) {
33            Ok(console_identifier) => console_identifier.size_in_bits() / 8,
34            Err(error) => A::halt(format!("Failed to recover an identifier from bits: {error}")),
35        };
36
37        // Ensure identifier fits within the data capacity of the base field.
38        let max_bytes = A::BaseField::size_in_data_bits() / 8; // Note: This intentionally rounds down.
39        match num_bytes as usize <= max_bytes {
40            // Return the identifier.
41            true => Self(field, num_bytes),
42            false => A::halt("Identifier exceeds the maximum capacity allowed"),
43        }
44    }
45
46    /// Initializes a new identifier from a list of big-endian bits.
47    fn from_bits_be(bits_be: &[Self::Boolean]) -> Self {
48        Self::from_bits_le(bits_be.iter().rev().cloned().collect::<Vec<_>>().as_slice())
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use crate::{Circuit, data::identifier::tests::sample_console_identifier};
56
57    use anyhow::Result;
58
59    const ITERATIONS: u64 = 100;
60
61    fn check_from_bits_le(num_constants: u64, num_public: u64, num_private: u64, num_constraints: u64) -> Result<()> {
62        for _ in 0..ITERATIONS {
63            // Initialize the console identifier.
64            let console_identifier = sample_console_identifier::<Circuit>()?;
65            // Initialize the circuit list of bits.
66            let circuit_bits: Vec<_> = Inject::constant(console_identifier.to_bits_le());
67
68            Circuit::scope("Identifier FromBits", || {
69                let candidate = Identifier::<Circuit>::from_bits_le(&circuit_bits);
70                assert_eq!(Mode::Constant, candidate.eject_mode());
71                assert_eq!(console_identifier, candidate.eject_value());
72                assert_scope!(num_constants, num_public, num_private, num_constraints);
73            });
74            Circuit::reset();
75        }
76        Ok(())
77    }
78
79    fn check_from_bits_be(num_constants: u64, num_public: u64, num_private: u64, num_constraints: u64) -> Result<()> {
80        for _ in 0..ITERATIONS {
81            // Initialize the console identifier.
82            let console_identifier = sample_console_identifier::<Circuit>()?;
83            // Initialize the circuit list of bits.
84            let circuit_bits: Vec<_> = Inject::constant(console_identifier.to_bits_be());
85
86            Circuit::scope("Identifier FromBits", || {
87                let candidate = Identifier::<Circuit>::from_bits_be(&circuit_bits);
88                assert_eq!(Mode::Constant, candidate.eject_mode());
89                assert_eq!(console_identifier, candidate.eject_value());
90                assert_scope!(num_constants, num_public, num_private, num_constraints);
91            });
92            Circuit::reset();
93        }
94        Ok(())
95    }
96
97    #[test]
98    fn test_from_bits_le() -> Result<()> {
99        check_from_bits_le(0, 0, 0, 0)
100    }
101
102    #[test]
103    fn test_from_bits_be() -> Result<()> {
104        check_from_bits_be(0, 0, 0, 0)
105    }
106}