leo_package/lib.rs
1// Copyright (C) 2019-2026 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
17//! This crate deals with Leo packages on the file system and network.
18//!
19//! The main type is `Package`, which deals with Leo packages on the local filesystem.
20//! A Leo package directory is intended to have a structure like this:
21//! .
22//! ├── program.json
23//! ├── build
24//! │ ├── imports
25//! │ │ └── credits.aleo
26//! │ └── main.aleo
27//! ├── outputs
28//! │ ├── program.TypeChecking.ast
29//! │ └── program.TypeChecking.json
30//! ├── src
31//! │ └── main.leo
32//! └── tests
33//! └── test_something.leo
34//!
35//! The file `program.json` is a manifest containing the program name, version, description,
36//! and license, together with information about its dependencies.
37//!
38//! Such a directory structure, together with a `.gitignore` file, may be created
39//! on the file system using `Package::initialize`.
40//! ```no_run
41//! # use leo_ast::NetworkName;
42//! # use leo_package::{Package};
43//! let path = Package::initialize("my_package", "path/to/parent").unwrap();
44//! ```
45//!
46//! `tests` is where unit test files may be placed.
47//!
48//! Given an existing directory with such a structure, a `Package` may be created from it with
49//! `Package::from_directory`:
50//! ```no_run
51//! # use leo_ast::NetworkName;
52//! use leo_package::Package;
53//! let package = Package::from_directory("path/to/package", "/home/me/.aleo", false, false, Some(NetworkName::TestnetV0), Some("http://localhost:3030")).unwrap();
54//! ```
55//! This will read the manifest and keep their data in `package.manifest`.
56//! It will also process dependencies and store them in topological order in `package.programs`. This processing
57//! will involve fetching bytecode from the network for network dependencies.
58//! If the `no_cache` option (3rd parameter) is set to `true`, the package will not use the dependency cache.
59//! The endpoint and network are optional and are only needed if the package has network dependencies.
60//!
61//! If you want to simply read the manifest file without processing dependencies, use
62//! `Package::from_directory_no_graph`.
63//!
64//! `Program` generally doesn't need to be created directly, as `Package` will create `Program`s
65//! for the main program and all dependencies. However, if you'd like to fetch bytecode for
66//! a program, you can use `Program::fetch`.
67
68#![forbid(unsafe_code)]
69
70use leo_ast::NetworkName;
71use leo_errors::{PackageError, Result, UtilError};
72use leo_span::Symbol;
73
74use std::path::Path;
75
76mod dependency;
77pub use dependency::*;
78
79mod location;
80pub use location::*;
81
82mod manifest;
83pub use manifest::*;
84
85mod package;
86pub use package::*;
87
88mod program;
89pub use program::*;
90
91pub const SOURCE_DIRECTORY: &str = "src";
92
93pub const MAIN_FILENAME: &str = "main.leo";
94
95pub const IMPORTS_DIRECTORY: &str = "build/imports";
96
97pub const OUTPUTS_DIRECTORY: &str = "outputs";
98
99pub const BUILD_DIRECTORY: &str = "build";
100
101pub const ABI_FILENAME: &str = "abi.json";
102
103pub const TESTS_DIRECTORY: &str = "tests";
104
105/// Maximum allowed program size in bytes.
106pub const MAX_PROGRAM_SIZE: usize = <snarkvm::prelude::TestnetV0 as snarkvm::prelude::Network>::MAX_PROGRAM_SIZE;
107
108/// The edition of a deployed program on the Aleo network.
109/// Edition 0 is the initial deployment, and increments with each upgrade.
110pub type Edition = u16;
111
112fn symbol(name: &str) -> Result<Symbol> {
113 name.strip_suffix(".aleo").map(Symbol::intern).ok_or_else(|| PackageError::invalid_network_name(name).into())
114}
115
116/// Is this a valid name for an Aleo program?
117///
118/// Namely, it must be of the format "xxx.aleo" where `xxx` is nonempty,
119/// consist solely of ASCII alphanumeric characters and underscore, and
120/// begin with a letter.
121pub fn is_valid_aleo_name(name: &str) -> bool {
122 let Some(rest) = name.strip_suffix(".aleo") else {
123 return false;
124 };
125
126 // Check that the name is nonempty.
127 if rest.is_empty() {
128 tracing::error!("Aleo names must be nonempty");
129 return false;
130 }
131
132 let first = rest.chars().next().unwrap();
133
134 // Check that the first character is not an underscore.
135 if first == '_' {
136 tracing::error!("Aleo names cannot begin with an underscore");
137 return false;
138 }
139
140 // Check that the first character is not a number.
141 if first.is_numeric() {
142 tracing::error!("Aleo names cannot begin with a number");
143 return false;
144 }
145
146 // Iterate and check that the name is valid.
147 if rest.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_') {
148 tracing::error!("Aleo names must can only contain ASCII alphanumeric characters and underscores.");
149 return false;
150 }
151
152 // Check that the name is not a SnarkVM reserved keyword
153 if reserved_keywords().any(|kw| kw == rest) {
154 tracing::error!(
155 "Aleo names cannot be a SnarkVM reserved keyword. Reserved keywords are: {}.",
156 reserved_keywords().collect::<Vec<_>>().join(", ")
157 );
158 return false;
159 }
160
161 // Check that the name does not contain `aleo`
162 if rest.contains("aleo") {
163 tracing::error!("Aleo names cannot contain the keyword `aleo`.",);
164 return false;
165 }
166
167 true
168}
169
170/// Get the list of all reserved and restricted keywords from snarkVM.
171/// These keywords cannot be used as program names.
172/// See: https://github.com/ProvableHQ/snarkVM/blob/046a2964f75576b2c4afbab9aa9eabc43ceb6dc3/synthesizer/program/src/lib.rs#L192
173pub fn reserved_keywords() -> impl Iterator<Item = &'static str> {
174 use snarkvm::prelude::{Program, TestnetV0};
175
176 // Flatten RESTRICTED_KEYWORDS by ignoring ConsensusVersion
177 let restricted = Program::<TestnetV0>::RESTRICTED_KEYWORDS.iter().flat_map(|(_, kws)| kws.iter().copied());
178
179 Program::<TestnetV0>::KEYWORDS.iter().copied().chain(restricted)
180}
181
182/// Creates a configured ureq agent for Leo network requests.
183///
184/// Disables `http_status_as_error` so 4xx/5xx responses return `Ok(Response)`
185/// instead of `Err(StatusCode)`. This preserves response bodies which often
186/// contain useful error details from the server.
187pub fn create_http_agent() -> ureq::Agent {
188 ureq::Agent::config_builder().max_redirects(0).http_status_as_error(false).build().new_agent()
189}
190
191// Fetch the given endpoint url and return the sanitized response.
192pub fn fetch_from_network(url: &str) -> Result<String, UtilError> {
193 fetch_from_network_plain(url).map(|s| s.replace("\\n", "\n").replace('\"', ""))
194}
195
196pub fn fetch_from_network_plain(url: &str) -> Result<String, UtilError> {
197 let mut response = create_http_agent()
198 .get(url)
199 .header("X-Leo-Version", env!("CARGO_PKG_VERSION"))
200 .call()
201 .map_err(|e| UtilError::failed_to_retrieve_from_endpoint(url, e))?;
202 match response.status().as_u16() {
203 200..=299 => Ok(response.body_mut().read_to_string().unwrap()),
204 301 => Err(UtilError::endpoint_moved_error(url)),
205 _ => Err(UtilError::network_error(url, response.status())),
206 }
207}
208
209/// Fetch the given program from the network and return the program as a string.
210// TODO (@d0cd) Unify with `leo_package::Program::fetch`.
211pub fn fetch_program_from_network(name: &str, endpoint: &str, network: NetworkName) -> Result<String, UtilError> {
212 let url = format!("{endpoint}/{network}/program/{name}");
213 let program = fetch_from_network(&url)?;
214 Ok(program)
215}
216
217/// Fetch the latest edition of a program from the network.
218///
219/// Returns the actual latest edition number for the given program.
220/// This should be used instead of defaulting to arbitrary edition numbers.
221pub fn fetch_latest_edition(name: &str, endpoint: &str, network: NetworkName) -> Result<Edition, UtilError> {
222 // Strip the .aleo suffix if present for the URL.
223 let name_without_suffix = name.strip_suffix(".aleo").unwrap_or(name);
224
225 let url = format!("{endpoint}/{network}/program/{name_without_suffix}.aleo/latest_edition");
226 let contents = fetch_from_network(&url)?;
227 contents
228 .parse::<u16>()
229 .map_err(|e| UtilError::failed_to_retrieve_from_endpoint(url, format!("Failed to parse edition as u16: {e}")))
230}
231
232// Verify that a fetched program is valid aleo instructions.
233pub fn verify_valid_program(name: &str, program: &str) -> Result<(), UtilError> {
234 use snarkvm::prelude::{Program, TestnetV0};
235 use std::str::FromStr as _;
236
237 // Check if the program size exceeds the maximum allowed limit.
238 let program_size = program.len();
239
240 if program_size > MAX_PROGRAM_SIZE {
241 return Err(UtilError::program_size_limit_exceeded(name, program_size, MAX_PROGRAM_SIZE));
242 }
243
244 // Parse the program to verify it's valid Aleo instructions.
245 match Program::<TestnetV0>::from_str(program) {
246 Ok(_) => Ok(()),
247 Err(_) => Err(UtilError::snarkvm_parsing_error(name)),
248 }
249}
250
251pub fn filename_no_leo_extension(path: &Path) -> Option<&str> {
252 filename_no_extension(path, ".leo")
253}
254
255pub fn filename_no_aleo_extension(path: &Path) -> Option<&str> {
256 filename_no_extension(path, ".aleo")
257}
258
259fn filename_no_extension<'a>(path: &'a Path, extension: &'static str) -> Option<&'a str> {
260 path.file_name().and_then(|os_str| os_str.to_str()).and_then(|s| s.strip_suffix(extension))
261}