Skip to content

Commit

Permalink
Removed redundant error documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
sokorototo committed May 21, 2024
1 parent 1873b9e commit 9608bbc
Show file tree
Hide file tree
Showing 11 changed files with 45 additions and 98 deletions.
10 changes: 0 additions & 10 deletions vach/src/crypto_utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,19 @@ pub fn gen_keypair() -> crypto::SigningKey {
}

/// Use this to read and parse a `Keypair` from a read stream
/// ### Errors
/// - If the data can't be parsed into a keypair
pub fn read_keypair<R: Read>(mut handle: R) -> InternalResult<crypto::SigningKey> {
let mut keypair_bytes = [0; crate::SECRET_KEY_LENGTH + crate::PUBLIC_KEY_LENGTH];
handle.read_exact(&mut keypair_bytes)?;
crypto::SigningKey::from_keypair_bytes(&keypair_bytes).map_err(|err| InternalError::ParseError(err.to_string()))
}

/// Read and parse a public key from a read stream
///
/// ### Errors
/// - If parsing of the public key fails
/// - `io` errors
pub fn read_public_key<T: Read>(mut handle: T) -> InternalResult<crypto::VerifyingKey> {
let mut keypair_bytes = [0; crate::PUBLIC_KEY_LENGTH];
handle.read_exact(&mut keypair_bytes)?;
crypto::VerifyingKey::from_bytes(&keypair_bytes).map_err(|err| InternalError::ParseError(err.to_string()))
}
/// Read and parse a secret key from a read stream
///
/// ### Errors
/// - If parsing of the secret key fails
/// - `io` errors
pub fn read_secret_key<T: Read>(mut handle: T) -> InternalResult<crypto::SigningKey> {
let mut secret_bytes = [0; crate::SECRET_KEY_LENGTH];
handle.read_exact(&mut secret_bytes)?;
Expand Down
3 changes: 0 additions & 3 deletions vach/src/global/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,6 @@ impl Flags {
/// flag.set(0b0000_1000_0000_0001, false).unwrap(); // 0 flags remain zero
/// assert_eq!(flag.bits(), 0b1000_0000_0000_0000);
/// ```
///
/// ### Errors
/// - Trying to set a bit in the forbidden section of the flags
pub fn set(&mut self, bit: u32, toggle: bool) -> InternalResult<u32> {
if (Flags::RESERVED_MASK & bit) != 0 {
return Err(InternalError::RestrictedFlagAccessError);
Expand Down
8 changes: 0 additions & 8 deletions vach/src/global/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,6 @@ impl ArchiveConfig {
/// // config.load_public_key(&keypair_bytes).unwrap();
/// config.load_public_key(&keypair_bytes[32..]).unwrap();
/// ```
///
/// ### Errors
/// - If parsing of the public key fails
/// - `io` errors
#[inline]
#[cfg(feature = "crypto")]
#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
Expand Down Expand Up @@ -147,8 +143,6 @@ impl Header {
pub const CAPACITY_SIZE: usize = 2;

/// Validates a `Header` with a template [ArchiveConfig]
/// ### Errors
/// - (in)validation of magic and archive version
pub(crate) fn validate(config: &ArchiveConfig, header: &Header) -> InternalResult {
// Validate magic
if header.magic != config.magic {
Expand All @@ -163,8 +157,6 @@ impl Header {
Ok(())
}

/// ### Errors
/// - `io` errors
pub(crate) fn from_handle<T: Read>(mut handle: T) -> InternalResult<Header> {
let mut buffer: [u8; Header::BASE_SIZE] = [0u8; Header::BASE_SIZE];
handle.read_exact(&mut buffer)?;
Expand Down
4 changes: 1 addition & 3 deletions vach/src/global/reg_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ impl RegistryEntry {
}

/// Given a read handle, will proceed to read and parse bytes into a [`RegistryEntry`] struct. (de-serialization)
/// ### Errors
/// Produces `io` errors and if the bytes in the id section is not valid UTF-8
pub(crate) fn from_handle<T: Read>(mut handle: T) -> InternalResult<RegistryEntry> {
let mut buffer: [u8; RegistryEntry::MIN_SIZE] = [0u8; RegistryEntry::MIN_SIZE];
handle.read_exact(&mut buffer)?;
Expand Down Expand Up @@ -98,7 +96,7 @@ impl RegistryEntry {
}

/// Serializes a [`RegistryEntry`] struct into an array of bytes
pub(crate) fn encode(&self, skip_signature: bool) -> InternalResult<Vec<u8>> {
pub(crate) fn to_bytes(&self, skip_signature: bool) -> InternalResult<Vec<u8>> {
// Make sure the ID is not too big or else it will break the archive
let id = self.id.as_ref();

Expand Down
4 changes: 1 addition & 3 deletions vach/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,7 @@ pub mod builder {
#[cfg_attr(docsrs, doc(cfg(feature = "archive")))]
pub mod archive {
pub use crate::loader::{archive::Archive, resource::Resource};
pub use crate::global::{
reg_entry::RegistryEntry, header::ArchiveConfig, error::*, flags::Flags,
};
pub use crate::global::{reg_entry::RegistryEntry, header::ArchiveConfig, error::*, flags::Flags};
#[cfg(feature = "compression")]
pub use crate::global::compressor::CompressionAlgorithm;
}
Expand Down
56 changes: 21 additions & 35 deletions vach/src/loader/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl<T> Archive<T> {

// Decompress and|or decrypt the data
#[inline(never)]
fn process(&self, entry: &RegistryEntry, id: &str, mut raw: Vec<u8>) -> InternalResult<(Vec<u8>, bool)> {
fn process(&self, entry: &RegistryEntry, mut raw: Vec<u8>) -> InternalResult<(Vec<u8>, bool)> {
/* Literally the hottest function in the block (🕶) */

// buffer_a originally contains the raw data
Expand All @@ -88,7 +88,7 @@ impl<T> Archive<T> {
if let Some(signature) = entry.signature {
let raw_size = raw.len();

let entry_bytes = entry.encode(true)?;
let entry_bytes = entry.to_bytes(true)?;
raw.extend_from_slice(&entry_bytes);

is_secure = pk.verify_strict(&raw, &signature).is_ok();
Expand Down Expand Up @@ -136,7 +136,11 @@ impl<T> Archive<T> {
Compressor::new(source.as_slice()).decompress(CompressionAlgorithm::Snappy, &mut target)?
} else {
return InternalResult::Err(InternalError::OtherError(
format!("Unable to determine the compression algorithm used for entry with ID: {id}").into(),
format!(
"Unable to determine the compression algorithm used for entry: {}",
entry
)
.into(),
));
};

Expand Down Expand Up @@ -164,20 +168,13 @@ where
/// ```skip
/// Archive::with_config(HANDLE, &ArchiveConfig::default())?;
/// ```
/// ### Errors
/// - If the internal call to `Archive::with_config(-)` returns an error
#[inline(always)]
pub fn new(handle: T) -> InternalResult<Archive<T>> {
Archive::with_config(handle, &ArchiveConfig::default())
}

/// Given a read handle, this will read and parse the data into an [`Archive`] struct.
/// Pass a reference to [ArchiveConfig] and it will be used to validate the source and for further configuration.
/// ### Errors
/// - If parsing fails, an `Err(---)` is returned.
/// - The archive fails to validate
/// - `io` errors
/// - If any `ID`s are not valid UTF-8
pub fn with_config(mut handle: T, config: &ArchiveConfig) -> InternalResult<Archive<T>> {
// Start reading from the start of the input
handle.seek(SeekFrom::Start(0))?;
Expand All @@ -194,31 +191,20 @@ where
entries.insert(entry.id.clone(), entry);
}

#[cfg(feature = "crypto")]
{
// Errors where no decryptor has been instantiated will be returned once a fetch is made to an encrypted resource
let decryptor = config
let archive = Archive {
header,
handle: Mutex::new(handle),
entries,

#[cfg(feature = "crypto")]
key: config.public_key,
#[cfg(feature = "crypto")]
decryptor: config
.public_key
.as_ref()
.map(|pk| crypto::Encryptor::new(pk, config.magic));

Ok(Archive {
header,
handle: Mutex::new(handle),
key: config.public_key,
entries,
decryptor,
})
}

#[cfg(not(feature = "crypto"))]
{
Ok(Archive {
header,
handle: Mutex::new(handle),
entries,
})
}
.map(|pk| crypto::Encryptor::new(pk, config.magic)),
};
Ok(archive)
}

/// Fetch a [`RegistryEntry`] from this [`Archive`].
Expand Down Expand Up @@ -265,7 +251,7 @@ where

// Prepare contextual variables
// Decompress and|or decrypt the data
let (buffer, is_secure) = self.process(&entry, id.as_ref(), raw)?;
let (buffer, is_secure) = self.process(&entry, raw)?;

Ok(Resource {
content_version: entry.content_version,
Expand All @@ -290,7 +276,7 @@ where

// Prepare contextual variables
// Decompress and|or decrypt the data
let (buffer, is_secure) = self.process(&entry, id.as_ref(), raw)?;
let (buffer, is_secure) = self.process(&entry, raw)?;

Ok(Resource {
content_version: entry.content_version,
Expand Down
22 changes: 11 additions & 11 deletions vach/src/tests/mod.rs → vach/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::prelude::*;

// Contains both the public key and secret key in the same file:
// secret -> [u8; crate::SECRET_KEY_LENGTH], public -> [u8; crate::PUBLIC_KEY_LENGTH]
const KEYPAIR: &[u8; crate::SECRET_KEY_LENGTH + crate::PUBLIC_KEY_LENGTH] = include_bytes!("../../test_data/pair.pub");
const KEYPAIR: &[u8; crate::SECRET_KEY_LENGTH + crate::PUBLIC_KEY_LENGTH] = include_bytes!("../test_data/pair.pub");

// The paths to the Archives, to be written|loaded
const SIGNED_TARGET: &str = "test_data/signed/target.vach";
Expand Down Expand Up @@ -137,12 +137,15 @@ fn builder_with_signature() -> InternalResult {
let mut build_config = BuilderConfig::default().callback(&cb);

build_config.load_keypair(KEYPAIR.as_slice())?;
builder.add_dir("test_data", None)?;

let template = Leaf::default().sign(true);
builder.add_dir("test_data", Some(&template))?;
// sign and no sign!
builder.add_leaf(Leaf::default().id("not_signed"))?;

// Tests conditional signing
builder.add_leaf(Leaf::default().id("not_signed").sign(false))?;
let signed = Leaf::new(b"Don't forget to recite your beatitudes!" as &[u8])
.id("signed")
.sign(true);
builder.add_leaf(signed)?;

let mut target = File::create(SIGNED_TARGET)?;
println!(
Expand All @@ -169,19 +172,16 @@ fn fetch_with_signature() -> InternalResult {

// The adjacent resource was flagged to not be signed
let not_signed_resource = archive.fetch_mut("not_signed")?;
assert!(!not_signed_resource.flags.contains(Flags::SIGNED_FLAG));
assert!(!not_signed_resource.authenticated);

// The adjacent resource was flagged to not be signed
let not_signed_resource = archive.fetch_mut("not_signed")?;
dbg!(&archive.entries());
assert!(!not_signed_resource.flags.contains(Flags::SIGNED_FLAG));
assert!(!not_signed_resource.authenticated);

// Check authenticity of retrieved data
let song = song.trim();
println!("{}", song);
assert_eq!(song.len(), 1977);

let resource = archive.fetch_mut("signed")?;

assert!(resource.authenticated);
assert!(resource.flags.contains(Flags::SIGNED_FLAG));

Expand Down
2 changes: 0 additions & 2 deletions vach/src/writer/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,6 @@ impl<'a> BuilderConfig<'a> {

// Keypair helpers
/// Parses and stores a keypair from a source.
/// ### Errors
/// If the call to `::utils::read_keypair()` fails to parse the data from the handle
#[cfg(feature = "crypto")]
pub fn load_keypair<T: std::io::Read>(&mut self, handle: T) -> crate::global::error::InternalResult {
crate::crypto_utils::read_keypair(handle).map(|kp| self.keypair = Some(kp))
Expand Down
20 changes: 4 additions & 16 deletions vach/src/writer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ impl<'a> Builder<'a> {
/// Appends a read handle wrapped in a [`Leaf`] into the processing queue.
/// The `data` is wrapped in the default [`Leaf`], without cloning the original data.
/// The second argument is the `ID` with which the embedded data will be tagged
/// ### Errors
/// - if a Leaf with the specified ID exists.
pub fn add<D: Read + Send + Sync + 'a>(&mut self, data: D, id: impl AsRef<str>) -> InternalResult {
let leaf = Leaf::new(data)
.id(id.as_ref().to_string())
Expand All @@ -67,9 +65,6 @@ impl<'a> Builder<'a> {
/// Loads all files from a directory, parses them into [`Leaf`]s and appends them into the processing queue.
/// An optional [`Leaf`] is passed as a template from which the new [`Leaf`]s shall implement, pass `None` to use the [`Builder`] internal default template.
/// Appended [`Leaf`]s have an `ID` in the form of of: `directory_name/file_name`. For example: `sounds/footstep.wav1, `sample/script.data`
/// ## Errors
/// - Any of the underlying calls to the filesystem fail.
/// - The internal call to `Builder::add_leaf()` fails.
pub fn add_dir(&mut self, path: impl AsRef<Path>, template: Option<&Leaf<'a>>) -> InternalResult {
use std::fs;

Expand All @@ -96,10 +91,8 @@ impl<'a> Builder<'a> {
Ok(())
}

/// Append a preconstructed [`Leaf`] into the processing queue.
/// [`Leaf`]s added directly do not implement data from the [`Builder`]s internal template.
/// ### Errors
/// - Returns an error if a [`Leaf`] with the specified `ID` exists.
/// Directly add a [`Leaf`] to the [`Builder`]
/// [`Leaf`]s added directly do not inherit data from the [`Builder`]s template.
pub fn add_leaf(&mut self, leaf: Leaf<'a>) -> InternalResult {
// Make sure no two leaves are written with the same ID
if !self.id_set.insert(leaf.id.clone()) {
Expand Down Expand Up @@ -188,11 +181,6 @@ impl<'a> Builder<'a> {

/// This iterates over all [`Leaf`]s in the processing queue, parses them and writes the bytes out into a the target.
/// Configure the custom *`MAGIC`*, `Header` flags and a [`Keypair`](crate::crypto::Keypair) using the [`BuilderConfig`] struct.
///
/// ### Errors
/// - Underlying `io` errors
/// - If the optional compression or compression features aren't enabled
/// - If the requirements of a given stage, compression or encryption, are not met. Like not providing a keypair if a [`Leaf`] is to be encrypted.
pub fn dump<W: Write + Seek + Send>(self, mut target: W, config: &BuilderConfig) -> InternalResult<u64> {
let Builder { mut leafs, .. } = self;

Expand Down Expand Up @@ -279,7 +267,7 @@ impl<'a> Builder<'a> {
#[cfg(feature = "crypto")]
if result.sign {
if let Some(keypair) = &config.keypair {
let entry_bytes = result.entry.encode(true)?;
let entry_bytes = result.entry.to_bytes(true)?;
result.data.extend_from_slice(&entry_bytes); // DON"T FORGET TO TRUNCATE IF MODIFICATIONS ARE MADE

// Include registry data in the signature
Expand All @@ -289,7 +277,7 @@ impl<'a> Builder<'a> {
}

// write to registry buffer, this one might include the Signature
let entry_bytes = result.entry.encode(false)?;
let entry_bytes = result.entry.to_bytes(false)?;
registry.write_all(&entry_bytes)?;

// Call the progress callback bound within the [`BuilderConfig`]
Expand Down
14 changes: 7 additions & 7 deletions vach/src/writer/prepared.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Unit of data ready to be inserted into a `Write + Clone` target during Building
pub(crate) struct Prepared {
pub(crate) data: Vec<u8>,
pub(crate) entry: super::RegistryEntry,
#[cfg(feature = "crypto")]
pub(crate) sign: bool,
}
// Unit of data ready to be inserted into a `Write + Clone` target during Building
pub(crate) struct Prepared {
pub(crate) data: Vec<u8>,
pub(crate) entry: super::RegistryEntry,
#[cfg(feature = "crypto")]
pub(crate) sign: bool,
}
Binary file modified vach/test_data/signed/target.vach
Binary file not shown.

0 comments on commit 9608bbc

Please sign in to comment.