leo_package/
program.rs

1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use crate::*;
18
19use leo_errors::{PackageError, Result, UtilError};
20use leo_span::Symbol;
21
22use snarkvm::prelude::{Program as SvmProgram, TestnetV0};
23
24use indexmap::IndexSet;
25use std::path::Path;
26
27/// Information about an Aleo program.
28#[derive(Clone, Debug)]
29pub struct Program {
30    // The name of the program (no ".aleo" suffix).
31    pub name: Symbol,
32    pub data: ProgramData,
33    pub dependencies: IndexSet<Dependency>,
34    pub is_test: bool,
35}
36
37impl Program {
38    /// Given the location `path` of a local Leo package, read the filesystem
39    /// to obtain a `Program`.
40    pub fn from_path<P: AsRef<Path>>(name: Symbol, path: P) -> Result<Self> {
41        Self::from_path_impl(name, path.as_ref())
42    }
43
44    fn from_path_impl(name: Symbol, path: &Path) -> Result<Self> {
45        let manifest = Manifest::read_from_file(path.join(MANIFEST_FILENAME))?;
46        let manifest_symbol = crate::symbol(&manifest.program)?;
47        if name != manifest_symbol {
48            return Err(PackageError::conflicting_manifest(
49                format_args!("{name}.aleo"),
50                format_args!("{manifest_symbol}.aleo"),
51            )
52            .into());
53        }
54        let source_directory = path.join(SOURCE_DIRECTORY);
55        let count = source_directory
56            .read_dir()
57            .map_err(|e| {
58                UtilError::util_file_io_error(
59                    format_args!("Failed to read directory {}", source_directory.display()),
60                    e,
61                )
62            })?
63            .count();
64
65        let source_path = source_directory.join(MAIN_FILENAME);
66
67        if !source_path.exists() || count != 1 {
68            return Err(PackageError::source_directory_can_contain_only_one_file(source_directory.display()).into());
69        }
70
71        Ok(Program {
72            name,
73            data: ProgramData::SourcePath(source_path),
74            dependencies: manifest
75                .dependencies
76                .unwrap_or_default()
77                .into_iter()
78                .map(|dependency| canonicalize_dependency_path_relative_to(path, dependency))
79                .collect::<Result<IndexSet<_>, _>>()?,
80            is_test: false,
81        })
82    }
83
84    /// Given the path to the source file of a test, create a `Program`.
85    ///
86    /// Unlike `Program::from_path`, the path is to the source file,
87    /// and the name of the program is determined from the filename.
88    ///
89    /// `main_program` must be provided since every test is dependent on it.
90    pub fn from_path_test<P: AsRef<Path>>(source_path: P, main_program: Dependency) -> Result<Self> {
91        Self::from_path_test_impl(source_path.as_ref(), main_program)
92    }
93
94    fn from_path_test_impl(source_path: &Path, main_program: Dependency) -> Result<Self> {
95        let name = filename_no_leo_extension(source_path)
96            .ok_or_else(|| PackageError::failed_path(source_path.display(), ""))?;
97        let package_directory = source_path.parent().and_then(|parent| parent.parent()).ok_or_else(|| {
98            UtilError::failed_to_open_file(format_args!("Failed to find package for test {}", source_path.display()))
99        })?;
100        let manifest = Manifest::read_from_file(package_directory.join(MANIFEST_FILENAME))?;
101        let mut dependencies = manifest
102            .dev_dependencies
103            .unwrap_or_default()
104            .into_iter()
105            .map(|dependency| canonicalize_dependency_path_relative_to(package_directory, dependency))
106            .collect::<Result<IndexSet<_>, _>>()?;
107        dependencies.insert(main_program);
108
109        Ok(Program {
110            name: Symbol::intern(name),
111            data: ProgramData::SourcePath(source_path.to_path_buf()),
112            dependencies,
113            is_test: true,
114        })
115    }
116
117    /// Given an Aleo program on a network, fetch it to build a `Program`.
118    pub fn fetch<P: AsRef<Path>>(
119        name: Symbol,
120        home_path: P,
121        network: NetworkName,
122        endpoint: &str,
123        no_cache: bool,
124    ) -> Result<Self> {
125        Self::fetch_impl(name, home_path.as_ref(), network, endpoint, no_cache)
126    }
127
128    fn fetch_impl(
129        name: Symbol,
130        home_path: &Path,
131        network: NetworkName,
132        endpoint: &str,
133        no_cache: bool,
134    ) -> Result<Self> {
135        // It's not a local program; let's check the cache.
136        let cache_directory = home_path.join(format!("registry/{network}"));
137        let full_cache_path = cache_directory.join(format!("{name}.aleo"));
138
139        // Get the existing bytecode if the file exists.
140        let existing_bytecode = match full_cache_path.exists() {
141            false => None,
142            true => {
143                // If the file exists, read it and compare it to the new contents.
144                let existing_contents = std::fs::read_to_string(&full_cache_path).map_err(|e| {
145                    UtilError::util_file_io_error(
146                        format_args!("Trying to read cached file at {}", full_cache_path.display()),
147                        e,
148                    )
149                })?;
150                Some(existing_contents)
151            }
152        };
153
154        let bytecode = match (existing_bytecode, no_cache) {
155            // If we are using the cache, we can just return the bytecode.
156            (Some(bytecode), false) => bytecode,
157            // Otherwise, we need to fetch it from the network.
158            (existing, _) => {
159                // We need to fetch it from the network.
160                let url = format!("{endpoint}/{network}/program/{name}.aleo");
161                let contents = fetch_from_network(&url)?;
162
163                // If the file already exists, compare it to the new contents.
164                if let Some(existing_contents) = existing {
165                    if existing_contents != contents {
166                        println!(
167                            "Warning: The cached file at `{}` is different from the one fetched from the network. The cached file will be overwritten.",
168                            full_cache_path.display()
169                        );
170                    }
171                }
172
173                // Write the bytecode to the cache.
174                std::fs::write(&full_cache_path, &contents).map_err(|err| {
175                    UtilError::util_file_io_error(
176                        format_args!("Could not open file `{}`", full_cache_path.display()),
177                        err,
178                    )
179                })?;
180
181                contents
182            }
183        };
184
185        // Parse the program so we can get its imports.
186        let svm_program: SvmProgram<TestnetV0> =
187            bytecode.parse().map_err(|_| UtilError::snarkvm_parsing_error(name))?;
188        let dependencies = svm_program
189            .imports()
190            .keys()
191            .map(|program_id| {
192                let name = program_id.to_string();
193                Dependency { name, location: Location::Network, path: None }
194            })
195            .collect();
196
197        Ok(Program { name, data: ProgramData::Bytecode(bytecode), dependencies, is_test: false })
198    }
199}
200
201/// If `dependency` has a relative path, assume it's relative to `base` and canonicalize it.
202///
203/// This needs to be done when collecting local dependencies from manifests which
204/// may be located at different places on the file system.
205fn canonicalize_dependency_path_relative_to(base: &Path, mut dependency: Dependency) -> Result<Dependency> {
206    if let Some(path) = &mut dependency.path {
207        if !path.is_absolute() {
208            let joined = base.join(&path);
209            *path = joined.canonicalize().map_err(|e| PackageError::failed_path(joined.display(), e))?;
210        }
211    }
212    Ok(dependency)
213}