state errors migrated

This commit is contained in:
gluaxspeed 2021-08-04 15:22:40 -07:00
parent 2a99a87da7
commit b35375908b
51 changed files with 232 additions and 425 deletions

1
Cargo.lock generated
View File

@ -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",

View File

@ -107,7 +107,7 @@ pub fn generate_test_constraints<'a, F: PrimeField, G: GroupType<F>>(
}
}
}
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

View File

@ -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,

View File

@ -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)?;
}

View File

@ -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);

View File

@ -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,
}
);

View File

@ -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<String, String> = res.json().map_err(|e| CliError::reqwest_json_error(e))?;
let res: HashMap<String, String> = 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));
}

View File

@ -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) {

View File

@ -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)?;

View File

@ -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::<Vec<u8>>())
.map_err(|e| CliError::cli_bytes_conversion_error(e))?;
.map_err(CliError::cli_bytes_conversion_error)?;
}
}

View File

@ -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::<Vec<u8>>())
.map_err(|e| CliError::cli_bytes_conversion_error(e))?;
.map_err(CliError::cli_bytes_conversion_error)?;
}
}

View File

@ -72,7 +72,7 @@ impl Command for Login {
};
let res = api.run_route(login)?;
let mut res: HashMap<String, String> = res.json().map_err(|e| CliError::reqwest_json_error(e))?;
let mut res: HashMap<String, String> = res.json().map_err(CliError::reqwest_json_error)?;
let tok_opt = res.remove("token");
if tok_opt.is_none() {

View File

@ -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))

View File

@ -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::<Bls12_377>::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::<Bls12_377>::read(verifying_key_bytes.as_slice())
.map_err(|e| CliError::cli_io_error(e))?;
.map_err(CliError::cli_io_error)?;
let verifying_key =
VerifyingKey::<Bls12_377>::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::<Bls12_377>::from(verifying_key);

View File

@ -61,7 +61,7 @@ impl Command for Update {
fn apply(self, _: Context, _: Self::Input) -> Result<Self::Output> {
// 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.

View File

@ -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");

View File

@ -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::<Config>(&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<String> {
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<String> {
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)
}

View File

@ -37,7 +37,7 @@ impl Context {
pub fn dir(&self) -> Result<PathBuf> {
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)?),
}
}

View File

@ -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};

View File

@ -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(&current_version, &latest_release.version).map_err(|e| CliError::self_update_error(e))? {
if bump_is_greater(&current_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())

View File

@ -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(())
}

View File

@ -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<PathBuf>) -> 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<PathBuf>) -> 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;

View File

@ -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(())
}

View File

@ -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 {

View File

@ -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(())
}

View File

@ -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(())
}

View File

@ -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(())

View File

@ -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(())

View File

@ -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<Cow<'a, Path>> {
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)
}

View File

@ -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<Cow<'a, Path>> {
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)
}

View File

@ -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(())
}

View File

@ -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(())
}

View File

@ -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(())
}

View File

@ -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);

View File

@ -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

View File

@ -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 {

View File

@ -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"

View File

@ -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 <https://www.gnu.org/licenses/>.
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),
}

View File

@ -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 <https://www.gnu.org/licenses/>.
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),
}

View File

@ -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 <https://www.gnu.org/licenses/>.
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),
}

View File

@ -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 <https://www.gnu.org/licenses/>.
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::*;

View File

@ -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 <https://www.gnu.org/licenses/>.
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),
}

View File

@ -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 <https://www.gnu.org/licenses/>.
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),
}

View File

@ -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 <https://www.gnu.org/licenses/>.
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),
}

View File

@ -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::*;

View File

@ -14,8 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
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<Components>,
ast_input: &AstInput,
) -> Result<bool, LocalDataVerificationError> {
pub fn verify_local_data_commitment(dpc: &SystemParameters<Components>, ast_input: &AstInput) -> Result<bool> {
// 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 =
<<Components as DPCComponents>::LocalDataCommitment as CommitmentScheme>::Randomness::read_le(
&leaf_randomness[..],
)?;
)
.map_err(StateError::state_io_error)?;
let local_data_commitment_leaf = <Components as DPCComponents>::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::<
<Components as DPCComponents>::LocalDataCommitment,
<Components as DPCComponents>::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 = <<Components as DPCComponents>::LocalDataCRH as CRH>::Output::read_le(&root[..])?;
let result = local_data_merkle_path.verify(
let local_data_commitment_root = <<Components as DPCComponents>::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)
}

