Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoding params from contract #117

Merged
merged 12 commits into from
Sep 30, 2024
Merged

Decoding params from contract #117

merged 12 commits into from
Sep 30, 2024

Conversation

ryardley
Copy link
Contributor

@ryardley ryardley commented Sep 27, 2024

Closes: #115

  • Replace u64 with Seed type that is based on [u8;32]
  • Add EnclaveError event bus event
  • Use packed tuple format for params
  • Fixed mocks within tests
  • Ensure CRP is created based on E3Request seed
  • Added test for encoding and decoding
  • Ensured enclave errors are dispatched locally on the event bus if evm events fail to parse
  • Changed contract MockE3Program to pass integration test.
  • Updated Enclave.spec.ts to work with MockE3Program contract changes.
  • Tidy up

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new command-line utility for encoding BFV parameters and generating random CRP.
    • Enhanced error handling for event processing in the EVM event listener.
    • Added new methods for encoding and decoding E3 parameters.
    • Updated event structures to utilize a new Seed type for better type safety.
  • Bug Fixes

    • Improved validation logic in the MockE3Program contract.
  • Documentation

    • Added and updated test cases to reflect changes in encoding and decoding logic.
  • Chores

    • Updated scripts to reflect changes in binary names and build processes.
    • Modified .gitignore to exclude additional file types.

Copy link
Contributor

coderabbitai bot commented Sep 27, 2024

Walkthrough

The changes across multiple files primarily focus on enhancing type safety by replacing the u64 type with a new Seed type for various fields, particularly related to event handling and cryptographic operations. The modifications also include the introduction of new error handling mechanisms, encoding and decoding functions, and adjustments to the event processing logic. Overall, the updates streamline the code structure and improve the management of parameters and events within the system.

Changes

File Path Change Summary
packages/ciphernode/core/src/committee_meta.rs, packages/ciphernode/core/src/plaintext_aggregator.rs, packages/ciphernode/core/src/publickey_aggregator.rs Updated seed field from u64 to Seed type in multiple structs, enhancing type safety.
packages/ciphernode/core/src/events.rs Added new EnclaveError variant and EnclaveErrorType enum, modified E3Requested struct to include Seed type, and introduced FromError trait for error conversions.
packages/ciphernode/core/src/evm_enclave.rs Changed From implementation for E3Requested to TryFrom, added decode_e3_params and encode_e3_params functions for parameter handling.
packages/ciphernode/core/src/evm_listener.rs Enhanced error handling in EvmEventListener to send EnclaveEvent on errors.
packages/ciphernode/core/src/fhe.rs Introduced from_encoded method in Fhe struct, updated FheFactory to accept SharedRng instead of Arc<Mutex<ChaCha20Rng>.
packages/ciphernode/core/src/keyshare.rs Refactored handle method for CiphernodeSelected to be synchronous, integrating keyshare generation logic directly.
packages/ciphernode/core/src/lib.rs Exported new functions decode_e3_params and encode_e3_params, improved logging capabilities in tests.
packages/ciphernode/core/src/logger.rs Added handling for EnclaveEvent::EnclaveError in SimpleLogger.
packages/ciphernode/core/src/main_aggregator.rs, packages/ciphernode/core/src/main_ciphernode.rs Updated RNG handling to create directly from OsRng, modified connection handling to evm_ciphernode_registry.
packages/ciphernode/core/src/sortition.rs Changed seed field in GetHasNode struct and associated methods from u64 to Seed.
packages/ciphernode/core/src/utils.rs Added encode_bfv_params and decode_params functions for parameter serialization and deserialization.
packages/ciphernode/enclave_node/src/bin/pack_e3_params.rs Introduced a command-line utility for encoding BFV parameters and generating CRP.
packages/evm/contracts/test/MockE3Program.sol Simplified validation logic in validate function, removing length check for e3ProgramParams.
tests/basic_integration/lib/fake_encrypt.sh, tests/basic_integration/lib/prebuild.sh Updated scripts to change the target binary from test_encryptor to fake_encrypt.
tests/basic_integration/test.sh Introduced INPUT_VALIDATOR_CONTRACT environment variable and modified logic for creating a new committee with encoded parameters.

Possibly related PRs

  • Better deploy script  #52: The changes in the main PR regarding the seed field's type change from u64 to Seed in the CommitteeMeta struct are related to the modifications in the PlaintextAggregator and PublicKeyAggregator where similar changes to the seed type are made, enhancing type safety across the codebase.

  • Evm Integration and integration script #107: The integration of the E3Requested event in the events.rs file and its handling in the fhe.rs file aligns with the changes made in this PR, which involve converting EVM events into EnclaveEvents, including the E3Requested event, thus ensuring consistency in event handling across the system.

Suggested reviewers

  • auryn-macmillan
  • nginnever
  • hmzakhalid

Poem

