From b35375908b6e94804e03d4e46dd7c213d7bf682f Mon Sep 17 00:00:00 2001 From: gluaxspeed Date: Wed, 4 Aug 2021 15:22:40 -0700 Subject: [PATCH] state errors migrated --- Cargo.lock | 1 + compiler/src/constraints/constraints.rs | 2 +- compiler/src/output/output_file.rs | 6 +-- errors/src/common/backtraced.rs | 8 ++-- errors/src/common/formatted.rs | 2 - errors/src/state/state_errors.rs | 47 +++++++++++++++++++ leo/api.rs | 6 +-- leo/commands/init.rs | 2 +- leo/commands/new.rs | 2 +- leo/commands/package/add.rs | 18 +++---- leo/commands/package/clone.rs | 16 +++---- leo/commands/package/login.rs | 2 +- leo/commands/prove.rs | 4 +- leo/commands/setup.rs | 12 ++--- leo/commands/update.rs | 2 +- leo/commands/watch.rs | 2 +- leo/config.rs | 42 ++++++++--------- leo/context.rs | 2 +- leo/main.rs | 1 - leo/updater.rs | 16 +++---- package/src/imports/directory.rs | 4 +- package/src/inputs/directory.rs | 8 ++-- package/src/inputs/input.rs | 4 +- package/src/inputs/state.rs | 4 +- package/src/outputs/checksum.rs | 4 +- package/src/outputs/circuit.rs | 4 +- package/src/outputs/directory.rs | 4 +- package/src/outputs/proof.rs | 5 +- package/src/outputs/proving_key.rs | 4 +- package/src/outputs/verification_key.rs | 4 +- package/src/root/gitignore.rs | 4 +- package/src/root/manifest.rs | 2 +- package/src/root/readme.rs | 4 +- package/src/root/zip.rs | 14 +++--- package/src/source/directory.rs | 6 +-- package/src/source/main.rs | 4 +- state/Cargo.toml | 12 +++-- state/src/errors/dpc_record_values.rs | 36 -------------- state/src/errors/input_value.rs | 32 ------------- state/src/errors/local_data_commitment.rs | 42 ----------------- state/src/errors/mod.rs | 33 ------------- state/src/errors/record_commitment.rs | 36 -------------- state/src/errors/state_leaf_values.rs | 31 ------------ state/src/errors/state_values.rs | 31 ------------ state/src/lib.rs | 6 --- .../local_data_commitment.rs | 37 ++++++++------- .../state_leaf_values.rs | 11 +++-- .../src/local_data_commitment/state_values.rs | 11 +++-- .../record_commitment/dpc_record_values.rs | 18 ++++--- .../record_commitment/record_commitment.rs | 24 +++++----- state/src/utilities/input_value.rs | 25 +++++----- 51 files changed, 232 insertions(+), 425 deletions(-) delete mode 100644 state/src/errors/dpc_record_values.rs delete mode 100644 state/src/errors/input_value.rs delete mode 100644 state/src/errors/local_data_commitment.rs delete mode 100644 state/src/errors/mod.rs delete mode 100644 state/src/errors/record_commitment.rs delete mode 100644 state/src/errors/state_leaf_values.rs delete mode 100644 state/src/errors/state_values.rs diff --git a/Cargo.lock b/Cargo.lock index 0df69a59ff..23d95d353f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1393,6 +1393,7 @@ version = "1.5.3" dependencies = [ "indexmap", "leo-ast", + "leo-errors", "leo-input", "rand 0.8.4", "rand_core 0.6.3", diff --git a/compiler/src/constraints/constraints.rs b/compiler/src/constraints/constraints.rs index b81ad10a69..8f740ae175 100644 --- a/compiler/src/constraints/constraints.rs +++ b/compiler/src/constraints/constraints.rs @@ -107,7 +107,7 @@ pub fn generate_test_constraints<'a, F: PrimeField, G: GroupType>( } } } - None => default.ok_or_else(|| CompilerError::no_test_input())?, + None => default.ok_or_else(CompilerError::no_test_input)?, }; // parse input files to abstract syntax trees diff --git a/compiler/src/output/output_file.rs b/compiler/src/output/output_file.rs index d0c3229bf4..771ce7d058 100644 --- a/compiler/src/output/output_file.rs +++ b/compiler/src/output/output_file.rs @@ -46,11 +46,9 @@ impl OutputFile { pub fn write(&self, path: &Path, bytes: &[u8]) -> Result<()> { // create output file let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| CompilerError::output_file_io_error(e))?; + let mut file = File::create(&path).map_err(CompilerError::output_file_io_error)?; - Ok(file - .write_all(bytes) - .map_err(|e| CompilerError::output_file_io_error(e))?) + Ok(file.write_all(bytes).map_err(CompilerError::output_file_io_error)?) } /// Removes the output file at the given path if it exists. Returns `true` on success, diff --git a/errors/src/common/backtraced.rs b/errors/src/common/backtraced.rs index f7ab92b1e9..ee4b7256cc 100644 --- a/errors/src/common/backtraced.rs +++ b/errors/src/common/backtraced.rs @@ -17,7 +17,7 @@ use std::fmt; use backtrace::Backtrace; -use color_backtrace::BacktracePrinter; +use color_backtrace::{BacktracePrinter, Verbosity}; use derivative::Derivative; pub const INDENT: &str = " "; @@ -103,20 +103,18 @@ impl fmt::Display for BacktracedError { "1" => { dbg!("1"); let mut printer = BacktracePrinter::default(); - printer = printer.verbosity(Verbosity::Medium); printer = printer.lib_verbosity(Verbosity::Medium); let trace = printer - .format_trace_to_string(&self.backtrace.backtrace) + .format_trace_to_string(&self.backtrace) .map_err(|_| fmt::Error)?; write!(f, "{}", trace)?; } "full" => { dbg!("full"); let mut printer = BacktracePrinter::default(); - printer = printer.verbosity(Verbosity::Full); printer = printer.lib_verbosity(Verbosity::Full); let trace = printer - .format_trace_to_string(&self.backtrace.backtrace) + .format_trace_to_string(&self.backtrace) .map_err(|_| fmt::Error)?; write!(f, "{}", trace)?; } diff --git a/errors/src/common/formatted.rs b/errors/src/common/formatted.rs index 252981e1ff..8cf78ced5b 100644 --- a/errors/src/common/formatted.rs +++ b/errors/src/common/formatted.rs @@ -142,7 +142,6 @@ impl fmt::Display for FormattedError { let leo_backtrace = std::env::var("LEO_BACKTRACE").unwrap_or_default().trim().to_owned(); match leo_backtrace.as_ref() { "1" => { - dbg!("1"); let mut printer = BacktracePrinter::default(); printer = printer.verbosity(Verbosity::Medium); printer = printer.lib_verbosity(Verbosity::Medium); @@ -152,7 +151,6 @@ impl fmt::Display for FormattedError { write!(f, "{}", trace)?; } "full" => { - dbg!("full"); let mut printer = BacktracePrinter::default(); printer = printer.verbosity(Verbosity::Full); printer = printer.lib_verbosity(Verbosity::Full); diff --git a/errors/src/state/state_errors.rs b/errors/src/state/state_errors.rs index d5695fb2cc..9b6c3f6697 100644 --- a/errors/src/state/state_errors.rs +++ b/errors/src/state/state_errors.rs @@ -16,8 +16,55 @@ use crate::create_errors; +use std::{ + error::Error as ErrorArg, + fmt::{Debug, Display}, +}; + create_errors!( StateError, exit_code_mask: 6000i32, error_code_prefix: "STA", + + @backtraced + parse_bool_error { + args: (error: impl ErrorArg), + msg: format!("failed to parse state file bool: {}", error), + help: None, + } + + @backtraced + parse_int_error { + args: (error: impl ErrorArg), + msg: format!("failed to parse state file int: {}", error), + help: None, + } + + @backtraced + expected_bytes { + args: (found: impl Display), + msg: format!("expected parameter array of u8 bytes, found `{}`", found), + help: None, + } + + @backtraced + expected_int { + args: (found: impl Display), + msg: format!("expected integer parameter, found `{}`", found), + help: None, + } + + @backtraced + mising_parameter { + args: (parameter: impl Display), + msg: format!("input parameter `{}` not found in state file", parameter), + help: None, + } + + @backtraced + state_io_error { + args: (error: impl ErrorArg), + msg: format!("io error found {}", error), + help: None, + } ); diff --git a/leo/api.rs b/leo/api.rs index d90d51427e..01e915c16b 100644 --- a/leo/api.rs +++ b/leo/api.rs @@ -249,10 +249,10 @@ impl Route for Publish { let status = res.status(); if status == StatusCode::OK { - let body: PublishResponse = res.json().map_err(|e| CliError::reqwest_json_error(e))?; + let body: PublishResponse = res.json().map_err(CliError::reqwest_json_error)?; Ok(body.package_id) } else { - let res: HashMap = res.json().map_err(|e| CliError::reqwest_json_error(e))?; + let res: HashMap = res.json().map_err(CliError::reqwest_json_error)?; Err(match status { StatusCode::BAD_REQUEST => CliError::bad_request(res.get("message").unwrap()).into(), StatusCode::UNAUTHORIZED => CliError::not_logged_in().into(), @@ -288,7 +288,7 @@ impl Route for Profile { // this may be extended for more precise error handling let status = res.status(); if status == StatusCode::OK { - let body: ProfileResponse = res.json().map_err(|e| CliError::reqwest_json_error(e))?; + let body: ProfileResponse = res.json().map_err(CliError::reqwest_json_error)?; return Ok(Some(body.username)); } diff --git a/leo/commands/init.rs b/leo/commands/init.rs index c82a4c9bd7..e513a31296 100644 --- a/leo/commands/init.rs +++ b/leo/commands/init.rs @@ -50,7 +50,7 @@ impl Command for Init { // Check that the given package name is valid. let package_name = path .file_stem() - .ok_or_else(|| CliError::invalid_project_name())? + .ok_or_else(CliError::invalid_project_name)? .to_string_lossy() .to_string(); if !LeoPackage::is_package_name_valid(&package_name) { diff --git a/leo/commands/new.rs b/leo/commands/new.rs index c08df08375..aa9e462cc1 100644 --- a/leo/commands/new.rs +++ b/leo/commands/new.rs @@ -61,7 +61,7 @@ impl Command for New { } // Create the package directory - fs::create_dir_all(&path).map_err(|err| CliError::package_could_not_create_directory(err))?; + fs::create_dir_all(&path).map_err(CliError::package_could_not_create_directory)?; LeoPackage::initialize(&package_name, &path, username)?; diff --git a/leo/commands/package/add.rs b/leo/commands/package/add.rs index 9cdef736b9..e5e7a4635b 100644 --- a/leo/commands/package/add.rs +++ b/leo/commands/package/add.rs @@ -92,7 +92,7 @@ impl Command for Add { let (author, package_name) = self .try_read_arguments() - .map_err(|e| CliError::cli_bytes_conversion_error(e))?; + .map_err(CliError::cli_bytes_conversion_error)?; // Attempt to fetch the package. let reader = { @@ -105,7 +105,7 @@ impl Command for Add { .api .run_route(fetch)? .bytes() - .map_err(|e| CliError::cli_bytes_conversion_error(e))?; + .map_err(CliError::cli_bytes_conversion_error)?; std::io::Cursor::new(bytes) }; @@ -115,13 +115,13 @@ impl Command for Add { ImportsDirectory::create(&path)?; path.push(IMPORTS_DIRECTORY_NAME); path.push(package_name); - create_dir_all(&path).map_err(|e| CliError::cli_io_error(e))?; + create_dir_all(&path).map_err(CliError::cli_io_error)?; }; // Proceed to unzip and parse the fetched bytes. - let mut zip_archive = zip::ZipArchive::new(reader).map_err(|e| CliError::cli_zip_error(e))?; + let mut zip_archive = zip::ZipArchive::new(reader).map_err(CliError::cli_zip_error)?; for i in 0..zip_archive.len() { - let file = zip_archive.by_index(i).map_err(|e| CliError::cli_zip_error(e))?; + let file = zip_archive.by_index(i).map_err(CliError::cli_zip_error)?; let file_name = file.name(); @@ -129,16 +129,16 @@ impl Command for Add { file_path.push(file_name); if file_name.ends_with('/') { - create_dir_all(file_path).map_err(|e| CliError::cli_io_error(e))?; + create_dir_all(file_path).map_err(CliError::cli_io_error)?; } else { if let Some(parent_directory) = path.parent() { - create_dir_all(parent_directory).map_err(|e| CliError::cli_io_error(e))?; + create_dir_all(parent_directory).map_err(CliError::cli_io_error)?; } - let mut created = File::create(file_path).map_err(|e| CliError::cli_io_error(e))?; + let mut created = File::create(file_path).map_err(CliError::cli_io_error)?; created .write_all(&file.bytes().map(|e| e.unwrap()).collect::>()) - .map_err(|e| CliError::cli_bytes_conversion_error(e))?; + .map_err(CliError::cli_bytes_conversion_error)?; } } diff --git a/leo/commands/package/clone.rs b/leo/commands/package/clone.rs index a6d71490eb..93e1b13db2 100644 --- a/leo/commands/package/clone.rs +++ b/leo/commands/package/clone.rs @@ -87,7 +87,7 @@ impl Clone { path.to_mut().push(directory_name); } - Ok(fs::create_dir_all(&path).map_err(|e| CliError::cli_io_error(e))?) + Ok(fs::create_dir_all(&path).map_err(CliError::cli_io_error)?) } } @@ -117,7 +117,7 @@ impl Command for Clone { .api .run_route(fetch)? .bytes() - .map_err(|e| CliError::cli_bytes_conversion_error(e))?; + .map_err(CliError::cli_bytes_conversion_error)?; std::io::Cursor::new(bytes) }; @@ -127,10 +127,10 @@ impl Command for Clone { Self::create_directory(&path, &package_name)?; // Proceed to unzip and parse the fetched bytes. - let mut zip_archive = zip::ZipArchive::new(reader).map_err(|e| CliError::cli_io_error(e))?; + let mut zip_archive = zip::ZipArchive::new(reader).map_err(CliError::cli_io_error)?; for i in 0..zip_archive.len() { - let file = zip_archive.by_index(i).map_err(|e| CliError::cli_zip_error(e))?; + let file = zip_archive.by_index(i).map_err(CliError::cli_zip_error)?; let file_name = file.name(); @@ -138,16 +138,16 @@ impl Command for Clone { file_path.push(file_name); if file_name.ends_with('/') { - fs::create_dir_all(file_path).map_err(|e| CliError::cli_io_error(e))?; + fs::create_dir_all(file_path).map_err(CliError::cli_io_error)?; } else { if let Some(parent_directory) = path.parent() { - fs::create_dir_all(parent_directory).map_err(|e| CliError::cli_io_error(e))?; + fs::create_dir_all(parent_directory).map_err(CliError::cli_io_error)?; } - let mut created = File::create(file_path).map_err(|e| CliError::cli_io_error(e))?; + let mut created = File::create(file_path).map_err(CliError::cli_io_error)?; created .write_all(&file.bytes().map(|e| e.unwrap()).collect::>()) - .map_err(|e| CliError::cli_bytes_conversion_error(e))?; + .map_err(CliError::cli_bytes_conversion_error)?; } } diff --git a/leo/commands/package/login.rs b/leo/commands/package/login.rs index 7c31fe4f74..652087e9e0 100644 --- a/leo/commands/package/login.rs +++ b/leo/commands/package/login.rs @@ -72,7 +72,7 @@ impl Command for Login { }; let res = api.run_route(login)?; - let mut res: HashMap = res.json().map_err(|e| CliError::reqwest_json_error(e))?; + let mut res: HashMap = res.json().map_err(CliError::reqwest_json_error)?; let tok_opt = res.remove("token"); if tok_opt.is_none() { diff --git a/leo/commands/prove.rs b/leo/commands/prove.rs index 86f85c1450..4447f1631a 100644 --- a/leo/commands/prove.rs +++ b/leo/commands/prove.rs @@ -72,9 +72,7 @@ impl Command for Prove { // Write the proof file to the output directory let mut proof = vec![]; - program_proof - .write_le(&mut proof) - .map_err(|e| CliError::cli_io_error(e))?; + program_proof.write_le(&mut proof).map_err(CliError::cli_io_error)?; ProofFile::new(&package_name).write_to(&path, &proof)?; Ok((program_proof, prepared_verifying_key)) diff --git a/leo/commands/setup.rs b/leo/commands/setup.rs index 5996bb1f3b..cc915730fa 100644 --- a/leo/commands/setup.rs +++ b/leo/commands/setup.rs @@ -89,7 +89,7 @@ impl Command for Setup { let mut proving_key_bytes = vec![]; proving_key .write_le(&mut proving_key_bytes) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; let _ = proving_key_file.write_to(&path, &proving_key_bytes)?; tracing::info!("Complete"); @@ -100,7 +100,7 @@ impl Command for Setup { proving_key .vk .write_le(&mut verification_key) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; let _ = verification_key_file.write_to(&path, &verification_key)?; tracing::info!("Complete"); @@ -116,16 +116,16 @@ impl Command for Setup { } let proving_key_bytes = ProvingKeyFile::new(&package_name).read_from(&path)?; let proving_key = ProvingKey::::read(proving_key_bytes.as_slice(), !self.skip_key_check) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; tracing::info!("Complete"); // Read the verification key file from the output directory tracing::info!("Loading verification key..."); let verifying_key_bytes = VerificationKeyFile::new(&package_name) .read_from(&path) - .map_err(|e| CliError::cli_io_error(e))?; - let verifying_key = VerifyingKey::::read(verifying_key_bytes.as_slice()) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; + let verifying_key = + VerifyingKey::::read(verifying_key_bytes.as_slice()).map_err(CliError::cli_io_error)?; // Derive the prepared verifying key file from the verifying key let prepared_verifying_key = PreparedVerifyingKey::::from(verifying_key); diff --git a/leo/commands/update.rs b/leo/commands/update.rs index f5a9a2991b..c434027778 100644 --- a/leo/commands/update.rs +++ b/leo/commands/update.rs @@ -61,7 +61,7 @@ impl Command for Update { fn apply(self, _: Context, _: Self::Input) -> Result { // If --list is passed, list all available versions and return. if self.list { - return Ok(Updater::show_available_releases().map_err(|e| CliError::could_not_fetch_versions(e))?); + return Ok(Updater::show_available_releases().map_err(CliError::could_not_fetch_versions)?); } // Handles enabling and disabling automatic updates in the config file. diff --git a/leo/commands/watch.rs b/leo/commands/watch.rs index 889ad6d1d0..7b612c9479 100644 --- a/leo/commands/watch.rs +++ b/leo/commands/watch.rs @@ -56,7 +56,7 @@ impl Command for Watch { watcher .watch(LEO_SOURCE_DIR, RecursiveMode::Recursive) - .map_err(|e| CliError::unable_to_watch(e))?; + .map_err(CliError::unable_to_watch)?; tracing::info!("Watching Leo source code"); diff --git a/leo/config.rs b/leo/config.rs index 940e4977ac..37aa5a3277 100644 --- a/leo/config.rs +++ b/leo/config.rs @@ -89,12 +89,12 @@ impl Config { if !Path::exists(&config_path) { // Create a new default `config.toml` file if it doesn't already exist - create_dir_all(&config_dir).map_err(|e| CliError::cli_io_error(e))?; + create_dir_all(&config_dir).map_err(CliError::cli_io_error)?; let default_config_string = - toml::to_string(&Config::default()).map_err(|e| CliError::failed_to_convert_to_toml(e))?; + toml::to_string(&Config::default()).map_err(CliError::failed_to_convert_to_toml)?; - fs::write(&config_path, default_config_string).map_err(|e| CliError::cli_io_error(e))?; + fs::write(&config_path, default_config_string).map_err(CliError::cli_io_error)?; } let toml_string = match fs::read_to_string(&config_path) { @@ -102,21 +102,21 @@ impl Config { // If the config is using an incorrect format, rewrite it. if toml::from_str::(&toml).is_err() { let default_config_string = - toml::to_string(&Config::default()).map_err(|e| CliError::failed_to_convert_to_toml(e))?; - fs::write(&config_path, default_config_string.clone()).map_err(|e| CliError::cli_io_error(e))?; + toml::to_string(&Config::default()).map_err(CliError::failed_to_convert_to_toml)?; + fs::write(&config_path, default_config_string.clone()).map_err(CliError::cli_io_error)?; toml = default_config_string; } toml } Err(_) => { - create_dir_all(&config_dir).map_err(|e| CliError::cli_io_error(e))?; - toml::to_string(&Config::default()).map_err(|e| CliError::failed_to_convert_to_toml(e))? + create_dir_all(&config_dir).map_err(CliError::cli_io_error)?; + toml::to_string(&Config::default()).map_err(CliError::failed_to_convert_to_toml)? } }; // Parse the contents into the `Config` struct - let config: Config = toml::from_str(&toml_string).map_err(|e| CliError::failed_to_convert_from_toml(e))?; + let config: Config = toml::from_str(&toml_string).map_err(CliError::failed_to_convert_from_toml)?; Ok(config) } @@ -132,9 +132,9 @@ impl Config { let config_path = LEO_CONFIG_PATH.clone(); fs::write( &config_path, - toml::to_string(&config).map_err(|e| CliError::failed_to_convert_to_toml(e))?, + toml::to_string(&config).map_err(CliError::failed_to_convert_to_toml)?, ) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; } Ok(()) @@ -146,37 +146,33 @@ pub fn write_token_and_username(token: &str, username: &str) -> Result<()> { // Create Leo config directory if it not exists if !Path::new(&config_dir).exists() { - create_dir_all(&config_dir).map_err(|e| CliError::cli_io_error(e))?; + create_dir_all(&config_dir).map_err(CliError::cli_io_error)?; } - let mut credentials = File::create(&LEO_CREDENTIALS_PATH.to_path_buf()).map_err(|e| CliError::cli_io_error(e))?; + let mut credentials = File::create(&LEO_CREDENTIALS_PATH.to_path_buf()).map_err(CliError::cli_io_error)?; credentials .write_all(token.as_bytes()) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; - let mut username_file = File::create(&LEO_USERNAME_PATH.to_path_buf()).map_err(|e| CliError::cli_io_error(e))?; + let mut username_file = File::create(&LEO_USERNAME_PATH.to_path_buf()).map_err(CliError::cli_io_error)?; username_file .write_all(username.as_bytes()) - .map_err(|e| CliError::cli_io_error(e))?; + .map_err(CliError::cli_io_error)?; Ok(()) } pub fn read_token() -> Result { - let mut credentials = File::open(&LEO_CREDENTIALS_PATH.to_path_buf()).map_err(|e| CliError::cli_io_error(e))?; + let mut credentials = File::open(&LEO_CREDENTIALS_PATH.to_path_buf()).map_err(CliError::cli_io_error)?; let mut buf = String::new(); - credentials - .read_to_string(&mut buf) - .map_err(|e| CliError::cli_io_error(e))?; + credentials.read_to_string(&mut buf).map_err(CliError::cli_io_error)?; Ok(buf) } pub fn read_username() -> Result { - let mut username = File::open(&LEO_USERNAME_PATH.to_path_buf()).map_err(|e| CliError::cli_io_error(e))?; + let mut username = File::open(&LEO_USERNAME_PATH.to_path_buf()).map_err(CliError::cli_io_error)?; let mut buf = String::new(); - username - .read_to_string(&mut buf) - .map_err(|e| CliError::cli_io_error(e))?; + username.read_to_string(&mut buf).map_err(CliError::cli_io_error)?; Ok(buf) } diff --git a/leo/context.rs b/leo/context.rs index 14fba3c141..d7c7beaeed 100644 --- a/leo/context.rs +++ b/leo/context.rs @@ -37,7 +37,7 @@ impl Context { pub fn dir(&self) -> Result { match &self.path { Some(path) => Ok(path.clone()), - None => Ok(current_dir().map_err(|e| CliError::cli_io_error(e))?), + None => Ok(current_dir().map_err(CliError::cli_io_error)?), } } diff --git a/leo/main.rs b/leo/main.rs index c0f8e02aed..979a8fd460 100644 --- a/leo/main.rs +++ b/leo/main.rs @@ -39,7 +39,6 @@ use commands::{ }; use leo_errors::Result; -use color_backtrace; use colored::Colorize; use std::{path::PathBuf, process::exit}; use structopt::{clap::AppSettings, StructOpt}; diff --git a/leo/updater.rs b/leo/updater.rs index ff90e12f8a..b54b3cdfc2 100644 --- a/leo/updater.rs +++ b/leo/updater.rs @@ -34,9 +34,9 @@ impl Updater { .repo_owner(Self::LEO_REPO_OWNER) .repo_name(Self::LEO_REPO_NAME) .build() - .map_err(|e| CliError::self_update_error(e))? + .map_err(CliError::self_update_error)? .fetch() - .map_err(|e| CliError::self_update_error(e))?; + .map_err(CliError::self_update_error)?; let mut output = "\nList of available versions\n".to_string(); for release in releases { @@ -60,9 +60,9 @@ impl Updater { .no_confirm(true) .show_output(show_output) .build() - .map_err(|e| CliError::self_update_error(e))? + .map_err(CliError::self_update_error)? .update() - .map_err(|e| CliError::self_update_error(e))?; + .map_err(CliError::self_update_error)?; Ok(status) } @@ -75,14 +75,12 @@ impl Updater { .bin_name(Self::LEO_BIN_NAME) .current_version(env!("CARGO_PKG_VERSION")) .build() - .map_err(|e| CliError::self_update_error(e))?; + .map_err(CliError::self_update_error)?; let current_version = updater.current_version(); - let latest_release = updater - .get_latest_release() - .map_err(|e| CliError::self_update_error(e))?; + let latest_release = updater.get_latest_release().map_err(CliError::self_update_error)?; - if bump_is_greater(¤t_version, &latest_release.version).map_err(|e| CliError::self_update_error(e))? { + if bump_is_greater(¤t_version, &latest_release.version).map_err(CliError::self_update_error)? { Ok(latest_release.version) } else { Err(CliError::old_release_version(current_version, latest_release.version).into()) diff --git a/package/src/imports/directory.rs b/package/src/imports/directory.rs index abf58e9cdf..beb1439b45 100644 --- a/package/src/imports/directory.rs +++ b/package/src/imports/directory.rs @@ -30,7 +30,7 @@ impl ImportsDirectory { path.to_mut().push(IMPORTS_DIRECTORY_NAME); } - fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_imports_directory(e))?; + fs::create_dir_all(&path).map_err(PackageError::failed_to_create_imports_directory)?; Ok(()) } @@ -47,7 +47,7 @@ impl ImportsDirectory { return Err(PackageError::import_does_not_exist(package_name).into()); } - fs::remove_dir_all(&path).map_err(|e| PackageError::failed_to_remove_imports_directory(e))?; + fs::remove_dir_all(&path).map_err(PackageError::failed_to_remove_imports_directory)?; Ok(()) } diff --git a/package/src/inputs/directory.rs b/package/src/inputs/directory.rs index 1b1e205bd5..92718b4f76 100644 --- a/package/src/inputs/directory.rs +++ b/package/src/inputs/directory.rs @@ -35,7 +35,7 @@ impl InputsDirectory { path.to_mut().push(INPUTS_DIRECTORY_NAME); } - fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_inputs_directory(e))?; + fs::create_dir_all(&path).map_err(PackageError::failed_to_create_inputs_directory)?; Ok(()) } @@ -44,7 +44,7 @@ impl InputsDirectory { let mut path = path.to_owned(); path.push(INPUTS_DIRECTORY_NAME); - let directory = fs::read_dir(&path).map_err(|e| PackageError::failed_to_read_inputs_directory(e))?; + let directory = fs::read_dir(&path).map_err(PackageError::failed_to_read_inputs_directory)?; let mut file_paths = Vec::new(); parse_file_paths(directory, &mut file_paths)?; @@ -54,7 +54,7 @@ impl InputsDirectory { fn parse_file_paths(directory: ReadDir, file_paths: &mut Vec) -> Result<()> { for file_entry in directory.into_iter() { - let file_entry = file_entry.map_err(|e| PackageError::failed_to_get_input_file_entry(e))?; + let file_entry = file_entry.map_err(PackageError::failed_to_get_input_file_entry)?; let file_path = file_entry.path(); // Verify that the entry is structured as a valid file or directory @@ -62,7 +62,7 @@ fn parse_file_paths(directory: ReadDir, file_paths: &mut Vec) -> Result .file_type() .map_err(|e| PackageError::failed_to_get_input_file_type(file_path.as_os_str().to_owned(), e))?; if file_type.is_dir() { - let directory = fs::read_dir(&file_path).map_err(|e| PackageError::failed_to_read_inputs_directory(e))?; + let directory = fs::read_dir(&file_path).map_err(PackageError::failed_to_read_inputs_directory)?; parse_file_paths(directory, file_paths)?; continue; diff --git a/package/src/inputs/input.rs b/package/src/inputs/input.rs index 531cf88975..1fd4c2c930 100644 --- a/package/src/inputs/input.rs +++ b/package/src/inputs/input.rs @@ -66,10 +66,10 @@ impl InputFile { /// Writes the standard input format to a file. pub fn write_to(self, path: &Path) -> Result<()> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_input_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_input_file)?; file.write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_input_file(e))?; + .map_err(PackageError::io_error_input_file)?; Ok(()) } diff --git a/package/src/inputs/state.rs b/package/src/inputs/state.rs index d07cf78da0..ba371b3c5f 100644 --- a/package/src/inputs/state.rs +++ b/package/src/inputs/state.rs @@ -65,11 +65,11 @@ impl StateFile { /// Writes the standard input format to a file. pub fn write_to(self, path: &Path) -> Result<()> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_state_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_state_file)?; Ok(file .write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_state_file(e))?) + .map_err(PackageError::io_error_state_file)?) } fn template(&self) -> String { diff --git a/package/src/outputs/checksum.rs b/package/src/outputs/checksum.rs index bd557b3f51..973fc75b8d 100644 --- a/package/src/outputs/checksum.rs +++ b/package/src/outputs/checksum.rs @@ -61,10 +61,10 @@ impl ChecksumFile { /// Writes the given checksum to a file. pub fn write_to(&self, path: &Path, checksum: String) -> Result<()> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_checksum_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_checksum_file)?; file.write_all(checksum.as_bytes()) - .map_err(|e| PackageError::io_error_checksum_file(e))?; + .map_err(PackageError::io_error_checksum_file)?; Ok(()) } diff --git a/package/src/outputs/circuit.rs b/package/src/outputs/circuit.rs index 9076668aa2..80cc657fba 100644 --- a/package/src/outputs/circuit.rs +++ b/package/src/outputs/circuit.rs @@ -61,10 +61,10 @@ impl CircuitFile { /// Writes the given serialized circuit to a file. pub fn write_to(&self, path: &Path, circuit: String) -> Result<()> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_circuit_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_circuit_file)?; file.write_all(circuit.as_bytes()) - .map_err(|e| PackageError::io_error_circuit_file(e))?; + .map_err(PackageError::io_error_circuit_file)?; Ok(()) } diff --git a/package/src/outputs/directory.rs b/package/src/outputs/directory.rs index ab72c99e92..e94dd40d2e 100644 --- a/package/src/outputs/directory.rs +++ b/package/src/outputs/directory.rs @@ -30,7 +30,7 @@ impl OutputsDirectory { path.to_mut().push(OUTPUTS_DIRECTORY_NAME); } - fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_inputs_directory(e))?; + fs::create_dir_all(&path).map_err(PackageError::failed_to_create_inputs_directory)?; Ok(()) } @@ -42,7 +42,7 @@ impl OutputsDirectory { } if path.exists() { - fs::remove_dir_all(&path).map_err(|e| PackageError::failed_to_create_inputs_directory(e))?; + fs::remove_dir_all(&path).map_err(PackageError::failed_to_create_inputs_directory)?; } Ok(()) diff --git a/package/src/outputs/proof.rs b/package/src/outputs/proof.rs index e2c0a08b7c..8ee058c754 100644 --- a/package/src/outputs/proof.rs +++ b/package/src/outputs/proof.rs @@ -61,10 +61,9 @@ impl ProofFile { /// Writes the given proof to a file. pub fn write_to(&self, path: &Path, proof: &[u8]) -> Result<()> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_proof_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_proof_file)?; - file.write_all(proof) - .map_err(|e| PackageError::io_error_proof_file(e))?; + file.write_all(proof).map_err(PackageError::io_error_proof_file)?; tracing::info!("Saving proof... ({:?})", path); Ok(()) diff --git a/package/src/outputs/proving_key.rs b/package/src/outputs/proving_key.rs index 64b920232e..f7fbda3261 100644 --- a/package/src/outputs/proving_key.rs +++ b/package/src/outputs/proving_key.rs @@ -64,10 +64,10 @@ impl ProvingKeyFile { /// Writes the given proving key to a file. pub fn write_to<'a>(&self, path: &'a Path, proving_key: &[u8]) -> Result> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_proving_key_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_proving_key_file)?; file.write_all(proving_key) - .map_err(|e| PackageError::io_error_proving_key_file(e))?; + .map_err(PackageError::io_error_proving_key_file)?; Ok(path) } diff --git a/package/src/outputs/verification_key.rs b/package/src/outputs/verification_key.rs index 5b3ba6f073..985376f1e0 100644 --- a/package/src/outputs/verification_key.rs +++ b/package/src/outputs/verification_key.rs @@ -65,10 +65,10 @@ impl VerificationKeyFile { /// Writes the given verification key to a file. pub fn write_to<'a>(&self, path: &'a Path, verification_key: &[u8]) -> Result> { let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(|e| PackageError::io_error_verification_key_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_verification_key_file)?; file.write_all(verification_key) - .map_err(|e| PackageError::io_error_verification_key_file(e))?; + .map_err(PackageError::io_error_verification_key_file)?; Ok(path) } diff --git a/package/src/root/gitignore.rs b/package/src/root/gitignore.rs index b324c56df0..ea16afdd6f 100644 --- a/package/src/root/gitignore.rs +++ b/package/src/root/gitignore.rs @@ -45,9 +45,9 @@ impl Gitignore { path.to_mut().push(GITIGNORE_FILENAME); } - let mut file = File::create(&path).map_err(|e| PackageError::io_error_gitignore_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_gitignore_file)?; file.write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_gitignore_file(e))?; + .map_err(PackageError::io_error_gitignore_file)?; Ok(()) } diff --git a/package/src/root/manifest.rs b/package/src/root/manifest.rs index a18f7ac826..fc08033cff 100644 --- a/package/src/root/manifest.rs +++ b/package/src/root/manifest.rs @@ -90,7 +90,7 @@ impl Manifest { File::create(&path).map_err(|e| PackageError::failed_to_create_manifest_file(MANIFEST_FILENAME, e))?; file.write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_manifest_file(e))?; + .map_err(PackageError::io_error_manifest_file)?; Ok(()) } diff --git a/package/src/root/readme.rs b/package/src/root/readme.rs index 3cea5acf5e..351d3efd51 100644 --- a/package/src/root/readme.rs +++ b/package/src/root/readme.rs @@ -54,10 +54,10 @@ impl README { path.to_mut().push(README_FILENAME); } - let mut file = File::create(&path).map_err(|e| PackageError::io_error_readme_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_readme_file)?; file.write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_readme_file(e))?; + .map_err(PackageError::io_error_readme_file)?; Ok(()) } diff --git a/package/src/root/zip.rs b/package/src/root/zip.rs index c2a131986c..62e4156f2f 100644 --- a/package/src/root/zip.rs +++ b/package/src/root/zip.rs @@ -83,7 +83,7 @@ impl ZipFile { // Create zip file let path = self.setup_file_path(src_dir); - let file = File::create(&path).map_err(|e| PackageError::failed_to_create_zip_file(e))?; + let file = File::create(&path).map_err(PackageError::failed_to_create_zip_file)?; let mut zip = ZipWriter::new(file); let options = FileOptions::default() .compression_method(zip::CompressionMethod::Stored) @@ -108,13 +108,13 @@ impl ZipFile { tracing::info!("Adding file {:?} as {:?}", path, name); #[allow(deprecated)] zip.start_file_from_path(name, options) - .map_err(|e| PackageError::io_error_zip_file(e))?; + .map_err(PackageError::io_error_zip_file)?; - let mut f = File::open(path).map_err(|e| PackageError::failed_to_open_zip_file(e))?; + let mut f = File::open(path).map_err(PackageError::failed_to_open_zip_file)?; f.read_to_end(&mut buffer) - .map_err(|e| PackageError::failed_to_read_zip_file(e))?; + .map_err(PackageError::failed_to_read_zip_file)?; zip.write_all(&*buffer) - .map_err(|e| PackageError::failed_to_write_zip_file(e))?; + .map_err(PackageError::failed_to_write_zip_file)?; buffer.clear(); } else if !name.as_os_str().is_empty() { @@ -123,11 +123,11 @@ impl ZipFile { tracing::info!("Adding directory {:?} as {:?}", path, name); #[allow(deprecated)] zip.add_directory_from_path(name, options) - .map_err(|e| PackageError::io_error_zip_file(e))?; + .map_err(PackageError::io_error_zip_file)?; } } - zip.finish().map_err(|e| PackageError::io_error_zip_file(e))?; + zip.finish().map_err(PackageError::io_error_zip_file)?; tracing::info!("Package zip file created successfully {:?}", path); diff --git a/package/src/source/directory.rs b/package/src/source/directory.rs index 1d906c1b0e..692f0261e4 100644 --- a/package/src/source/directory.rs +++ b/package/src/source/directory.rs @@ -36,7 +36,7 @@ impl SourceDirectory { path.to_mut().push(SOURCE_DIRECTORY_NAME); } - fs::create_dir_all(&path).map_err(|e| PackageError::failed_to_create_source_directory(e))?; + fs::create_dir_all(&path).map_err(PackageError::failed_to_create_source_directory)?; Ok(()) } @@ -45,11 +45,11 @@ impl SourceDirectory { let mut path = Cow::from(path); path.to_mut().push(SOURCE_DIRECTORY_NAME); - let directory = fs::read_dir(&path).map_err(|e| PackageError::failed_to_read_inputs_directory(e))?; + let directory = fs::read_dir(&path).map_err(PackageError::failed_to_read_inputs_directory)?; let mut file_paths = Vec::new(); for file_entry in directory.into_iter() { - let file_entry = file_entry.map_err(|e| PackageError::failed_to_get_source_file_entry(e))?; + let file_entry = file_entry.map_err(PackageError::failed_to_get_source_file_entry)?; let file_path = file_entry.path(); // Verify that the entry is structured as a valid file diff --git a/package/src/source/main.rs b/package/src/source/main.rs index 5d7f15bbf0..479c669e7d 100644 --- a/package/src/source/main.rs +++ b/package/src/source/main.rs @@ -60,10 +60,10 @@ impl MainFile { path.to_mut().push(MAIN_FILENAME); } - let mut file = File::create(&path).map_err(|e| PackageError::io_error_main_file(e))?; + let mut file = File::create(&path).map_err(PackageError::io_error_main_file)?; Ok(file .write_all(self.template().as_bytes()) - .map_err(|e| PackageError::io_error_main_file(e))?) + .map_err(PackageError::io_error_main_file)?) } fn template(&self) -> String { diff --git a/state/Cargo.toml b/state/Cargo.toml index 13a4c99a12..a1f404de72 100644 --- a/state/Cargo.toml +++ b/state/Cargo.toml @@ -17,14 +17,18 @@ include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] license = "GPL-3.0" edition = "2018" -[dependencies.leo-input] -path = "../input" -version = "1.5.3" - [dependencies.leo-ast] path = "../ast" version = "1.5.3" +[dependencies.leo-errors] +path = "../errors" +version = "1.5.3" + +[dependencies.leo-input] +path = "../input" +version = "1.5.3" + [dependencies.snarkvm-algorithms] version = "0.7.4" diff --git a/state/src/errors/dpc_record_values.rs b/state/src/errors/dpc_record_values.rs deleted file mode 100644 index 437666bfea..0000000000 --- a/state/src/errors/dpc_record_values.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::InputValueError; - -use snarkvm_dpc::AccountError; - -use std::{num::ParseIntError, str::ParseBoolError}; - -#[derive(Debug, Error)] -pub enum DPCRecordValuesError { - #[error("{}", _0)] - AccountError(#[from] AccountError), - - #[error("{}", _0)] - InputValueError(#[from] InputValueError), - - #[error("{}", _0)] - ParseBoolError(#[from] ParseBoolError), - - #[error("{}", _0)] - ParseIntError(#[from] ParseIntError), -} diff --git a/state/src/errors/input_value.rs b/state/src/errors/input_value.rs deleted file mode 100644 index 2463d27d4b..0000000000 --- a/state/src/errors/input_value.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::num::ParseIntError; - -#[derive(Debug, Error)] -pub enum InputValueError { - #[error("expected parameter array of u8 bytes, found `{}`", _0)] - ExpectedBytes(String), - - #[error("expected integer parameter, found `{}`", _0)] - ExpectedInteger(String), - - #[error("input parameter `{}` not found in state file", _0)] - MissingParameter(String), - - #[error("{}", _0)] - ParseIntError(#[from] ParseIntError), -} diff --git a/state/src/errors/local_data_commitment.rs b/state/src/errors/local_data_commitment.rs deleted file mode 100644 index a0f8465983..0000000000 --- a/state/src/errors/local_data_commitment.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{RecordVerificationError, StateLeafValuesError, StateValuesError}; - -use snarkvm_algorithms::{CommitmentError, MerkleError}; - -use std::io::Error as IOError; - -#[derive(Debug, Error)] -pub enum LocalDataVerificationError { - #[error("{}", _0)] - CommitmentError(#[from] CommitmentError), - - #[error("{}", _0)] - MerkleError(#[from] MerkleError), - - #[error("{}", _0)] - IOError(#[from] IOError), - - #[error("{}", _0)] - RecordVerificationError(#[from] RecordVerificationError), - - #[error("{}", _0)] - StateLeafValuesError(#[from] StateLeafValuesError), - - #[error("{}", _0)] - StateValuesError(#[from] StateValuesError), -} diff --git a/state/src/errors/mod.rs b/state/src/errors/mod.rs deleted file mode 100644 index 961b1fad08..0000000000 --- a/state/src/errors/mod.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod dpc_record_values; -pub use self::dpc_record_values::*; - -pub mod input_value; -pub use self::input_value::*; - -pub mod state_leaf_values; -pub use self::state_leaf_values::*; - -pub mod state_values; -pub use self::state_values::*; - -pub mod local_data_commitment; -pub use self::local_data_commitment::*; - -pub mod record_commitment; -pub use self::record_commitment::*; diff --git a/state/src/errors/record_commitment.rs b/state/src/errors/record_commitment.rs deleted file mode 100644 index 507c5bb48f..0000000000 --- a/state/src/errors/record_commitment.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::DPCRecordValuesError; - -use snarkvm_algorithms::CommitmentError; - -use std::io::Error as IOError; - -#[derive(Debug, Error)] -pub enum RecordVerificationError { - #[error("record commitment does not match record data")] - CommitmentsDoNotMatch, - - #[error("{}", _0)] - CommitmentError(#[from] CommitmentError), - - #[error("{}", _0)] - DPCRecordValuesError(#[from] DPCRecordValuesError), - - #[error("{}", _0)] - IOError(#[from] IOError), -} diff --git a/state/src/errors/state_leaf_values.rs b/state/src/errors/state_leaf_values.rs deleted file mode 100644 index 83b377178a..0000000000 --- a/state/src/errors/state_leaf_values.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::InputValueError; - -use std::{num::ParseIntError, str::ParseBoolError}; - -#[derive(Debug, Error)] -pub enum StateLeafValuesError { - #[error("{}", _0)] - InputValueError(#[from] InputValueError), - - #[error("{}", _0)] - ParseBoolError(#[from] ParseBoolError), - - #[error("{}", _0)] - ParseIntError(#[from] ParseIntError), -} diff --git a/state/src/errors/state_values.rs b/state/src/errors/state_values.rs deleted file mode 100644 index 94af651517..0000000000 --- a/state/src/errors/state_values.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::InputValueError; - -use std::{num::ParseIntError, str::ParseBoolError}; - -#[derive(Debug, Error)] -pub enum StateValuesError { - #[error("{}", _0)] - InputValueError(#[from] InputValueError), - - #[error("{}", _0)] - ParseBoolError(#[from] ParseBoolError), - - #[error("{}", _0)] - ParseIntError(#[from] ParseIntError), -} diff --git a/state/src/lib.rs b/state/src/lib.rs index 65bd11e5d5..70de10048d 100644 --- a/state/src/lib.rs +++ b/state/src/lib.rs @@ -17,12 +17,6 @@ #![allow(clippy::module_inception)] #![allow(clippy::upper_case_acronyms)] -#[macro_use] -extern crate thiserror; - -pub mod errors; -pub use self::errors::*; - pub mod local_data_commitment; pub use self::local_data_commitment::*; diff --git a/state/src/local_data_commitment/local_data_commitment.rs b/state/src/local_data_commitment/local_data_commitment.rs index 19b74c6f22..5a5fa81317 100644 --- a/state/src/local_data_commitment/local_data_commitment.rs +++ b/state/src/local_data_commitment/local_data_commitment.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{verify_record_commitment, LocalDataVerificationError, StateLeafValues, StateValues}; +use crate::{verify_record_commitment, StateLeafValues, StateValues}; use leo_ast::Input as AstInput; +use leo_errors::{Result, SnarkVMError, StateError}; use snarkvm_algorithms::{ commitment_tree::CommitmentMerklePath, @@ -31,10 +32,7 @@ use std::convert::TryFrom; /// Returns `true` if the path to the local data commitment leaf is a valid path in the record /// commitment Merkle tree. -pub fn verify_local_data_commitment( - dpc: &SystemParameters, - ast_input: &AstInput, -) -> Result { +pub fn verify_local_data_commitment(dpc: &SystemParameters, ast_input: &AstInput) -> Result { // Verify record commitment. let typed_record = ast_input.get_record(); let dpc_record_values = verify_record_commitment(dpc, typed_record)?; @@ -58,35 +56,42 @@ pub fn verify_local_data_commitment( // Select local data commitment input bytes. let is_death = leaf_index < (Components::NUM_INPUT_RECORDS as u32); let input_bytes = if is_death { - to_bytes_le![record_serial_number, record_commitment, memo, network_id]? + to_bytes_le![record_serial_number, record_commitment, memo, network_id] + .map_err(StateError::state_io_error)? } else { - to_bytes_le![record_commitment, memo, network_id]? + to_bytes_le![record_commitment, memo, network_id].map_err(StateError::state_io_error)? }; // Construct local data commitment leaf. let local_data_leaf_randomness = <::LocalDataCommitment as CommitmentScheme>::Randomness::read_le( &leaf_randomness[..], - )?; + ) + .map_err(StateError::state_io_error)?; let local_data_commitment_leaf = ::LocalDataCommitment::commit( &dpc.local_data_commitment, &input_bytes, &local_data_leaf_randomness, - )?; + ) + .map_err(|_| SnarkVMError::default())?; // Construct record commitment merkle path. let local_data_merkle_path = CommitmentMerklePath::< ::LocalDataCommitment, ::LocalDataCRH, - >::read_le(&path[..])?; + >::read_le(&path[..]) + .map_err(StateError::state_io_error)?; // Check record commitment merkle path is valid for the given local data commitment root. - let local_data_commitment_root = <::LocalDataCRH as CRH>::Output::read_le(&root[..])?; - let result = local_data_merkle_path.verify( - &dpc.local_data_crh, - &local_data_commitment_root, - &local_data_commitment_leaf, - )?; + let local_data_commitment_root = <::LocalDataCRH as CRH>::Output::read_le(&root[..]) + .map_err(StateError::state_io_error)?; + let result = local_data_merkle_path + .verify( + &dpc.local_data_crh, + &local_data_commitment_root, + &local_data_commitment_leaf, + ) + .map_err(|_| SnarkVMError::default())?; Ok(result) } diff --git a/state/src/local_data_commitment/state_leaf_values.rs b/state/src/local_data_commitment/state_leaf_values.rs index 8c7148741d..b0f60390cd 100644 --- a/state/src/local_data_commitment/state_leaf_values.rs +++ b/state/src/local_data_commitment/state_leaf_values.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{find_input, input_to_bytes, input_to_integer_string, StateLeafValuesError}; +use crate::{find_input, input_to_bytes, input_to_integer_string}; use leo_ast::StateLeaf as AstStateLeaf; +use leo_errors::{LeoError, Result, StateError}; use std::convert::TryFrom; @@ -34,9 +35,9 @@ pub struct StateLeafValues { } impl TryFrom<&AstStateLeaf> for StateLeafValues { - type Error = StateLeafValuesError; + type Error = LeoError; - fn try_from(ast_state_leaf: &AstStateLeaf) -> Result { + fn try_from(ast_state_leaf: &AstStateLeaf) -> Result { let parameters = ast_state_leaf.values(); // Lookup path @@ -49,7 +50,9 @@ impl TryFrom<&AstStateLeaf> for StateLeafValues { // Lookup network id let network_id_value = find_input(NETWORK_ID_PARAMETER_STRING.to_owned(), ¶meters)?; - let network_id = input_to_integer_string(network_id_value)?.parse::()?; + let network_id = input_to_integer_string(network_id_value)? + .parse::() + .map_err(StateError::parse_int_error)?; // Lookup leaf randomness let leaf_randomness_value = find_input(LEAF_RANDOMNESS_PARAMETER_STRING.to_owned(), ¶meters)?; diff --git a/state/src/local_data_commitment/state_values.rs b/state/src/local_data_commitment/state_values.rs index 0ba48af568..323d4ccf46 100644 --- a/state/src/local_data_commitment/state_values.rs +++ b/state/src/local_data_commitment/state_values.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{find_input, input_to_bytes, input_to_integer_string, StateValuesError}; +use crate::{find_input, input_to_bytes, input_to_integer_string}; use leo_ast::State as AstState; +use leo_errors::{LeoError, Result, StateError}; use std::convert::TryFrom; @@ -30,14 +31,16 @@ pub struct StateValues { } impl TryFrom<&AstState> for StateValues { - type Error = StateValuesError; + type Error = LeoError; - fn try_from(ast_state: &AstState) -> Result { + fn try_from(ast_state: &AstState) -> Result { let parameters = ast_state.values(); // Lookup leaf index let leaf_index_value = find_input(LEAF_INDEX_PARAMETER_STRING.to_owned(), ¶meters)?; - let leaf_index = input_to_integer_string(leaf_index_value)?.parse::()?; + let leaf_index = input_to_integer_string(leaf_index_value)? + .parse::() + .map_err(StateError::parse_int_error)?; // Lookup root let root_value = find_input(ROOT_PARAMETER_STRING.to_owned(), ¶meters)?; diff --git a/state/src/record_commitment/dpc_record_values.rs b/state/src/record_commitment/dpc_record_values.rs index 7de85e1cc0..945b541001 100644 --- a/state/src/record_commitment/dpc_record_values.rs +++ b/state/src/record_commitment/dpc_record_values.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{utilities::*, DPCRecordValuesError}; +use crate::utilities::*; use leo_ast::Record as AstRecord; +use leo_errors::{LeoError, Result, SnarkVMError, StateError}; use snarkvm_dpc::{testnet1::instantiated::Components, Address}; @@ -48,9 +49,9 @@ pub struct DPCRecordValues { } impl TryFrom<&AstRecord> for DPCRecordValues { - type Error = DPCRecordValuesError; + type Error = LeoError; - fn try_from(ast_record: &AstRecord) -> Result { + fn try_from(ast_record: &AstRecord) -> Result { let parameters = ast_record.values(); // Lookup serial number @@ -59,15 +60,20 @@ impl TryFrom<&AstRecord> for DPCRecordValues { // Lookup record owner let owner_value = find_input(OWNER_PARAMETER_STRING.to_owned(), ¶meters)?; - let owner = Address::::from_str(&owner_value.to_string())?; + let owner = Address::::from_str(&owner_value.to_string()).map_err(|_| SnarkVMError::default())?; // Lookup record is_dummy let is_dummy_value = find_input(IS_DUMMY_PARAMETER_STRING.to_owned(), ¶meters)?; - let is_dummy = is_dummy_value.to_string().parse::()?; + let is_dummy = is_dummy_value + .to_string() + .parse::() + .map_err(StateError::parse_bool_error)?; // Lookup record value let value_value = find_input(VALUE_PARAMETER_STRING.to_owned(), ¶meters)?; - let value = input_to_integer_string(value_value)?.parse::()?; + let value = input_to_integer_string(value_value)? + .parse::() + .map_err(StateError::parse_int_error)?; // Lookup record payload let payload_value = find_input(PAYLOAD_PARAMETER_STRING.to_owned(), ¶meters)?; diff --git a/state/src/record_commitment/record_commitment.rs b/state/src/record_commitment/record_commitment.rs index c4b7549b1d..fad0ed8241 100644 --- a/state/src/record_commitment/record_commitment.rs +++ b/state/src/record_commitment/record_commitment.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{DPCRecordValues, RecordVerificationError}; +use crate::DPCRecordValues; use leo_ast::Record as AstRecord; +use leo_errors::{Result, SnarkVMError, StateError}; use snarkvm_algorithms::traits::CommitmentScheme; use snarkvm_dpc::{ @@ -28,12 +29,9 @@ use std::convert::TryFrom; /// Returns a serialized [`DPCRecordValues`] type if the record commitment is valid given the /// system parameters. -pub fn verify_record_commitment( - dpc: &SystemParameters, - ast_record: &AstRecord, -) -> Result { +pub fn verify_record_commitment(dpc: &SystemParameters, ast_record: &AstRecord) -> Result { // generate a dpc record from the typed record - let record = DPCRecordValues::try_from(ast_record)?; + let record: DPCRecordValues = DPCRecordValues::try_from(ast_record)?; // verify record commitment let record_commitment_input = to_bytes_le![ @@ -44,24 +42,28 @@ pub fn verify_record_commitment( record.birth_program_id, record.death_program_id, record.serial_number_nonce - ]?; + ] + .map_err(StateError::state_io_error)?; let commitment = - <::RecordCommitment as CommitmentScheme>::Output::read_le(&record.commitment[..])?; + <::RecordCommitment as CommitmentScheme>::Output::read_le(&record.commitment[..]) + .map_err(StateError::state_io_error)?; let commitment_randomness = <::RecordCommitment as CommitmentScheme>::Randomness::read_le( &record.commitment_randomness[..], - )?; + ) + .map_err(StateError::state_io_error)?; let record_commitment = ::RecordCommitment::commit( &dpc.record_commitment, &record_commitment_input, &commitment_randomness, - )?; + ) + .map_err(|_| SnarkVMError::default())?; if record_commitment == commitment { Ok(record) } else { - Err(RecordVerificationError::CommitmentsDoNotMatch) + Err(SnarkVMError::default().into()) } } diff --git a/state/src/utilities/input_value.rs b/state/src/utilities/input_value.rs index a4e463f038..0640d21844 100644 --- a/state/src/utilities/input_value.rs +++ b/state/src/utilities/input_value.rs @@ -14,49 +14,48 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::InputValueError; use leo_ast::{InputValue, Parameter}; +use leo_errors::{Result, StateError}; use indexmap::IndexMap; /// Returns the input parameter with the given name. /// If a parameter with the given name does not exist, then an error is returned. -pub fn find_input( - name: String, - parameters: &IndexMap>, -) -> Result { +pub fn find_input(name: String, parameters: &IndexMap>) -> Result { let matched_parameter = parameters .iter() .find(|(parameter, _value)| parameter.variable.name.as_ref() == name); match matched_parameter { Some((_, Some(value))) => Ok(value.clone()), - _ => Err(InputValueError::MissingParameter(name)), + _ => Err(StateError::mising_parameter(name).into()), } } /// Returns the string of the integer input value. /// If the input value is not an integer, then an error is returned. -pub fn input_to_integer_string(input: InputValue) -> Result { +pub fn input_to_integer_string(input: InputValue) -> Result { match input { InputValue::Integer(_type, string) => Ok(string), - value => Err(InputValueError::ExpectedInteger(value.to_string())), + value => Err(StateError::expected_int(value).into()), } } /// Returns the given input value as u8 bytes. /// If the given input value cannot be serialized into bytes then an error is returned. -pub fn input_to_bytes(input: InputValue) -> Result, InputValueError> { +pub fn input_to_bytes(input: InputValue) -> Result> { let input_array = match input { InputValue::Array(values) => values, - value => return Err(InputValueError::ExpectedBytes(value.to_string())), + value => return Err(StateError::expected_bytes(value).into()), }; let mut result_vec = Vec::with_capacity(input_array.len()); for input in input_array { let integer_string = input_to_integer_string(input)?; - let byte = integer_string.parse::()?; + let byte = integer_string + .parse::() + .map_err(StateError::parse_int_error)?; result_vec.push(byte); } @@ -66,10 +65,10 @@ pub fn input_to_bytes(input: InputValue) -> Result, InputValueError> { /// Returns the given input value as an array of u8 bytes. /// If the given input value cannot be serialized into an array of bytes then an error is returned. -pub fn input_to_nested_bytes(input: InputValue) -> Result>, InputValueError> { +pub fn input_to_nested_bytes(input: InputValue) -> Result>> { let inner_arrays = match input { InputValue::Array(arrays) => arrays, - value => return Err(InputValueError::ExpectedBytes(value.to_string())), + value => return Err(StateError::expected_bytes(value).into()), }; let mut result_vec = Vec::with_capacity(inner_arrays.len());