use crate::{errors::VerificationKeyFileError, outputs::OUTPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::Path,
};
pub static VERIFICATION_KEY_FILE_EXTENSION: &str = ".lvk";
#[derive(Deserialize)]
pub struct VerificationKeyFile {
pub package_name: String,
}
impl VerificationKeyFile {
pub fn new(package_name: &str) -> Self {
Self {
package_name: package_name.to_string(),
}
}
pub fn full_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
self.setup_file_path(path)
}
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
pub fn read_from(&self, path: &Path) -> Result<Vec<u8>, VerificationKeyFileError> {
let path = self.setup_file_path(path);
Ok(fs::read(&path).map_err(|_| VerificationKeyFileError::FileReadError(path.into_owned()))?)
}
pub fn write_to<'a>(
&self,
path: &'a Path,
verification_key: &[u8],
) -> Result<Cow<'a, Path>, VerificationKeyFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
file.write_all(verification_key)?;
Ok(path)
}
pub fn remove(&self, path: &Path) -> Result<bool, VerificationKeyFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| VerificationKeyFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.to_mut()
.push(format!("{}{}", self.package_name, VERIFICATION_KEY_FILE_EXTENSION));
}
path
}
}