🐇 In the code where rabbits hop,
Seeds now grow, no need to stop.
Events dance with error's grace,
Type safety finds its rightful place.
With each change, we leap and cheer,
A brighter code, let’s hold it dear! 🌱


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ryardley ryardley changed the title Encoding params Decoding params from contract Sep 27, 2024
@ryardley ryardley marked this pull request as ready for review September 30, 2024 12:40
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 16

🧹 Outside diff range and nitpick comments (17)
tests/basic_integration/lib/prebuild.sh (1)

3-3: LGTM, but consider addressing warnings and adding documentation.

The change from test_encryptor to fake_encrypt aligns with the PR objectives, particularly the updates to tests and mocks. However, there are a couple of suggestions to improve the script:

  1. Reconsider using RUSTFLAGS="-A warnings". Suppressing all warnings might hide potential issues. Consider removing this flag or using more specific warning suppressions if absolutely necessary.

  2. Add a comment explaining the purpose of fake_encrypt and why it replaced test_encryptor. This would improve code documentation and make it easier for other developers to understand the change.

Consider applying these changes:

 #!/usr/bin/env sh
 
-cd packages/ciphernode && RUSTFLAGS="-A warnings" cargo build --bin fake_encrypt --bin node --bin aggregator;
+# Change to the ciphernode package directory
+cd packages/ciphernode
+
+# Build the required binaries
+# fake_encrypt: [Add a brief description of its purpose]
+# node: [Add a brief description of its purpose]
+# aggregator: [Add a brief description of its purpose]
+cargo build --bin fake_encrypt --bin node --bin aggregator

This change removes the warning suppression and adds explanatory comments, improving code clarity and potentially catching important warnings during the build process.

packages/evm/contracts/test/MockE3Program.sol (1)

23-26: Good use of abi.decode, consider adding a comment

The replacement of inline assembly with abi.decode improves readability and safety. This is a positive change.

Consider adding a brief comment explaining the structure of e3ProgramParams for better clarity:

+       // e3ProgramParams contains (bytes, IInputValidator)
        (, inputValidator) = abi.decode(
            e3ProgramParams,
            (bytes, IInputValidator)
        );
packages/ciphernode/enclave_node/src/bin/pack_e3_params.rs (3)

6-9: LGTM: Robust hex parsing function.

The parse_hex function correctly handles both "0x" prefixed and non-prefixed hex strings, returning a Result for proper error handling.

Consider adding a check for empty strings to provide a more specific error message:

 fn parse_hex(arg: &str) -> Result<u64, ParseIntError> {
+    if arg.trim().is_empty() {
+        return Err(ParseIntError::new());
+    }
     let without_prefix = arg.trim_start_matches("0x");
     u64::from_str_radix(without_prefix, 16)
 }

11-28: LGTM: Well-structured CLI argument definition.

The Args struct effectively defines the command-line interface for the utility, with appropriate types and help messages for each field.

Consider adding input validation for the degree and plaintext_modulus fields to ensure they are within acceptable ranges. You can use the value_parser attribute with a custom validation function:

fn validate_degree(s: &str) -> Result<u64, String> {
    let degree: u64 = s.parse().map_err(|_| format!("`{}` isn't a valid degree", s))?;
    if degree.is_power_of_two() && degree >= 1024 && degree <= 32768 {
        Ok(degree)
    } else {
        Err(format!("Degree must be a power of 2 between 1024 and 32768"))
    }
}

#[arg(short, long, value_parser = validate_degree)]
degree: u64,

Apply similar validation for plaintext_modulus based on your specific requirements.


30-45: LGTM: Main function implements the core utility logic effectively.

The main function correctly parses arguments, performs basic validation, encodes parameters, and outputs the result.

Consider the following improvements:

  1. Use eprintln! for error messages to separate them from the main output:
-    println!("Parameter `--moduli` must include at least one value");
+    eprintln!("Error: Parameter `--moduli` must include at least one value");
  1. Handle the no_crp flag in the encoding process:
-    let encoded = encode_bfv_params(args.moduli, args.degree, args.plaintext_modulus);
+    let encoded = encode_bfv_params(args.moduli, args.degree, args.plaintext_modulus, !args.no_crp);
  1. Use alloy::hex::encode for consistent hex encoding:
-    for byte in abi_encoded {
-        print!("{:02x}", byte);
-    }
+    println!("{}", alloy::hex::encode(abi_encoded));

These changes will improve error visibility, respect the no_crp flag, and use a consistent hex encoding method.

packages/ciphernode/core/src/utils.rs (2)

48-50: New function for encoding BFV parameters looks good.

The encode_bfv_params function provides a convenient way to encode BFV parameters and reuses the existing setup_bfv_params function, which is good for code maintainability.

Consider using usize for the degree parameter instead of u64 to avoid the cast:

