snarkvm_circuit_program/id/
to_address.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> ProgramID<A> {
19    /// Returns the program address for this program ID.
20    pub fn to_address(&self) -> Address<A> {
21        // Compute the program address as `HashToGroup(program_id)`.
22        let group = A::hash_to_group_psd4(&[self.name().to_field(), self.network().to_field()]);
23        // Return the program address.
24        Address::from_group(group)
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use crate::{Circuit, data::identifier::tests::sample_lowercase_console_identifier_as_string};
32
33    use anyhow::Result;
34
35    const ITERATIONS: usize = 100;
36
37    fn check_to_address(
38        mode: Mode,
39        num_constants: u64,
40        num_public: u64,
41        num_private: u64,
42        num_constraints: u64,
43    ) -> Result<()> {
44        for i in 0..ITERATIONS {
45            // Sample a random fixed-length alphanumeric string, that always starts with an alphabetic character.
46            let expected_name_string = sample_lowercase_console_identifier_as_string::<Circuit>()?;
47            let expected_program_id = console::ProgramID::<<Circuit as Environment>::Network>::from_str(&format!(
48                "{expected_name_string}.aleo"
49            ))?;
50            let expected = expected_program_id.to_address()?;
51
52            let program_id = ProgramID::<Circuit>::new(mode, expected_program_id);
53
54            Circuit::scope(format!("{mode}"), || {
55                let candidate = program_id.to_address();
56                assert_eq!(expected, candidate.eject_value());
57                if i > 0 {
58                    assert_scope!(num_constants, num_public, num_private, num_constraints);
59                }
60            });
61            Circuit::reset();
62        }
63        Ok(())
64    }
65
66    #[test]
67    fn test_to_address_constant() -> Result<()> {
68        check_to_address(Mode::Constant, 1059, 0, 0, 0)
69    }
70
71    #[test]
72    fn test_to_address_public() -> Result<()> {
73        check_to_address(Mode::Public, 1059, 0, 0, 0)
74    }
75
76    #[test]
77    fn test_to_address_private() -> Result<()> {
78        check_to_address(Mode::Private, 1059, 0, 0, 0)
79    }
80}