Skip to content

Commit

Permalink
chore: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Bisht13 committed Sep 2, 2024
1 parent 304019a commit 90f37d3
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 96 deletions.
2 changes: 0 additions & 2 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# Pull Request Template

## Description
<!-- Please include a summary of the change and which issue is fixed. Also, list any dependencies that are required for this change. -->

Expand Down
15 changes: 9 additions & 6 deletions CODING_GUIDELINES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This document outlines the coding guidelines for contributing to Relayer Utils.

## 1. Code Formatting

- **Tool**: Use `rustfmt` to automatically format your code. Ensure that all code is formatted before committing.
- **Tool**: Use `rustfmt` to automatically format your code. Ensure that all code is formatted before committing. Run `cargo fmt` to format your code according to the project's style guidelines.
- **Indentation**: Use 4 spaces per indentation level. Do not use tabs.
- **Line Length**: Aim to keep lines under 100 characters, but it's not a strict rule. Use your judgment to ensure readability.
- **Imports**: Group imports into four sections: `extern crate`, `use`, `use crate`, and `use super`.
Expand Down Expand Up @@ -37,7 +37,12 @@ This document outlines the coding guidelines for contributing to Relayer Utils.
- **Code Duplication**: Avoid duplicating code. If you find yourself copying and pasting code, consider refactoring it into a shared function or module.
- **No warnings**: Ensure that your code compiles without warnings. Fix any warnings before committing.

## 2. Naming Conventions
## 2. Code Linting

- **Tool**: Use `cargo clippy` to lint your code and catch common mistakes and improve your Rust code. Run `cargo clippy` before committing your code to ensure it adheres to Rust's best practices and the project's specific requirements.
- **Handling Lints**: Address all warnings and errors reported by `clippy`. If you must ignore a lint, use `#[allow(clippy::lint_name)]` and provide a comment explaining why.

## 3. Naming Conventions

- **Variables and Functions**: Use `snake_case`.
- Example: `let user_name = "Alice";`
Expand All @@ -48,7 +53,7 @@ This document outlines the coding guidelines for contributing to Relayer Utils.
- **Module Names**: Use `snake_case`.
- Example: `mod user_account;`

## 3. Documentation
## 4. Documentation

- **Public Items**: All public functions, structs, and modules must have documentation comments using `///`.
- Example:
Expand All @@ -75,7 +80,7 @@ This document outlines the coding guidelines for contributing to Relayer Utils.
// module contents
```

## 4. Error Handling
## 5. Error Handling

- **Use of `Result` and `Option`**:
- Use `Result` for operations that can fail and `Option` for values that may or may not be present.
Expand All @@ -91,5 +96,3 @@ This document outlines the coding guidelines for contributing to Relayer Utils.
```
- **Custom Error Types**: When appropriate, define custom error types using `enum` and implement the `anyhow::Error` trait.
- **Error Propagation**: Propagate errors using `?` where possible to simplify error handling.