-pub fn encode_bfv_params(moduli: Vec<u64>, degree: u64, plaintext_modulus: u64) -> Vec<u8> {
-    setup_bfv_params(&moduli, degree as usize, plaintext_modulus).to_bytes()
+pub fn encode_bfv_params(moduli: Vec<u64>, degree: usize, plaintext_modulus: u64) -> Vec<u8> {
+    setup_bfv_params(&moduli, degree, plaintext_modulus).to_bytes()

This change would make the function signature more consistent with setup_bfv_params and eliminate the need for the cast.


52-56: New function for decoding BFV parameters is well-implemented.

The decode_params function effectively deserializes BFV parameters from bytes, with good error handling using anyhow::Context. The use of Arc for wrapping the result is appropriate for efficient sharing of the deserialized parameters.

For consistency with the encode_bfv_params function, consider renaming this function to decode_bfv_params:

-pub fn decode_params(bytes: &[u8]) -> Result<Arc<BfvParameters>> {
+pub fn decode_bfv_params(bytes: &[u8]) -> Result<Arc<BfvParameters>> {
     Ok(Arc::new(
         BfvParameters::try_deserialize(bytes).context("Could not decode Bfv Params")?,
     ))
 }

This change would make the function naming more consistent across the module.

packages/ciphernode/core/src/main_aggregator.rs (1)

46-50: Approve RNG creation changes with a suggestion for error handling

The changes to RNG creation look good. Using OsRng directly is a more straightforward approach. However, consider handling the potential failure of RNG creation more gracefully.

Consider replacing the expect call with proper error handling:

let rng = Arc::new(Mutex::new(
    rand_chacha::ChaCha20Rng::from_rng(OsRng).map_err(|e| {
        // Log the error
        log::error!("Failed to create RNG: {}", e);
        // Return a custom error or propagate this error
        YourCustomError::RngCreationFailed(e)
    })?
));

This approach would allow for better error reporting and prevent a potential panic.

packages/ciphernode/core/src/sortition.rs (1)

41-43: LGTM: SortitionModule implementation updated correctly

The contains method implementation in SortitionModule has been successfully updated to use the Seed type. The addition of .into() when passing seed to DistanceSortition::new ensures compatibility with the existing implementation.

Consider caching the result of seed.into() if it's used multiple times within the method to avoid repeated conversions:

let seed_value = seed.into();
DistanceSortition::new(
    seed_value,
    // ... rest of the code
)

This minor optimization could be beneficial if the conversion is computationally expensive or if the method is called frequently.

packages/ciphernode/core/src/plaintext_aggregator.rs (1)

Line range hint 108-186: LGTM: Handler<DecryptionshareCreated> implementation updated.

The implementation correctly uses the seed variable of type Seed in the context of the GetHasNode message. This is consistent with the earlier changes to the PlaintextAggregatorState and constructor.

Consider adding a type annotation for seed when destructuring PlaintextAggregatorState::Collecting for improved readability:

- threshold_m, seed, ..
+ threshold_m, seed: Seed, ..

This change would make the type of seed explicit at the point of use.

packages/ciphernode/core/src/keyshare.rs (2)

58-62: Address the TODO comments related to key encryption and decryption.

The TODO comments indicate pending implementation for decrypting from the FHE actor and re-encrypting the secret key securely. These are crucial for maintaining the security and functionality of the system.

Would you like assistance in implementing the key encryption and decryption logic? I can help by providing code examples or outlining best practices for secure key management.


119-119: Remove unnecessary debug statements.

The println!("\n\nDECRYPTING!\n\n"); statement may clutter the output in a production environment.

Consider removing or replacing it with proper logging if necessary.

-println!("\n\nDECRYPTING!\n\n");
packages/ciphernode/core/src/evm_enclave.rs (1)

Line range hint 96-98: Handle potential errors without using unwrap()

Using unwrap() on asynchronous operations can cause the program to panic if an error occurs. It's better to handle these potential errors gracefully to improve the robustness of the code.

Consider propagating the errors using the ? operator and adjusting the function signature to return a Result:

-pub async fn connect_evm_enclave(bus: Addr<EventBus>, rpc_url: &str, contract_address: Address) {
+pub async fn connect_evm_enclave(bus: Addr<EventBus>, rpc_url: &str, contract_address: Address) -> Result<()> {

  let evm_manager = EvmContractManager::attach(bus.clone(), rpc_url).await;
  let evm_listener = evm_manager
      .send(AddListener { contract_address })
      .await
-     .unwrap();
+     ?;

  evm_listener
      .send(AddEventHandler::<E3Requested>::new())
      .await
-     .unwrap();
+     ?;

  evm_listener
      .send(AddEventHandler::<CiphertextOutputPublished>::new())
      .await
-     .unwrap();
+     ?;

  evm_listener.do_send(StartListening);

  println!("Evm is listening to {}", contract_address);
+ Ok(())
}

This change ensures that any errors encountered during the asynchronous calls are properly propagated to the caller for handling.

Also applies to: 101-103, 105-108

tests/basic_integration/test.sh (2)

18-18: Convert inline comment to a TODO for clarity

The comment on line 18 suggests a potential enhancement. Converting it to a TODO comment will make the intended action clearer and help in tracking it.

Apply this diff:

-# We _may_ wish to get these off the hardhat environment somehow?
+# TODO: Retrieve these contract addresses from the hardhat environment

21-21: Add descriptive comment for INPUT_VALIDATOR_CONTRACT

Providing context for the INPUT_VALIDATOR_CONTRACT environment variable will improve readability and maintainability.

Consider adding a comment:

+# Address of the input validator contract
export INPUT_VALIDATOR_CONTRACT="0x8A791620dd6260079BF849Dc5567aDC3F2FdC318"
packages/ciphernode/core/src/events.rs (2)

388-394: Use consistent casing for enum variants to follow Rust conventions.

Consider renaming the enum variants to use UpperCamelCase for better readability and to align with Rust naming conventions. For example, rename PublickeyAggregation to PublicKeyAggregation, and IO to Io.

Apply this diff to rename the variants:

 pub enum EnclaveErrorType {
-    Evm,
-    KeyGeneration,
-    PublickeyAggregation,
-    IO,
-    PlaintextAggregation,
-    Decryption,
+    Evm,
+    KeyGeneration,
+    PublicKeyAggregation,
+    Io,
+    PlaintextAggregation,
+    Decryption,
}

256-263: Avoid unnecessary cloning to improve performance.

In the From<EnclaveError> for EnclaveEvent implementation, cloning data may be unnecessary if ownership can be transferred. Consider removing the clones to enhance efficiency.

Apply this diff to eliminate unnecessary clones:

 impl From<EnclaveError> for EnclaveEvent {
     fn from(data: EnclaveError) -> Self {
         EnclaveEvent::EnclaveError {
-            id: EventId::from(data.clone()),
-            data: data.clone(),
+            id: EventId::from(&data),
+            data,
         }
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cf50fd6 and 002607c.

📒 Files selected for processing (22)
  • packages/ciphernode/core/src/committee_meta.rs (1 hunks)
  • packages/ciphernode/core/src/events.rs (7 hunks)
  • packages/ciphernode/core/src/evm_enclave.rs (4 hunks)
  • packages/ciphernode/core/src/evm_listener.rs (2 hunks)
  • packages/ciphernode/core/src/fhe.rs (3 hunks)
  • packages/ciphernode/core/src/keyshare.rs (3 hunks)
  • packages/ciphernode/core/src/lib.rs (10 hunks)
  • packages/ciphernode/core/src/logger.rs (1 hunks)
  • packages/ciphernode/core/src/main_aggregator.rs (1 hunks)
  • packages/ciphernode/core/src/main_ciphernode.rs (2 hunks)
  • packages/ciphernode/core/src/plaintext_aggregator.rs (3 hunks)
  • packages/ciphernode/core/src/publickey_aggregator.rs (4 hunks)
  • packages/ciphernode/core/src/sortition.rs (2 hunks)
  • packages/ciphernode/core/src/utils.rs (2 hunks)
  • packages/ciphernode/enclave_node/src/bin/pack_e3_params.rs (1 hunks)
  • packages/evm/contracts/test/MockE3Program.sol (1 hunks)
  • packages/evm/test/Enclave.spec.ts (5 hunks)
  • tests/basic_integration/lib/fake_encrypt.sh (1 hunks)
  • tests/basic_integration/lib/pack_e3_params.sh (1 hunks)
  • tests/basic_integration/lib/prebuild.sh (1 hunks)
  • tests/basic_integration/output/.gitignore (1 hunks)
  • tests/basic_integration/test.sh (3 hunks)
🔇 Additional comments (55)
tests/basic_integration/output/.gitignore (1)

3-3: LGTM: Addition of *.hex to .gitignore is appropriate.

The inclusion of *.hex in the .gitignore file is a good practice. It ensures that hexadecimal output files, which are likely generated during the testing process, are not tracked by version control. This aligns well with the existing entries and the overall purpose of the .gitignore file in this directory.

To ensure we're not missing any other file types that might need to be ignored, let's check the output directory for any other file extensions:

tests/basic_integration/lib/pack_e3_params.sh (2)

1-1: LGTM: Correct shebang for a bash script.

The shebang line is correctly written, using the portable /usr/bin/env bash approach.


3-3: 🛠️ Refactor suggestion

Consider improving script robustness and readability.

The script successfully changes directory, sets RUSTFLAGS, and runs the Rust binary. However, there are a few points to consider:

  1. Error handling: The script doesn't handle potential errors if the directory change fails. Consider adding error checking.

  2. Readability: The line is quite long. Consider breaking it into multiple lines for better readability.

  3. Warning suppression: Suppressing all warnings with -A warnings might hide important information. Is this intentional for all use cases of this script?

Here's a suggested refactor for improved robustness and readability:

-cd packages/ciphernode && RUSTFLAGS="-A warnings" cargo run --bin pack_e3_params -- "$@" 
+#!/usr/bin/env bash
+
+set -e  # Exit immediately if a command exits with a non-zero status
+
+cd packages/ciphernode || exit 1
+
+RUSTFLAGS="-A warnings" cargo run --bin pack_e3_params -- "$@"

Could you clarify the intended use of this script and whether suppressing all warnings is necessary? This will help determine if additional modifications are needed.

packages/ciphernode/core/src/committee_meta.rs (3)

3-7: LGTM: CommitteeMeta struct updated correctly

The seed field in the CommitteeMeta struct has been updated from u64 to Seed as per the PR objectives. This change likely improves type safety by using a more specific type for the seed value.


Line range hint 9-27: Verify compatibility with E3Requested event

The CommitteeMetaFactory::create method remains unchanged, which suggests that the E3Requested event now provides a Seed type for the seed field. This is good for maintaining compatibility.

To ensure that the E3Requested event has been updated accordingly, please run the following script:

#!/bin/bash
# Description: Verify E3Requested event compatibility with Seed type

# Test: Check E3Requested struct definition
echo "Checking E3Requested struct definition:"
rg --type rust -A 10 "struct E3Requested" | rg "seed:\s*Seed"

1-1: Verify the Seed type implementation

The Seed type is now imported and used in this file. This change aligns with the PR objectives of replacing u64 with a new Seed type.

To ensure the Seed type is correctly implemented and used consistently across the codebase, please run the following script:

✅ Verification successful

Seed type implementation is correct

The Seed type is properly defined as a struct and used consistently across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the Seed type implementation and usage

# Test 1: Check the Seed type definition
echo "Checking Seed type definition:"
rg --type rust "type Seed = \[u8; 32\]" || rg --type rust "struct Seed"

# Test 2: Verify consistent usage of Seed type
echo "Verifying consistent usage of Seed type:"
rg --type rust "\bSeed\b"

Length of output: 2966

packages/evm/contracts/test/MockE3Program.sol (2)

20-22: Confirm the strict length requirement for computeProviderParams

The check for computeProviderParams now requires an exact length of 32 bytes. This aligns with the PR objective of using a new Seed type, but it's more restrictive than before.

To verify if this change is consistent across the codebase:

#!/bin/bash
# Search for other occurrences of computeProviderParams to ensure consistent length checks
rg --type solidity "computeProviderParams" -C 5

20-22: Verify the impact of removing e3ProgramParams length check

The removal of the length check for e3ProgramParams could potentially allow malformed input. Please ensure that this change doesn't introduce vulnerabilities and that e3ProgramParams is properly validated elsewhere if necessary.

To verify the usage and validation of e3ProgramParams:

packages/ciphernode/enclave_node/src/bin/pack_e3_params.rs (2)

1-4: LGTM: Imports are appropriate and concise.

The imports cover all necessary dependencies for the command-line utility, including hex conversion, argument parsing, and core encoding functions.


1-45: Overall: Well-implemented utility with room for minor improvements.

This new file successfully implements a command-line utility for encoding BFV parameters and generating a random CRP. The code is well-structured, uses appropriate libraries, and follows Rust best practices.

Key strengths:

  1. Effective use of the clap library for argument parsing.
  2. Good error handling with Result types.
  3. Clear separation of concerns between argument parsing, parameter encoding, and output.

Areas for improvement:

  1. Enhanced input validation for numeric parameters.
  2. More consistent error handling and messaging.
  3. Utilization of the no_crp flag in the encoding process.
  4. Improved output formatting using standard library functions.

These improvements will enhance the robustness and user-friendliness of the utility.

To ensure the encode_bfv_params and encode_e3_params functions are correctly implemented in the enclave_core module, please run the following verification script:

packages/ciphernode/core/src/logger.rs (2)

46-46: Improved log formatting consistency.

The removal of the extra newline character at the end of the log message for the E3Requested event improves the consistency of log formatting across different event types. This change enhances the readability of the logs.


48-49: Enhanced error handling with EnclaveError logging.

The addition of specific handling for the EnclaveError event type improves the error reporting capabilities of the logger. This change aligns well with the PR objectives of enhancing error management. The log message format is consistent with other event types, maintaining overall code style consistency.

packages/ciphernode/core/src/utils.rs (2)

2-2: Improved error handling and serialization capabilities.

The addition of anyhow for error handling and Deserialize trait is a positive change:

  1. anyhow allows for more descriptive error contexts, enhancing error handling capabilities.
  2. Including Deserialize alongside Serialize enables full serialization cycle, which is consistent with the new decoding functionality introduced.

These changes improve the robustness and flexibility of the code.

Also applies to: 7-7


Line range hint 1-57: Overall, the changes enhance the utility and robustness of the module.

The modifications to this file improve error handling, add serialization capabilities, and introduce new utility functions for encoding and decoding BFV parameters. These changes align well with the PR objectives, particularly in optimizing data storage and retrieval.

Key improvements:

  1. Enhanced error handling with anyhow.
  2. Added serialization and deserialization capabilities for BFV parameters.
  3. New utility functions that complement existing functionality.

These changes contribute to a more robust and flexible implementation, which should improve the overall reliability and maintainability of the codebase.

packages/ciphernode/core/src/main_aggregator.rs (1)

58-58: Approve the direct use of rng in FheFactory::create

The change to directly pass rng to FheFactory::create is a good optimization. It removes a redundant clone operation and ensures that all components use the same RNG instance, which can be important for reproducibility and potentially for security reasons.

packages/ciphernode/core/src/main_ciphernode.rs (2)

5-6: LGTM: Import statements reordered.

The reordering of import statements doesn't affect the functionality and is likely due to code formatting. This change improves code readability.


68-68: Verify thread safety and impact of direct rng usage in FheFactory.

The change from passing a cloned rng to passing it directly could affect how randomness is managed within the factory. Please confirm:

  1. Is rng used elsewhere in the code?
  2. Does this change maintain thread safety?
  3. Are there any implications for determinism in random number generation?

To help verify this change, you can run the following script to check for other usages of rng and potential thread safety issues:

#!/bin/bash
# Description: Check for other usages of rng and potential thread safety issues

# Search for other usages of rng
rg --type rust "\brng\b"

# Search for potential thread safety issues related to rng
rg --type rust -e "Mutex.*rng" -e "RwLock.*rng" -e "Arc.*rng"
packages/ciphernode/core/src/sortition.rs (4)

6-6: LGTM: Import statement updated correctly

The addition of the Seed type to the import statement is consistent with the changes made throughout the file. This update ensures that the new Seed type is available for use in the module.


11-11: LGTM: GetHasNode struct updated correctly

The seed field type in the GetHasNode struct has been successfully updated from u64 to Seed. This change enhances type safety and is consistent with the PR objectives of replacing u64 with the new Seed type.


17-17: LGTM: SortitionList trait updated correctly

The contains method signature in the SortitionList trait has been properly updated to use Seed instead of u64 for the seed parameter. This change maintains the trait's interface while improving type safety, aligning with the PR objectives.


Line range hint 1-124: Summary: Successful migration from u64 to Seed type

The changes in this file successfully replace the u64 type with the new Seed type for the seed field and related parameters. This modification enhances type safety and aligns well with the PR objectives. The changes are consistent throughout the file, affecting the GetHasNode struct, SortitionList trait, and SortitionModule implementation.

Key points:

  1. Import statement updated to include Seed.
  2. GetHasNode struct's seed field type changed to Seed.
  3. SortitionList trait's contains method signature updated.
  4. SortitionModule implementation adapted to use Seed with appropriate conversion.

These changes improve the overall type safety of the sortition module without altering its core functionality. The code remains clean and readable, with only minor suggestions for optimization.

packages/ciphernode/core/src/plaintext_aggregator.rs (4)

4-4: LGTM: Import of Seed type added.

The addition of Seed to the import list is consistent with the changes described in the PR objectives and AI summary. This import is necessary for using the new Seed type throughout the file.


14-14: Approved: Enhanced type safety with Seed.

The change from u64 to Seed for the seed field in the Collecting variant of PlaintextAggregatorState aligns with the PR objectives. This modification enhances type safety and clarifies the intent of the code by using a more specific type for cryptographic operations.


Line range hint 188-224: LGTM: PlaintextAggregatorFactory::create consistent with Seed changes.

The usage of meta.seed in the PlaintextAggregatorFactory::create method is consistent with the changes to use the Seed type. No explicit type changes were needed in this method as it relies on the meta struct.

To ensure the meta struct has been updated to use the Seed type for its seed field, run the following script:

#!/bin/bash
# Description: Verify the meta struct definition uses Seed type for seed field

# Test: Search for the meta struct definition
ast-grep --lang rust --pattern 'struct $META_NAME {
  $$$
  seed: $SEED_TYPE,
  $$$
}'

This will help confirm that the meta struct is correctly using the Seed type for its seed field.


49-49: LGTM: Constructor updated for Seed type.

The modification of the new method to accept seed: Seed instead of u64 is consistent with the changes in the PlaintextAggregatorState enum. This ensures type consistency throughout the struct and its associated methods.

To ensure all usages of PlaintextAggregator::new have been updated, run the following script:

packages/ciphernode/core/src/publickey_aggregator.rs (5)

8-8: LGTM: Import statement updated correctly.

The addition of the Seed import is consistent with the changes described in the PR objectives and AI summary. This import is necessary for using the new Seed type throughout the file.


18-18: Approved: Enhanced type safety in PublicKeyAggregatorState enum.

The change from u64 to Seed for the seed field in the Collecting variant of PublicKeyAggregatorState aligns with the PR objectives. This modification improves type safety by using a more specific and descriptive type for the seed.


56-56: LGTM: Constructor updated consistently with Seed type.

The change in the PublicKeyAggregator::new method to use Seed instead of u64 for the seed parameter is consistent with the earlier modifications. This update ensures that the constructor aligns with the new type used in the PublicKeyAggregatorState enum, maintaining consistency throughout the struct.


Line range hint 1-225: Summary: Successful implementation of Seed type.

The changes in this file successfully implement the new Seed type, replacing the previous u64 type for seed-related fields and parameters. These modifications enhance type safety and consistency throughout the PublicKeyAggregator implementation. The changes align well with the PR objectives and maintain the overall logic of the aggregator.

Key points:

  1. Import statements have been updated to include the new Seed type.
  2. The PublicKeyAggregatorState enum now uses Seed instead of u64.
  3. The PublicKeyAggregator::new method has been updated to accept Seed as a parameter.
  4. The PublicKeyAggregatorFactory::create method now passes the Seed type directly.

These changes contribute to a more robust and type-safe implementation of the public key aggregation process.


Line range hint 225-225: LGTM: Factory method updated to use Seed type.

The change in the PublicKeyAggregatorFactory::create method to pass meta.seed directly to PublicKeyAggregator::new is consistent with the earlier modifications. This update ensures that the factory method uses the new Seed type when creating a PublicKeyAggregator instance.

To ensure type consistency, please verify that meta.seed is indeed of type Seed. Run the following script to check the type of meta.seed:

This will help confirm that meta.seed is correctly defined as Seed type in the Meta struct or its usage context.

packages/ciphernode/core/src/evm_listener.rs (1)

15-15: [Approved] Necessary imports added for enhanced error handling

The addition of EnclaveErrorType, EnclaveEvent, and FromError imports is appropriate and necessary for the new error handling logic implemented below. These imports ensure that the code can properly construct and send error events to the event bus.

packages/ciphernode/core/src/keyshare.rs (2)

119-124: Verify that errors from decrypt_ciphertext are properly propagated and handled.

The decrypt_ciphertext method may return errors, and using the ? operator will propagate them. Ensure that these errors are adequately handled to prevent unhandled exceptions.

Please confirm that the calling context of on_decryption_requested properly handles potential errors without causing the application to panic.


83-87: ⚠️ Potential issue

Handle errors gracefully instead of using unwrap() on asynchronous operations.

Using .unwrap() on the await of on_decryption_requested can cause the actor to panic if an error occurs, leading to potential application crashes.

Modify the code to handle the potential error:

Box::pin(async move {
-    on_decryption_requested(fhe, data, bus, event, address)
-        .await
-        .unwrap()
+    if let Err(e) = on_decryption_requested(fhe, data, bus, event, address).await {
+        // Handle the error, e.g., send an error event or log it
+        bus.do_send(EnclaveEvent::from_error(
+            EnclaveErrorType::Decryption,
+            e,
+        ));
+    }
})

Likely invalid or redundant comment.

packages/ciphernode/core/src/evm_enclave.rs (1)

133-146: Great job adding comprehensive tests for encoding and decoding

The test_evm_decode function thoroughly tests the encode_e3_params and decode_e3_params functions, ensuring that parameters are correctly encoded and decoded. Including such tests enhances code reliability and helps prevent regressions.

packages/ciphernode/core/src/fhe.rs (5)

1-1: Appropriate addition of necessary imports

The inclusion of Seed in the imports is correct and necessary for the new functionality.


9-9: Import required traits from fhe_traits

The added traits Deserialize, DeserializeParametrized, FheDecoder, and Serialize are essential for serialization and deserialization operations used in this module.


43-50: Efficient initialization with the new from_encoded method

The from_encoded method provides a streamlined way to initialize Fhe from encoded parameters and a seed. The use of BfvParameters::try_deserialize and set_up_crp is appropriate, and error handling with the ? operator ensures that errors are propagated correctly.


134-134: Destructure E3Requested event to extract params and seed

Extracting params and seed from E3Requested is appropriate and aligns with the updated event structure.


128-128: Ensure all calls to FheFactory::create are updated

The create function now accepts SharedRng instead of Arc<Mutex<ChaCha20Rng>>. Verify that all invocations of this function across the codebase are updated to match the new signature to prevent any type mismatch errors.

Run the following script to find usages of FheFactory::create and check the arguments passed:

tests/basic_integration/test.sh (1)

109-109: ⚠️ Potential issue

Ensure fake_encrypt binary is built before waiting

The script waits for the fake_encrypt binary, but it's not clear if it's built prior to this point. To prevent indefinite waiting, confirm that fake_encrypt is built before invoking waiton-files.

Apply this diff to build fake_encrypt if necessary:

+if [ ! -f "$ROOT_DIR/packages/ciphernode/target/debug/fake_encrypt" ]; then
+  echo "Building fake_encrypt binary..."
+  pushd "$ROOT_DIR/packages/ciphernode" >/dev/null
+  cargo build --bin fake_encrypt
+  popd >/dev/null
+fi

Alternatively, verify the existence of the binary:

Run the following script to confirm fake_encrypt exists:

packages/ciphernode/core/src/events.rs (3)

6-7: New imports are correctly added and necessary.

The added imports for error::Error and fmt::{self, Display} are required for the implementations of error handling and display formatting within the code.


170-174: Confirm the uniqueness of the FromError trait name.

Introduce the FromError trait cautiously to avoid conflicts with existing traits or future standard library additions. Verify that this trait name does not clash with other commonly used traits and consider using a more descriptive name if necessary.

Run the following script to check for existing traits named FromError:

#!/bin/bash
# Description: Check for existing 'FromError' trait definitions in the codebase or dependencies.

# Search for trait definitions named 'FromError'.
rg --type rust 'trait FromError' -A 2

307-308: Verify consistency of the Seed type usage across the codebase.

The E3Requested struct now includes pub seed: Seed. Ensure that all instances where E3Requested is constructed or used have been updated to accommodate this change, preventing potential type mismatches or runtime errors.

Run the following script to check for usages of E3Requested and verify the seed field handling:

packages/ciphernode/core/src/lib.rs (9)

37-37: Ensure new public functions are documented and tested

The functions decode_e3_params and encode_e3_params are now being publicly exported. Please ensure they are adequately documented and covered by unit tests to maintain code quality and API usability.


97-97: Optimize RNG handling by passing without cloning

Passing rng directly to FheFactory::create(rng) avoids unnecessary cloning of the random number generator, which can improve performance and reduce overhead.


109-109: Enhance logging with SimpleLogger attachment

Attaching SimpleLogger using SimpleLogger::attach(addr, bus.clone()) will improve logging capabilities during the setup of the local cipher node, aiding in debugging and monitoring.


127-127: Verify secure handling of encapsulated seed

By encapsulating the seed within the Seed struct, make sure that it maintains the desired level of randomness and that the seed is securely managed to prevent potential security vulnerabilities.


145-147: Ensure thread-safe initialization of RNG with mutex

Initializing ChaCha20Rng using Arc::new(std::sync::Mutex::new(...)) requires careful handling to avoid deadlocks and ensure thread safety. Verify that the mutex is properly managed in concurrent environments.


210-211: Duplicate issue: Exposing seed in events

This duplicates the earlier concern about including seed in events. Ensure that all instances where the seed is used in events are reviewed for security implications.


373-374: Maintain consistency in seed usage within tests

The seed initialization in test_p2p_actor_forwards_events_to_bus mirrors previous changes. Confirm that this maintains test integrity and aligns with the updated Seed struct usage.


385-386: Duplicate issue: Exposing seed in events

As previously noted, including seed in event payloads may introduce security vulnerabilities. Re-evaluate its necessity in this context.


177-178: ⚠️ Potential issue

Potential security concern: Exposing seed in events

Including seed in the E3Requested event may expose sensitive information. Assess whether the seed should be transmitted in clear text or if it needs to be protected to prevent security risks like replay attacks.

⛔ Skipped due to learnings
Learnt from: auryn-macmillan
PR: gnosisguild/enclave#107
File: packages/ciphernode/core/src/logger.rs:45-46
Timestamp: 2024-09-26T16:47:14.932Z
Learning: The `seed` in the `E3Requested` event is a seed for RNG and not sensitive. Logging it is acceptable.
packages/evm/test/Enclave.spec.ts (3)

83-84: Ensure correct encoding of e3ProgramParams

The e3ProgramParams now include both bytes and address types. Verify that "0x12345678" correctly represents the expected bytes data for the E3 Program, and that the inputValidator address is accurately retrieved using await inputValidator.getAddress().


536-536: Verify the use of ZeroHash and ethers.ZeroAddress in tests

In this test case, e3ProgramParams are encoded with [ZeroHash, ethers.ZeroAddress]. Ensure that using ZeroHash and ethers.ZeroAddress accurately simulates the scenario where the encryption scheme is disabled, and that it triggers the expected InvalidEncryptionScheme error.


554-554: Test correctly simulates an invalid computation request

By encoding e3ProgramParams with [ZeroHash, ethers.ZeroAddress], the test effectively simulates an invalid request. This setup correctly triggers the InvalidComputationRequest error as expected.

tests/basic_integration/lib/fake_encrypt.sh Show resolved Hide resolved
packages/ciphernode/core/src/evm_listener.rs Show resolved Hide resolved
packages/ciphernode/core/src/keyshare.rs Show resolved Hide resolved
tests/basic_integration/test.sh Show resolved Hide resolved
packages/ciphernode/core/src/events.rs Show resolved Hide resolved
packages/ciphernode/core/src/lib.rs Show resolved Hide resolved
packages/evm/test/Enclave.spec.ts Show resolved Hide resolved
packages/evm/test/Enclave.spec.ts Show resolved Hide resolved
@hmzakhalid
Copy link
Member

lgtm

Copy link
Member

@auryn-macmillan auryn-macmillan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@auryn-macmillan auryn-macmillan merged commit e8b6ce9 into main Sep 30, 2024
3 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 10, 2024
2 tasks
@coderabbitai coderabbitai bot mentioned this pull request Oct 31, 2024
@ryardley ryardley deleted the ry/encode_params branch December 5, 2024 06:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Remove hardcoded FHE params
3 participants