From 90f37d33f4a1c8936ab017ed646f6f796400ed4b Mon Sep 17 00:00:00 2001 From: Aditya Bisht Date: Mon, 2 Sep 2024 23:03:15 +0000 Subject: [PATCH] chore: cleanup --- .github/pull_request_template.md | 2 - CODING_GUIDELINES.md | 15 +++-- Cargo.lock | 28 +------- Cargo.toml | 2 - rust-toolchain | 2 +- src/circuit.rs | 108 ++++++++++++++++++------------- src/cryptos.rs | 11 +++- src/node/converters.rs | 2 +- src/parse_email.rs | 20 +++--- 9 files changed, 94 insertions(+), 96 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index a26a5f2..79ffbd1 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,5 +1,3 @@ -# Pull Request Template - ## Description diff --git a/CODING_GUIDELINES.md b/CODING_GUIDELINES.md index 8ad9d39..2a5de17 100644 --- a/CODING_GUIDELINES.md +++ b/CODING_GUIDELINES.md @@ -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`. @@ -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";` @@ -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: @@ -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. @@ -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. - - diff --git a/Cargo.lock b/Cargo.lock index 1814e06..abe9885 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,9 +97,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.81" +version = "0.1.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" +checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1" dependencies = [ "proc-macro2", "quote", @@ -1195,16 +1195,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "fancy-regex" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2" -dependencies = [ - "bit-set", - "regex", -] - [[package]] name = "fancy-regex" version = "0.13.0" @@ -2852,7 +2842,6 @@ dependencies = [ "base64 0.21.7", "cfdkim", "ethers", - "fancy-regex 0.11.0", "file-rotate", "halo2curves", "hex", @@ -2868,7 +2857,6 @@ dependencies = [ "rsa", "serde", "serde_json", - "serde_regex", "slog", "slog-async", "slog-json", @@ -3267,16 +3255,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_regex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8136f1a4ea815d7eac4101cfd0b16dc0cb5e1fe1b8609dfd728058656b7badf" -dependencies = [ - "regex", - "serde", -] - [[package]] name = "serde_spanned" version = "0.6.7" @@ -4485,7 +4463,7 @@ name = "zk-regex-apis" version = "2.1.1" source = "git+https://github.com/zkemail/zk-regex.git#3b626316b07081378ffdca0d36ed2bec6df5b55a" dependencies = [ - "fancy-regex 0.13.0", + "fancy-regex", "itertools 0.13.0", "js-sys", "serde", diff --git a/Cargo.toml b/Cargo.toml index ff5d8ec..6477f22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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", @@ -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" } diff --git a/rust-toolchain b/rust-toolchain index 837f16a..4fa580b 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1 +1 @@ -1.73.0 \ No newline at end of file +1.80.1 \ No newline at end of file diff --git a/src/circuit.rs b/src/circuit.rs index bc1717b..d8617d8 100644 --- a/src/circuit.rs +++ b/src/circuit.rs @@ -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, // The email body in bytes + pub header: Vec, // 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, // Selector for SHA-256 precomputation + pub max_header_length: Option, // The maximum length of the email header + pub max_body_length: Option, // The maximum length of the email body + pub ignore_body_hash_check: Option, // 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, - header: Vec, - body_hash_idx: usize, - rsa_signature: BigInt, - rsa_public_key: BigInt, - sha_precompute_selector: Option, - max_header_length: Option, - max_body_length: Option, - ignore_body_hash_check: Option, - ) -> 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), } } } @@ -203,21 +211,33 @@ pub async fn generate_email_circuit_input( params: Option, ) -> Result { // 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)?; diff --git a/src/cryptos.rs b/src/cryptos.rs index 422d0f3..b7823a0 100644 --- a/src/cryptos.rs +++ b/src/cryptos.rs @@ -15,6 +15,11 @@ use crate::{ MAX_EMAIL_ADDR_BYTES, }; +type ShaResult = Vec; // The result of a SHA-256 hash operation. +type RemainingBody = Vec; // 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>; // 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); @@ -324,14 +329,14 @@ pub fn partial_sha(msg: &[u8], msg_len: usize) -> Vec { /// /// # 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`. pub fn generate_partial_sha( body: Vec, body_length: usize, selector_string: Option, max_remaining_body_length: usize, -) -> Result<(Vec, Vec, usize), Box> { +) -> PartialShaResult { let mut selector_index = 0; if let Some(selector_str) = selector_string { diff --git a/src/node/converters.rs b/src/node/converters.rs index 3a4ae95..e6eedd6 100644 --- a/src/node/converters.rs +++ b/src/node/converters.rs @@ -62,7 +62,7 @@ pub(crate) fn bytes_to_fields_node(mut cx: FunctionContext) -> JsResult // 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)?; } diff --git a/src/parse_email.rs b/src/parse_email.rs index 5994c09..ca277e3 100644 --- a/src/parse_email.rs +++ b/src/parse_email.rs @@ -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, ®ex_config)?[0] + } else if self.need_soft_line_breaks() { + extract_substr_idxes(&self.cleaned_body, ®ex_config)?[0] } else { - if self.need_soft_line_breaks() { - extract_substr_idxes(&self.cleaned_body, ®ex_config)?[0] - } else { - extract_substr_idxes(&self.canonicalized_body, ®ex_config)?[0] - } + extract_substr_idxes(&self.canonicalized_body, ®ex_config)?[0] }; let str = self.canonicalized_body[idxes.0..idxes.1].to_string(); Ok(str) @@ -172,14 +170,12 @@ impl ParsedEmail { if ignore_body_hash_check { let idxes = extract_substr_idxes(&self.canonicalized_header, ®ex_config)?[0]; Ok(idxes) + } else if self.need_soft_line_breaks() { + let idxes = extract_substr_idxes(&self.cleaned_body, ®ex_config)?[0]; + Ok(idxes) } else { - if self.need_soft_line_breaks() { - let idxes = extract_substr_idxes(&self.cleaned_body, ®ex_config)?[0]; - Ok(idxes) - } else { - let idxes = extract_substr_idxes(&self.canonicalized_body, ®ex_config)?[0]; - Ok(idxes) - } + let idxes = extract_substr_idxes(&self.canonicalized_body, ®ex_config)?[0]; + Ok(idxes) } }