View File

@ -14,8 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
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<Self, Self::Error> {
fn try_from(ast_state_leaf: &AstStateLeaf) -> Result<Self> {
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(), &parameters)?;
let network_id = input_to_integer_string(network_id_value)?.parse::<u8>()?;
let network_id = input_to_integer_string(network_id_value)?
.parse::<u8>()
.map_err(StateError::parse_int_error)?;
// Lookup leaf randomness
let leaf_randomness_value = find_input(LEAF_RANDOMNESS_PARAMETER_STRING.to_owned(), &parameters)?;

View File

@ -14,8 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
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<Self, Self::Error> {
fn try_from(ast_state: &AstState) -> Result<Self> {
let parameters = ast_state.values();
// Lookup leaf index
let leaf_index_value = find_input(LEAF_INDEX_PARAMETER_STRING.to_owned(), &parameters)?;
let leaf_index = input_to_integer_string(leaf_index_value)?.parse::<u32>()?;
let leaf_index = input_to_integer_string(leaf_index_value)?
.parse::<u32>()
.map_err(StateError::parse_int_error)?;
// Lookup root
let root_value = find_input(ROOT_PARAMETER_STRING.to_owned(), &parameters)?;

View File

@ -14,8 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
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<Self, Self::Error> {
fn try_from(ast_record: &AstRecord) -> Result<Self> {
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(), &parameters)?;
let owner = Address::<Components>::from_str(&owner_value.to_string())?;
let owner = Address::<Components>::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(), &parameters)?;
let is_dummy = is_dummy_value.to_string().parse::<bool>()?;
let is_dummy = is_dummy_value
.to_string()
.parse::<bool>()
.map_err(StateError::parse_bool_error)?;
// Lookup record value
let value_value = find_input(VALUE_PARAMETER_STRING.to_owned(), &parameters)?;
let value = input_to_integer_string(value_value)?.parse::<u64>()?;
let value = input_to_integer_string(value_value)?
.parse::<u64>()
.map_err(StateError::parse_int_error)?;
// Lookup record payload
let payload_value = find_input(PAYLOAD_PARAMETER_STRING.to_owned(), &parameters)?;

View File

@ -14,8 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
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<Components>,
ast_record: &AstRecord,
) -> Result<DPCRecordValues, RecordVerificationError> {
pub fn verify_record_commitment(dpc: &SystemParameters<Components>, ast_record: &AstRecord) -> Result<DPCRecordValues> {
// 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 =
<<Components as DPCComponents>::RecordCommitment as CommitmentScheme>::Output::read_le(&record.commitment[..])?;
<<Components as DPCComponents>::RecordCommitment as CommitmentScheme>::Output::read_le(&record.commitment[..])
.map_err(StateError::state_io_error)?;
let commitment_randomness =
<<Components as DPCComponents>::RecordCommitment as CommitmentScheme>::Randomness::read_le(
&record.commitment_randomness[..],
)?;
)
.map_err(StateError::state_io_error)?;
let record_commitment = <Components as DPCComponents>::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())
}
}

View File

@ -14,49 +14,48 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
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<Parameter, Option<InputValue>>,
) -> Result<InputValue, InputValueError> {
pub fn find_input(name: String, parameters: &IndexMap<Parameter, Option<InputValue>>) -> Result<InputValue> {
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<String, InputValueError> {
pub fn input_to_integer_string(input: InputValue) -> Result<String> {
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<Vec<u8>, InputValueError> {
pub fn input_to_bytes(input: InputValue) -> Result<Vec<u8>> {
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::<u8>()?;
let byte = integer_string
.parse::<u8>()
.map_err(StateError::parse_int_error)?;
result_vec.push(byte);
}
@ -66,10 +65,10 @@ pub fn input_to_bytes(input: InputValue) -> Result<Vec<u8>, 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<Vec<Vec<u8>>, InputValueError> {
pub fn input_to_nested_bytes(input: InputValue) -> Result<Vec<Vec<u8>>> {
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());