28 changes: 3 additions & 25 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ itertools = "0.10.3"
serde_json = "1.0.95"
serde = { version = "1.0.159", features = ["derive"] }
zk-regex-apis = { version = "2.1.1", git = "https://github.com/zkemail/zk-regex.git" }
fancy-regex = "0.11.0"
hex = "0.4.3"
tokio = { version = "1.16", features = [
"net",
Expand All @@ -23,7 +22,6 @@ tokio = { version = "1.16", features = [
"rt-multi-thread",
"macros",
] }
serde_regex = "1.1.0"
anyhow = "1.0.75"
once_cell = "1.18.0"
poseidon-rs = { git = "https://github.com/zkemail/poseidon-rs.git", version = "1.0.0" }
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.73.0
1.80.1
108 changes: 64 additions & 44 deletions src/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,48 +67,56 @@ pub struct CircuitInputParams {
ignore_body_hash_check: bool, // Flag to ignore the body hash check
}

pub struct CircuitParams {
pub body: Vec<u8>, // The email body in bytes
pub header: Vec<u8>, // The email header in bytes
pub body_hash_idx: usize, // The index of the body hash in the header
pub rsa_signature: BigInt, // The RSA signature as a BigInt
pub rsa_public_key: BigInt, // The RSA public key as a BigInt
}

pub struct CircuitOptions {
pub sha_precompute_selector: Option<String>, // Selector for SHA-256 precomputation
pub max_header_length: Option<usize>, // The maximum length of the email header
pub max_body_length: Option<usize>, // The maximum length of the email body
pub ignore_body_hash_check: Option<bool>, // Flag to ignore the body hash check
}

impl CircuitInputParams {
/// Creates a new `CircuitInputParams` instance with provided values or default ones.
/// Creates a new `CircuitInputParams` instance with provided parameters and options.
///
/// # Arguments
///
/// * `body` - A vector of bytes representing the email body.
/// * `header` - A vector of bytes representing the email header.
/// * `body_hash_idx` - The index of the body hash within the circuit.
/// * `rsa_signature` - The RSA signature as a BigInt.
/// * `rsa_public_key` - The RSA public key as a BigInt.
/// * `sha_precompute_selector` - Optional selector for SHA-256 precomputation.
/// * `max_header_length` - Optional maximum length of the email header.
/// * `max_body_length` - Optional maximum length of the email body.
/// * `ignore_body_hash_check` - Optional flag to ignore the body hash check.
/// * `params` - A `CircuitParams` struct containing:
/// * `body`: A vector of bytes representing the email body.
/// * `header`: A vector of bytes representing the email header.
/// * `body_hash_idx`: The index of the body hash within the circuit.
/// * `rsa_signature`: The RSA signature as a BigInt.
/// * `rsa_public_key`: The RSA public key as a BigInt.
///
/// * `options` - A `CircuitOptions` struct containing optional parameters:
/// * `sha_precompute_selector`: Selector for SHA-256 precomputation.
/// * `max_header_length`: Maximum length of the email header, with a default value if not provided.
/// * `max_body_length`: Maximum length of the email body, with a default value if not provided.
/// * `ignore_body_hash_check`: Flag to ignore the body hash check, defaults to false if not provided.
///
/// # Returns
///
/// A `CircuitInputParams` instance with the specified or default parameters.
pub fn new(
body: Vec<u8>,
header: Vec<u8>,
body_hash_idx: usize,
rsa_signature: BigInt,
rsa_public_key: BigInt,
sha_precompute_selector: Option<String>,
max_header_length: Option<usize>,
max_body_length: Option<usize>,
ignore_body_hash_check: Option<bool>,
) -> Self {
/// A `CircuitInputParams` instance with the specified parameters and options applied.
pub fn new(params: CircuitParams, options: CircuitOptions) -> Self {
CircuitInputParams {
body,
header,
body_hash_idx,
rsa_signature,
rsa_public_key,
sha_precompute_selector,
body: params.body,
header: params.header,
body_hash_idx: params.body_hash_idx,
rsa_signature: params.rsa_signature,
rsa_public_key: params.rsa_public_key,
sha_precompute_selector: options.sha_precompute_selector,
// Use the provided max_header_length or default to MAX_HEADER_PADDED_BYTES
max_header_length: max_header_length.unwrap_or(MAX_HEADER_PADDED_BYTES),
max_header_length: options.max_header_length.unwrap_or(MAX_HEADER_PADDED_BYTES),
// Use the provided max_body_length or default to MAX_BODY_PADDED_BYTES
max_body_length: max_body_length.unwrap_or(MAX_BODY_PADDED_BYTES),
max_body_length: options.max_body_length.unwrap_or(MAX_BODY_PADDED_BYTES),
// Use the provided ignore_body_hash_check or default to false
ignore_body_hash_check: ignore_body_hash_check.unwrap_or(false),
ignore_body_hash_check: options.ignore_body_hash_check.unwrap_or(false),
}
}
}
Expand Down Expand Up @@ -203,21 +211,33 @@ pub async fn generate_email_circuit_input(
params: Option<EmailCircuitParams>,
) -> Result<String> {
// Parse the raw email to extract canonicalized body and header, and other components
let parsed_email = ParsedEmail::new_from_raw_email(&email).await?;
// Create circuit input parameters from the parsed email and optional parameters
let circuit_input_params = CircuitInputParams::new(
parsed_email.canonicalized_body.as_bytes().to_vec(),
parsed_email.canonicalized_header.as_bytes().to_vec(),
parsed_email.get_body_hash_idxes()?.0,
vec_u8_to_bigint(parsed_email.clone().signature),
vec_u8_to_bigint(parsed_email.clone().public_key),
params
let parsed_email = ParsedEmail::new_from_raw_email(email).await?;

// Clone the fields that are used by value before the move occurs
let public_key = parsed_email.public_key.clone();
let signature = parsed_email.signature.clone();

// Create a CircuitParams struct from the parsed email
let circuit_params = CircuitParams {
body: parsed_email.canonicalized_body.as_bytes().to_vec(),
header: parsed_email.canonicalized_header.as_bytes().to_vec(),
body_hash_idx: parsed_email.get_body_hash_idxes()?.0,
rsa_signature: vec_u8_to_bigint(signature),
rsa_public_key: vec_u8_to_bigint(public_key),
};

// Create a CircuitOptions struct from the optional parameters
let circuit_options = CircuitOptions {
sha_precompute_selector: params
.as_ref()
.and_then(|p| p.sha_precompute_selector.clone()),
params.as_ref().and_then(|p| p.max_header_length),
params.as_ref().and_then(|p| p.max_body_length),
params.as_ref().and_then(|p| p.ignore_body_hash_check),
);
max_header_length: params.as_ref().and_then(|p| p.max_header_length),
max_body_length: params.as_ref().and_then(|p| p.max_body_length),
ignore_body_hash_check: params.as_ref().and_then(|p| p.ignore_body_hash_check),
};

// Create circuit input parameters from the CircuitParams and CircuitOptions structs
let circuit_input_params = CircuitInputParams::new(circuit_params, circuit_options);

// Generate the circuit inputs from the parameters
let email_circuit_inputs = generate_circuit_inputs(circuit_input_params)?;
Expand Down
11 changes: 8 additions & 3 deletions src/cryptos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ use crate::{
MAX_EMAIL_ADDR_BYTES,
};

type ShaResult = Vec<u8>; // The result of a SHA-256 hash operation.
type RemainingBody = Vec<u8>; // The remaining part of a message after a SHA-256 hash operation.
type RemainingBodyLength = usize; // The length of the remaining message body in bytes.
type PartialShaResult = Result<(ShaResult, RemainingBody, RemainingBodyLength), Box<dyn Error>>; // The result of a partial SHA-256 hash operation, including the hash, remaining body, and its length, or an error.

#[derive(Debug, Clone, Copy)]
/// `RelayerRand` is a single field element representing a random value.
pub struct RelayerRand(pub Fr);
Expand Down Expand Up @@ -324,14 +329,14 @@ pub fn partial_sha(msg: &[u8], msg_len: usize) -> Vec<u8> {
///
/// # Returns
///
/// A result containing a tuple of the precomputed SHA-256 hash, the remaining body, and its length,
/// or an error if the selector is not found or the remaining body is too long.
/// A tuple containing the SHA-256 hash of the pre-selector part of the message, the remaining body after the selector, and its length.
/// If an error occurs, it is returned as a `Box<dyn Error>`.
pub fn generate_partial_sha(
body: Vec<u8>,
body_length: usize,
selector_string: Option<String>,
max_remaining_body_length: usize,
) -> Result<(Vec<u8>, Vec<u8>, usize), Box<dyn Error>> {
) -> PartialShaResult {
let mut selector_index = 0;

if let Some(selector_str) = selector_string {
Expand Down
2 changes: 1 addition & 1 deletion src/node/converters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub(crate) fn bytes_to_fields_node(mut cx: FunctionContext) -> JsResult<JsArray>

// Populate the JavaScript array with the field elements.
for (i, field) in fields.into_iter().enumerate() {
let field = cx.string(&field_to_hex(&field));
let field = cx.string(field_to_hex(&field));
js_array.set(&mut cx, i as u32, field)?;
}

Expand Down
20 changes: 8 additions & 12 deletions src/parse_email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,10 @@ impl ParsedEmail {
let regex_config = serde_json::from_str(include_str!("../regexes/invitation_code.json"))?;
let idxes = if ignore_body_hash_check {
extract_substr_idxes(&self.canonicalized_header, &regex_config)?[0]
} else if self.need_soft_line_breaks() {
extract_substr_idxes(&self.cleaned_body, &regex_config)?[0]
} else {
if self.need_soft_line_breaks() {
extract_substr_idxes(&self.cleaned_body, &regex_config)?[0]
} else {
extract_substr_idxes(&self.canonicalized_body, &regex_config)?[0]
}
extract_substr_idxes(&self.canonicalized_body, &regex_config)?[0]
};
let str = self.canonicalized_body[idxes.0..idxes.1].to_string();
Ok(str)
Expand All @@ -172,14 +170,12 @@ impl ParsedEmail {
if ignore_body_hash_check {
let idxes = extract_substr_idxes(&self.canonicalized_header, &regex_config)?[0];
Ok(idxes)
} else if self.need_soft_line_breaks() {
let idxes = extract_substr_idxes(&self.cleaned_body, &regex_config)?[0];
Ok(idxes)
} else {
if self.need_soft_line_breaks() {
let idxes = extract_substr_idxes(&self.cleaned_body, &regex_config)?[0];
Ok(idxes)
} else {
let idxes = extract_substr_idxes(&self.canonicalized_body, &regex_config)?[0];
Ok(idxes)
}
let idxes = extract_substr_idxes(&self.canonicalized_body, &regex_config)?[0];
Ok(idxes)
}
}

Expand Down

0 comments on commit 90f37d3

Please sign in to comment.