Skip to main content

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//! │   ├── my_program
25//! │   │   ├── my_program.aleo
26//! │   │   └── abi.json
27//! │   └── credits
28//! │       └── credits.aleo
29//! ├── src
30//! │   └── main.leo
31//! └── tests
32//!     └── test_something.leo
33//!
34//! Inside `build`, every compilation unit - the package's own program or
35//! library, its local dependencies, and fetched network imports - gets its own
36//! `build/<name>/` directory with the same shape.
37//!
38//! For packages that live inside a workspace (a directory whose `workspace.json`
39//! is an ancestor), `build/` moves to the workspace root rather than the
40//! package's own directory. Every member's per-unit subdirectory is then keyed
41//! by unit name under `<workspace_root>/build/<name>/`, so a unit built once
42//! is reused across members instead of being rebuilt per member.
43//!
44//! The file `program.json` is a manifest containing the program name, version, description,
45//! and license, together with information about its dependencies.
46//!
47//! Such a directory structure, together with a `.gitignore` file, may be created
48//! on the file system using `Package::initialize`.
49//! ```no_run
50//! # use leo_ast::NetworkName;
51//! # use leo_package::{Package};
52//! let path = Package::initialize("my_package", "path/to/parent", false).unwrap();
53//! ```
54//!
55//! `tests` is where unit test files may be placed.
56//!
57//! Given an existing directory with such a structure, a `Package` may be created from it with
58//! `Package::from_directory`:
59//! ```no_run
60//! # use leo_ast::NetworkName;
61//! use leo_package::Package;
62//! let package = Package::from_directory("path/to/package", "/home/me/.aleo", false, false, false, Some(NetworkName::TestnetV0), Some("http://localhost:3030"), 3).unwrap();
63//! ```
64//! This will read the manifest and keep their data in `package.manifest`.
65//! It will also process dependencies and store them in topological order in `package.compilation_units`. This processing
66//! will involve fetching bytecode from the network for network dependencies.
67//! If the `no_cache` option (3rd parameter) is set to `true`, the package will not use the dependency cache.
68//! The endpoint and network are optional and are only needed if the package has network dependencies.
69//!
70//! If you want to simply read the manifest file without processing dependencies, use
71//! `Package::from_directory_no_graph`.
72//!
73//! `CompilationUnit` generally doesn't need to be created directly, as `Package` will create `CompilationUnit`s
74//! for the main program and all dependencies. However, if you'd like to fetch bytecode for
75//! a program, you can use `CompilationUnit::fetch`.
76
77#![forbid(unsafe_code)]
78
79mod errors;
80
81use leo_ast::NetworkName;
82use leo_errors::{Backtraced, Result};
83use leo_span::Symbol;
84
85use std::path::Path;
86
87mod dependency;
88pub use dependency::*;
89
90mod location;
91pub use location::*;
92
93mod manifest;
94pub use manifest::*;
95
96mod package;
97pub use package::*;
98
99mod compilation_unit;
100pub use compilation_unit::*;
101
102pub mod git;
103
104mod lock;
105pub use lock::*;
106
107mod workspace;
108pub use workspace::*;
109
110#[cfg(test)]
111mod test_util;
112
113#[cfg(test)]
114mod tests;
115
116pub const SOURCE_DIRECTORY: &str = "src";
117
118pub const MAIN_FILENAME: &str = "main.leo";
119
120pub const LIB_FILENAME: &str = "lib.leo";
121
122pub const BUILD_DIRECTORY: &str = "build";
123
124pub const ABI_FILENAME: &str = "abi.json";
125
126/// Name of the per-unit subdirectory holding interface ABI JSON files.
127pub const INTERFACES_DIRNAME: &str = "interfaces";
128
129pub const TESTS_DIRECTORY: &str = "tests";
130
131/// Maximum allowed program size in bytes.
132pub const MAX_PROGRAM_SIZE: usize =
133    <snarkvm::prelude::TestnetV0 as snarkvm::prelude::Network>::MAX_PROGRAM_SIZE.last().unwrap().1;
134
135/// The edition of a deployed program on the Aleo network.
136/// Edition 0 is the initial deployment, and increments with each upgrade.
137pub type Edition = u16;
138
139/// Strips a trailing `.aleo` (the Aleo program-ID suffix) from a compilation
140/// unit name, yielding the bare name.
141///
142/// `CompilationUnit` names are bare for local packages but `.aleo`-suffixed for
143/// network programs; build paths key on the bare name so the two are unified.
144pub fn bare_unit_name(name: &str) -> &str {
145    name.strip_suffix(".aleo").unwrap_or(name)
146}
147
148/// Canonicalizes a program name to its `.aleo`-suffixed form, appending the
149/// suffix only when it is absent. The inverse of [`bare_unit_name`].
150pub fn canonicalize_program_name(name: &str) -> String {
151    if name.ends_with(".aleo") { name.to_string() } else { format!("{name}.aleo") }
152}
153
154/// Converts a valid program or library name into a `Symbol`.
155///
156/// Names must either end with `.aleo` or contain no periods; otherwise an error is returned.
157fn symbol(name: &str) -> Result<Symbol> {
158    if name.ends_with(".aleo") || !name.contains('.') {
159        Ok(Symbol::intern(name))
160    } else {
161        Err(crate::errors::invalid_network_name(name).into())
162    }
163}
164
165/// Checks whether a string is a valid Aleo program name.
166///
167/// A valid program name must end with `.aleo` and the base name (without the
168/// suffix) must satisfy Aleo package naming rules.
169pub fn is_valid_program_name(name: &str) -> bool {
170    let Some(rest) = name.strip_suffix(".aleo") else {
171        tracing::error!("Program names must end with `.aleo`.");
172        return false;
173    };
174
175    is_valid_package_name(rest)
176}
177
178/// Checks whether a string is a valid Aleo library name.
179///
180/// Library names must satisfy Aleo package naming rules but do not require
181/// a `.aleo` suffix.
182pub fn is_valid_library_name(name: &str) -> bool {
183    is_valid_package_name(name)
184}
185
186/// Checks whether a string satisfies general Aleo package naming rules.
187///
188/// Expects a bare name (no `.aleo` suffix; use [`bare_unit_name`] to strip one first). Names must
189/// be nonempty, start with a letter, contain only ASCII alphanumeric characters or underscores,
190/// avoid reserved keywords, and not contain "aleo".
191pub fn is_valid_package_name(name: &str) -> bool {
192    // Check that the name is nonempty.
193    if name.is_empty() {
194        tracing::error!("Aleo names must be nonempty");
195        return false;
196    }
197
198    let first = name.chars().next().unwrap();
199
200    // Check that the first character is not an underscore.
201    if first == '_' {
202        tracing::error!("Aleo names cannot begin with an underscore");
203        return false;
204    }
205
206    // Check that the first character is not a number.
207    if first.is_numeric() {
208        tracing::error!("Aleo names cannot begin with a number");
209        return false;
210    }
211
212    // Check valid characters.
213    if name.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_') {
214        tracing::error!("Aleo names can only contain ASCII alphanumeric characters and underscores.");
215        return false;
216    }
217
218    if is_leo_keyword(name) {
219        tracing::error!("Aleo names cannot be a Leo keyword.");
220        return false;
221    }
222
223    if is_aleo_keyword(name) {
224        tracing::error!(
225            "Aleo names cannot be a SnarkVM reserved keyword. Reserved keywords are: {}.",
226            aleo_reserved_keywords().collect::<Vec<_>>().join(", ")
227        );
228        return false;
229    }
230
231    if name == "std" {
232        tracing::error!("`{name}` is reserved by Leo and cannot be used as a package, program, or library name.");
233        return false;
234    }
235
236    // Disallow "aleo"
237    if name.contains("aleo") {
238        tracing::error!("Aleo names cannot contain the keyword `aleo`.");
239        return false;
240    }
241
242    true
243}
244
245/// Get the list of all reserved and restricted keywords from snarkVM.
246/// These keywords cannot be used as program names.
247/// See: https://github.com/ProvableHQ/snarkVM/blob/046a2964f75576b2c4afbab9aa9eabc43ceb6dc3/synthesizer/program/src/lib.rs#L192
248pub fn aleo_reserved_keywords() -> impl Iterator<Item = &'static str> {
249    use snarkvm::prelude::{Program, TestnetV0};
250
251    // Flatten RESTRICTED_KEYWORDS by ignoring ConsensusVersion
252    let restricted = Program::<TestnetV0>::RESTRICTED_KEYWORDS.iter().flat_map(|(_, kws)| kws.iter().copied());
253
254    Program::<TestnetV0>::KEYWORDS.iter().copied().chain(restricted)
255}
256
257fn is_leo_keyword(name: &str) -> bool {
258    leo_parser_rowan::is_keyword(name)
259}
260
261fn is_aleo_keyword(name: &str) -> bool {
262    aleo_reserved_keywords().any(|kw| kw == name)
263}
264
265/// Creates a configured ureq agent for Leo network requests.
266///
267/// Disables `http_status_as_error` so 4xx/5xx responses return `Ok(Response)`
268/// instead of `Err(StatusCode)`. This preserves response bodies which often
269/// contain useful error details from the server.
270pub fn create_http_agent() -> ureq::Agent {
271    ureq::Agent::config_builder().max_redirects(0).http_status_as_error(false).build().new_agent()
272}
273
274/// Retries a fallible network operation with exponential backoff.
275///
276/// Attempts the operation `retries + 1` times. Delays between attempts are
277/// 1 s, 2 s, 4 s, …, capped at 64 s. Returns the result of the last attempt.
278///
279/// Only use this for idempotent, read-only network calls (GET requests);
280/// never use it for state-mutating calls such as transaction broadcasts.
281pub fn retry_network_call<T, E: std::fmt::Display>(
282    network_retries: u32,
283    mut f: impl FnMut() -> std::result::Result<T, E>,
284) -> std::result::Result<T, E> {
285    let mut result = f();
286    for attempt in 1..=network_retries {
287        if result.is_ok() {
288            break;
289        }
290        let delay_secs = 2u64.pow(attempt - 1).min(64);
291        eprintln!("⚠️  Network request failed, retrying in {delay_secs}s (attempt {attempt}/{network_retries})...");
292        std::thread::sleep(std::time::Duration::from_secs(delay_secs));
293        result = f();
294    }
295    result
296}
297
298// Fetch the given endpoint url and return the sanitized response.
299pub fn fetch_from_network(url: &str, network_retries: u32) -> Result<String, Backtraced> {
300    fetch_from_network_plain(url, network_retries).map(|s| s.replace("\\n", "\n").replace('\"', ""))
301}
302
303pub fn fetch_from_network_plain(url: &str, network_retries: u32) -> Result<String, Backtraced> {
304    // Retry only on transport-level failures (connection errors, timeouts, etc.).
305    // HTTP 3xx/4xx/5xx responses are not retried since they reflect persistent conditions.
306    let agent = create_http_agent();
307    let mut response = retry_network_call(network_retries, || {
308        agent
309            .get(url)
310            .header("X-Leo-Version", env!("CARGO_PKG_VERSION"))
311            .call()
312            .map_err(|e| crate::errors::failed_to_retrieve_from_endpoint(url, e))
313    })?;
314    match response.status().as_u16() {
315        200..=299 => Ok(response.body_mut().read_to_string().unwrap()),
316        301 => Err(crate::errors::endpoint_moved_error(url)),
317        _ => Err(crate::errors::network_error(url, response.status())),
318    }
319}
320
321/// Fetch the given program from the network and return the program as a string.
322// TODO (@d0cd) Unify with `leo_package::CompilationUnit::fetch`.
323pub fn fetch_program_from_network(
324    name: &str,
325    endpoint: &str,
326    network: NetworkName,
327    network_retries: u32,
328) -> Result<String, Backtraced> {
329    let url = format!("{endpoint}/{network}/program/{name}");
330    let program = fetch_from_network(&url, network_retries)?;
331    Ok(program)
332}
333
334/// Fetch the latest edition of a program from the network.
335///
336/// Returns the actual latest edition number for the given program.
337/// This should be used instead of defaulting to arbitrary edition numbers.
338pub fn fetch_latest_edition(
339    name: &str,
340    endpoint: &str,
341    network: NetworkName,
342    network_retries: u32,
343) -> Result<Edition, Backtraced> {
344    // Strip the .aleo suffix if present for the URL.
345    let name_without_suffix = name.strip_suffix(".aleo").unwrap_or(name);
346
347    let url = format!("{endpoint}/{network}/program/{name_without_suffix}.aleo/latest_edition");
348    let contents = fetch_from_network(&url, network_retries)?;
349    contents.parse::<u16>().map_err(|e| {
350        crate::errors::failed_to_retrieve_from_endpoint(url, format!("Failed to parse edition as u16: {e}"))
351    })
352}
353
354// Verify that a fetched program is valid aleo instructions.
355pub fn verify_valid_program(name: &str, program: &str) -> Result<(), Backtraced> {
356    use snarkvm::prelude::{Program, TestnetV0};
357    use std::str::FromStr as _;
358
359    // Check if the program size exceeds the maximum allowed limit.
360    let program_size = program.len();
361
362    if program_size > MAX_PROGRAM_SIZE {
363        return Err(crate::errors::program_size_limit_exceeded(name, program_size, MAX_PROGRAM_SIZE));
364    }
365
366    // Parse the program to verify it's valid Aleo instructions.
367    match Program::<TestnetV0>::from_str(program) {
368        Ok(_) => Ok(()),
369        Err(_) => Err(crate::errors::snarkvm_parsing_error(name)),
370    }
371}
372
373pub fn filename_no_leo_extension(path: &Path) -> Option<&str> {
374    filename_no_extension(path, ".leo")
375}
376
377pub fn filename_no_aleo_extension(path: &Path) -> Option<&str> {
378    filename_no_extension(path, ".aleo")
379}
380
381fn filename_no_extension<'a>(path: &'a Path, extension: &'static str) -> Option<&'a str> {
382    path.file_name().and_then(|os_str| os_str.to_str()).and_then(|s| s.strip_suffix(extension))
383}
384
385#[cfg(test)]
386mod package_tests {
387    use super::{Package, is_valid_library_name, is_valid_program_name};
388
389    #[test]
390    fn package_names_reject_leo_keywords() {
391        assert!(!is_valid_program_name("in.aleo"));
392        assert!(!is_valid_library_name("in"));
393    }
394
395    #[test]
396    fn package_names_accept_keyword_prefixes() {
397        assert!(is_valid_program_name("inside.aleo"));
398        assert!(is_valid_library_name("inside"));
399    }
400
401    #[test]
402    fn package_initialize_rejects_leo_keyword_program_names() {
403        let dir = std::env::temp_dir().join(format!("leo_keyword_program_name_{}", std::process::id()));
404        let _ = std::fs::remove_dir_all(&dir);
405        std::fs::create_dir_all(&dir).unwrap();
406
407        assert!(Package::initialize("in", &dir, false).is_err());
408
409        std::fs::remove_dir_all(&dir).unwrap();
410    }
411}