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

feat: http client and request builders #235

Merged
merged 20 commits into from
Feb 16, 2025
Merged

Conversation

jns-ps
Copy link
Contributor

@jns-ps jns-ps commented Feb 13, 2025

Summary by CodeRabbit

  • New Features
    • Introduced new API and client modules enabling asynchronous account operations and robust HTTP interactions.
  • Refactor
    • Streamlined request building, transaction signing, and signature verification processes.
    • Simplified response handling and internal API interfaces.
  • Chores
    • Updated dependency versions, expanded workspace components, and refined build commands for specific output targets.
  • Tests
    • Revised test suites to adopt the new transaction builder, ensuring consistency across simulated environments.

@jns-ps jns-ps self-assigned this Feb 13, 2025
Copy link

vercel bot commented Feb 13, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
prism ⬜️ Ignored (Inspect) Visit Preview Feb 16, 2025 8:00am

Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

Walkthrough

This pull request expands the workspace by adding two new crates, crates/api and crates/client, and updates several dependencies and versions across the repository. It introduces a new asynchronous API interface with robust error handling and request builders. The changes refactor transaction signing by distinguishing unsigned and signed transactions and update testing modules to use TestTransactionBuilder instead of the legacy builder. Additionally, modifications in the HTTP client and key verification enhance clarity and error reporting across the codebase, while minor adjustments to build commands and dependency patches are also included.

Changes

File(s) Change Summary
Cargo.toml (root), crates/api/Cargo.toml, crates/client/Cargo.toml, crates/node_types/prover/Cargo.toml, crates/zk/sp1-script/Cargo.toml, crates/keys/Cargo.toml, crates/tree/Cargo.toml Updated dependency versions and added new workspace dependencies (e.g. reqwest, url). New crates (crates/api and crates/client) integrated; removal of patches in sp1-script and removal of ecdsa in prism-keys; deletion of utoipa dependency in prism-tree.
crates/api/src/api.rs, crates/api/src/lib.rs, crates/api/src/types.rs Introduced the PrismApi trait with asynchronous methods, a new PendingTransaction struct, and an organized module structure with new types for account and commitment responses.
crates/api/src/builder.rs Added a new request builder module with multiple builders (for creating accounts, registering services, and modifying accounts) along with signing and sending transaction flows.
crates/client/src/http_client.rs, crates/client/src/lib.rs Added a new HTTP client (PrismHttpClient) implementing the PrismApi trait with functions for GET, POST, and no-response POST methods, as well as structured error handling via PrismHttpClientError.
crates/common/src/account.rs, crates/common/src/transaction.rs, crates/common/src/lib.rs, crates/common/src/test_transaction_builder.rs Removed the legacy prepare_transaction method and refactored transaction signing by introducing UnsignedTransaction. Renamed TransactionBuilder to TestTransactionBuilder and updated test and transaction logic accordingly.
crates/keys/src/signatures.rs, crates/keys/src/verifying_keys.rs Removed the Placeholder variant from the Signature enum and refined error messages in signature verification for improved clarity.
crates/node_types/prover/src/prover/mod.rs, crates/node_types/prover/src/webserver.rs Modified account and commitment retrieval methods (renamed to use _from_tree) and integrated the PrismApi trait. Removed internal duplicate types from webserver responses.
Tests: crates/node_types/prover/src/prover/tests.rs, crates/tests/src/lib.rs, crates/tree/src/tests.rs, crates/zk/sp1-script/src/main.rs Switched imports and function parameters from TransactionBuilder to TestTransactionBuilder for a consistent testing approach.
justfile Updated the build command to include parameters for output directory and ELF naming.

Sequence Diagram(s)

sequenceDiagram
    participant Client as PrismHttpClient
    participant Prism as PrismApi Trait
    participant Server
    Client->>Prism: get_account(id) / get_commitment()
    Prism->>Server: HTTP Request (fetch/post)
    Server-->>Prism: JSON Response
    Prism-->>Client: Returns Response
Loading
sequenceDiagram
    participant Builder as RequestBuilder
    participant UTX as UnsignedTransaction
    participant Signer as SigningKey
    participant TX as Transaction
    Builder->>UTX: Create unsigned transaction
    UTX->>Signer: Request signature
    Signer-->>UTX: Provides signature
    UTX->>TX: Produce signed transaction
    TX-->>Builder: Return signed transaction
Loading

Suggested reviewers

  • sebasti810

Poem

I'm a rabbit, hopping through the code,
New crates and APIs lighten my humble abode.
With builders and clients, transactions take flight,
As error checks and signatures glow in the night.
Dependencies update, leaving bugs at bay—
A playful leap forward, come join me and play!
🐇🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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: 1

🔭 Outside diff range comments (1)
crates/api/src/api.rs (1)

126-163: 🛠️ Refactor suggestion

Prevent potential infinite loops in wait_with_interval.
Relying on a loop that never exits unless nonce changes could lead to hangs in scenarios where finalization is delayed indefinitely. Consider adding a timeout parameter or maximum retry count.

🧹 Nitpick comments (16)
crates/common/src/transaction.rs (2)

12-37: Well-defined approach for separating unsigned and signed transactions.
Encapsulating the transaction signing logic in UnsignedTransaction helps avoid partial or repeated signatures in Transaction. Ensure you include unit tests that verify a transaction can only be signed once and that the fields (id and nonce) are valid.


80-105: Consider adding more granular variants for transaction errors.
While these errors cover typical issues, situations like a distinct "InvalidSignature" variant may provide more clarity than bundling everything under SigningFailed.

crates/client/src/http_client.rs (3)

1-9: Initialize client with optional configuration.
Storing reqwest::Client is fine. Consider parameterizing the construction of the client, allowing custom timeouts or headers if needed.


11-57: Robust request helpers with potential improvements.
The fetch, post, and post_no_response methods handle JSON well. However, you might want to log or handle status codes before attempting to deserialize JSON, for improved debugging.


115-125: Refine conversion from TransactionError to HTTP client error.
Mapping all TransactionError variants to PrismHttpClientError::Request can obscure the root cause. Consider creating distinct error variants or at least logging the original details.

crates/api/src/api.rs (1)

13-124: Trait-driven design is coherent and flexible.
The PrismApi trait effectively delineates account and transaction operations. You might want to document the expected client-side usages for each method to guide implementers.

crates/api/src/builder.rs (4)

1-37: Consider adding doc comments for the RequestBuilder struct and its methods.
These builders are a key entry point for constructing account-related transactions, so providing doc comments describing usage, parameters, and return types would improve maintainability and clarity.


77-112: Ensure consistent usage of custom errors.
You correctly return TransactionError::MissingKey when no verifying key is provided, but other invalid states (e.g., empty id or service_id) might benefit from similarly explicit errors.


295-321: Add potential fallback or error handling for the signing step.
Using signing_key.sign(...) can fail under certain key or algorithm conditions. Consider returning a meaningful error instead of unwrapping in deeper calls (e.g., in UnsignedTransaction::sign).


323-343: Provide side effects or confirmation after sending the transaction.
Once send completes, you create a PendingTransaction. If there are follow-up steps (e.g., logging, user notification, or storing a reference locally), consider integrating them here or exposing a callback.

crates/common/src/transaction_builder.rs (3)

260-267: Avoid unwrap() for signing.
If something goes wrong (e.g., invalid key usage), unwrap() will panic. Returning a Result might be safer.


297-304: Enforce consistent error handling in revoke_key.
Like in add_key, consider gracefully propagating signing errors without panicking.


549-556: Ensure safe concurrency when setting data.
If multiple clients set data concurrently for the same account id, reusing account.nonce() can lead to conflicts; consider concurrency strategies.

crates/client/src/lib.rs (1)

1-3: Ensure http_client is tested independently.
The new module is essential for client-server communication. Consider adding integration tests to verify requests and responses.

Do you want help writing a basic test scaffold that hits a mock server?

crates/api/src/lib.rs (1)

31-39: Consider adding validation constraints to schema example.

The schema example is helpful but could be enhanced by adding validation constraints for the hex strings to ensure they are exactly 64 characters long (32 bytes).

 #[schema(example = r#"{
-    "leaf": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
+    "leaf": {
+        "type": "string",
+        "pattern": "^[a-f0-9]{64}$",
+        "example": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
+    },
     "siblings": [
-        "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
-        "9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba"
+        {
+            "type": "string",
+            "pattern": "^[a-f0-9]{64}$",
+            "example": "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"
+        }
     ]
 }"#)]
crates/node_types/prover/src/webserver.rs (1)

131-141: Consider using anyhow::Result for consistent error handling.

The error handling could be simplified by using anyhow's Result type and the ? operator.

-    let get_account_result = session.get_account(&request.id).await;
-    let Ok(account_response) = get_account_result else {
-        return (
-            StatusCode::INTERNAL_SERVER_ERROR,
-            format!(
-                "Failed to retrieve account or non-membership-proof: {}",
-                get_account_result.unwrap_err()
-            ),
-        )
-            .into_response();
-    };
+    let account_response = session
+        .get_account(&request.id)
+        .await
+        .map_err(|e| (
+            StatusCode::INTERNAL_SERVER_ERROR,
+            format!("Failed to retrieve account or non-membership-proof: {}", e),
+        ))?;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d274020 and d1ff6ad.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (16)
  • Cargo.toml (4 hunks)
  • crates/api/Cargo.toml (1 hunks)
  • crates/api/src/api.rs (1 hunks)
  • crates/api/src/builder.rs (1 hunks)
  • crates/api/src/lib.rs (1 hunks)
  • crates/client/Cargo.toml (1 hunks)
  • crates/client/src/http_client.rs (1 hunks)
  • crates/client/src/lib.rs (1 hunks)
  • crates/common/src/account.rs (2 hunks)
  • crates/common/src/transaction.rs (4 hunks)
  • crates/common/src/transaction_builder.rs (7 hunks)
  • crates/node_types/prover/Cargo.toml (1 hunks)
  • crates/node_types/prover/src/prover/mod.rs (6 hunks)
  • crates/node_types/prover/src/webserver.rs (3 hunks)
  • crates/tree/Cargo.toml (1 hunks)
  • crates/tree/src/proofs.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: clippy
  • GitHub Check: unit-test
  • GitHub Check: unused dependencies
  • GitHub Check: integration-test
  • GitHub Check: build-and-push-image
🔇 Additional comments (28)
crates/common/src/transaction.rs (2)

1-2: No issues found with imported traits.
These imports are standard and align with the newly added display logic.


56-69: Validate coverage for signature verification.
The verify_signature method is straightforward and relies on to_unsigned_tx to reconstruct the message. Consider adding or confirming unit tests to ensure tampering with id, operation, or nonce is consistently caught.

crates/client/src/http_client.rs (1)

59-74: Implementation of PrismApi is concise.
These methods are straightforward wrappers around the HTTP helpers and appear to fulfill the trait contract as expected.

crates/api/src/api.rs (3)

1-2: Duration import is straightforward.
No issues found.


3-7: Consistent usage of prism_common transaction and accounts.
These imports are aligned with the domain logic.


11-12: Builder and response imports look correct.
Ensure the builder usage remains consistent across new operations.

crates/api/src/builder.rs (3)

39-112: Validate non-empty id and service_id.
In the CreateAccountRequestBuilder, there is no explicit check that id and service_id are non-empty. This could lead to invalid account creation if either field is accidentally left blank.

Would you like to ensure that empty strings trigger an error?


114-171: Consider adding parallel validation here as in CreateAccountRequestBuilder.
The RegisterServiceRequestBuilder also sets id and a verifying key, but there's no explicit check for empty or invalid id. Consistency in validation helps prevent subtle bugs.


173-293: Revisit disallowing a zero nonce in validate_id_and_nonce.
Currently, the builder fails if nonce == 0. In some contexts, zero might be a permissible initial nonce. Please confirm this conforms to the intended logical flow.

crates/common/src/transaction_builder.rs (4)

7-7: Good addition of UnsignedTransaction usage.
This helps separate transaction creation from signing, improving clarity and modularity.


129-136: Confirm intentional use of a zero nonce.
Here, nonce is set to 0 for the newly created service. This may conflict if the service id already exists and expects a nonzero nonce.


199-206: Watch for reuse of account ID with zero nonce.
As with service registrations, consider verifying the account doesn't already exist when using nonce = 0.


439-446: Double-check that nonce = account.nonce() is appropriate for data addition.
If the account’s nonce is already incremented elsewhere, overwriting data might result in concurrency or replay issues.

crates/client/src/lib.rs (1)

3-14: Re-export choices look solid.
Providing these re-exports under a single client API is convenient for end users. No issues spotted here.

crates/api/src/lib.rs (1)

48-55: LGTM! The empty constructor is well implemented.

The empty constructor provides a convenient way to create an empty proof with no leaf and empty siblings.

crates/node_types/prover/src/webserver.rs (1)

157-160: LGTM! The commitment endpoint response handling is clean and concise.

The match expression provides clear error handling and uses the new CommitmentResponse type effectively.

crates/common/src/account.rs (1)

100-100: LGTM! Signature verification is now more encapsulated.

The change to use tx.verify_signature()? improves encapsulation by moving the signature verification logic into the Transaction struct.

crates/tree/src/proofs.rs (1)

222-237: LGTM! The hashed method implementation is clean and efficient.

The implementation correctly maps the leaf and sibling hashes from SparseMerkleProof to HashedMerkleProof, maintaining the tree structure.

crates/node_types/prover/src/prover/mod.rs (3)

3-3: LGTM! Import of PrismApi and related types.

The import of PrismApi and related types from the new prism-api crate aligns with the PR objectives of API redesign.


463-466: LGTM! Method renames improve clarity.

The renaming of get_commitment to get_commitment_from_tree and get_account to get_account_from_tree better describes their functionality and source of data.

Also applies to: 468-473


512-537: LGTM! Clean PrismApi trait implementation.

The implementation of the PrismApi trait for the Prover struct is well-structured:

  • Proper error type definition
  • Clear mapping between internal methods and API methods
  • Consistent error handling
crates/api/Cargo.toml (1)

1-25: LGTM! Well-structured Cargo.toml for the new API crate.

Dependencies are appropriate for an API crate and workspace configuration is correctly set up.

crates/client/Cargo.toml (1)

1-28: LGTM! Well-structured Cargo.toml for the new client crate.

Dependencies are appropriate for an HTTP client implementation and workspace configuration is correctly set up.

crates/tree/Cargo.toml (1)

15-15: LGTM! Dependency changes align with API redesign.

The addition of prism-api and removal of utoipa aligns with centralizing API definitions in the new prism-api crate.

crates/node_types/prover/Cargo.toml (1)

26-26: LGTM!

The addition of the prism-api dependency is correctly specified using workspace inheritance, aligning with the PR objectives of API redesign.

Cargo.toml (3)

19-19: LGTM!

The new crates api and client are correctly added to both default-members and members sections, aligning with the PR objectives of API redesign.

Also applies to: 21-21, 35-35, 37-37


69-72: LGTM!

The HTTP client dependencies are well-chosen:

  • reqwest is a popular, stable HTTP client library
  • url is the de-facto URL parsing library

134-134: LGTM!

The workspace dependencies for the new crates are correctly specified using relative paths.

Also applies to: 136-136

Copy link
Contributor

@distractedm1nd distractedm1nd left a comment

Choose a reason for hiding this comment

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

Struggling to find improvements to this PR. It's great.

The only thing I could ask to refine (which we should do, but maybe in next PR), would be adding rustdoc and eventually creating (http) client tests. Would rather have this merged immediately so it can be used by teams

So I would say we open issues for:

  1. Updating tutorial in docs + Adding rustdocs, including example usage (high priority, should be done next week)
  2. Creating integration tests with the http client (can probably be punted back a bit, medium priority)

@jns-ps jns-ps force-pushed the reuse-types-for-client branch from d1ff6ad to eb1f2ab Compare February 14, 2025 21:53
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: 3

♻️ Duplicate comments (1)
crates/client/src/http_client.rs (1)

111-113: ⚠️ Potential issue

Handle cases where err.status() could be None.

Relying on expect can lead to panics if the error doesn't contain a status.

-            PrismHttpClientError::Status(
-                err.status().expect("Status error should contain status").into(),
-            )
+            match err.status() {
+                Some(status) => PrismHttpClientError::Status(status.as_u16()),
+                None => PrismHttpClientError::Unknown,
+            }
🧹 Nitpick comments (14)
crates/api/src/api.rs (2)

28-30: Rename or clarify the builder method name.
build_request is a bit vague. Together with the chainable pattern, it might be clearer to rename it to request_builder, new_request, or something that implies returning a builder instance.


32-32: Enhance post-transaction feedback.
post_transaction returns a Result<(), Self::Error>, which may be too minimal. Consider returning a more informative response (e.g., transaction hash or status) to track or debug the transaction.

crates/common/src/test_transaction_builder.rs (3)

129-136: Handle signing errors gracefully instead of unwrapping.
Throughout these lines, unwrap() is used immediately after signing unsigned transactions. This will panic on error, even though the library supports fallible operations. For a more robust test suite, consider handling errors with ? or returning a Result.

-let transaction = unsigned_tx.sign(&signing_key).unwrap();
+let transaction = match unsigned_tx.sign(&signing_key) {
+    Ok(tx) => tx,
+    Err(e) => {
+        // Optionally log or handle the error as needed
+        panic!("Failed to sign transaction: {:?}", e);
+    }
+};

Also applies to: 199-206, 260-267, 297-304, 439-446, 549-556


60-60: Confirm whether the name “TestTransactionBuilder” is sufficiently descriptive.
Previously known as TransactionBuilder, it has been renamed for testing usage. Ensure team members understand its scope is purely test-oriented and it won’t be used in production. If usage in production builds is unintended, consider adding doc comments indicating so.

Also applies to: 83-83


426-452: DRY up repeated transaction-building patterns.
Many methods construct an UnsignedTransaction, compute a nonce, sign, and then wrap into UncommittedTransaction. This pattern is repeated across add, revoke, set, etc. Consider refactoring into a helper function to reduce duplication.

crates/api/src/types.rs (2)

1-26: Add clarifications or references for cryptographic fields.
For example, commitment: Digest in CommitmentResponse and id: String in AccountRequest might benefit from referencing how these fields are generated or used in the cryptographic flow. This can help integrators or new maintainers.


45-51: Provide partial equality or debugging support for HashedMerkleProof usage.
Currently, there is a straightforward approach (impl Debug, Serialize, Deserialize, ToSchema). If you plan to compare proofs in tests or logs, you might also derive or implement relevant traits. PartialEq is already there, so consider Eq if feasible.

crates/common/src/transaction.rs (2)

25-36: Consider adding error context to TransactionError.

The error handling could be more informative by including the specific cause of encoding or signing failures.

-        let bytes = self.encode_to_bytes().map_err(|_| TransactionError::EncodingFailed)?;
+        let bytes = self.encode_to_bytes().map_err(|e| TransactionError::EncodingFailed(e.to_string()))?;

80-105: Enhance error handling with additional context.

The TransactionError enum could be more informative by including error details in its variants.

 pub enum TransactionError {
     InvalidOp(String),
     InvalidNonce(u64),
     MissingKey,
-    EncodingFailed,
-    SigningFailed,
+    EncodingFailed(String),
+    SigningFailed(String),
 }

 impl Display for TransactionError {
     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
         match self {
             TransactionError::InvalidOp(msg) => write!(f, "Invalid operation: {}", msg),
             TransactionError::InvalidNonce(nonce) => write!(f, "Invalid nonce: {}", nonce),
             TransactionError::MissingKey => write!(f, "Public Key for account is missing"),
-            TransactionError::EncodingFailed => write!(f, "Encoding transaction failed"),
-            TransactionError::SigningFailed => write!(f, "Signing transaction failed"),
+            TransactionError::EncodingFailed(msg) => write!(f, "Encoding transaction failed: {}", msg),
+            TransactionError::SigningFailed(msg) => write!(f, "Signing transaction failed: {}", msg),
         }
     }
 }
crates/client/src/http_client.rs (1)

23-30: Add timeout configuration for HTTP requests.

The fetch method should include a configurable timeout to prevent hanging on slow responses.

+    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
+        self.client = self.client.timeout(timeout);
+        self
+    }

     pub async fn fetch<T>(&self, path: &str) -> Result<T, PrismHttpClientError>
     where
         T: DeserializeOwned,
     {
         let url = self.join_url(path)?;
-        let response = self.client.get(&url).send().await?;
+        let response = self.client
+            .get(&url)
+            .send()
+            .await
+            .map_err(|e| match e.is_timeout() {
+                true => PrismHttpClientError::Timeout,
+                false => e.into(),
+            })?;
         response.json::<T>().await.map_err(Into::<PrismHttpClientError>::into)
     }
crates/node_types/prover/src/webserver.rs (2)

146-146: Consider adding response metadata.

The account response could include metadata like request timestamp or server version.

-    (StatusCode::OK, Json(account_response)).into_response()
+    let response = AccountResponseWrapper {
+        data: account_response,
+        metadata: ResponseMetadata {
+            timestamp: chrono::Utc::now(),
+            version: env!("CARGO_PKG_VERSION"),
+        },
+    };
+    (StatusCode::OK, Json(response)).into_response()

161-161: Add rate limiting for commitment endpoint.

The get_commitment endpoint should include rate limiting to prevent abuse.

Consider implementing rate limiting using a middleware like tower::limit::RateLimit.

crates/node_types/prover/src/prover/mod.rs (1)

516-554: Consider adding error context in PrismApi implementation.

The implementation could benefit from more descriptive error contexts to help with debugging.

Apply this diff to improve error handling:

     async fn get_account(&self, id: &str) -> Result<AccountResponse, Self::Error> {
-        let acc_response = match self.get_account_from_tree(id).await? {
+        let acc_response = match self.get_account_from_tree(id)
+            .await
+            .with_context(|| format!("Failed to get account from tree: {}", id))? {
             Found(account, inclusion_proof) => {
                 let hashed_inclusion_proof = inclusion_proof.hashed();
                 AccountResponse {
Cargo.toml (1)

134-136: Integration of Prism Crate Dependencies.
Adding prism-api = { path = "crates/api" } and prism-client = { path = "crates/client" } in the [workspace.dependencies] section correctly integrates the new crates into the project. Verify that inter-crate imports and usage across the codebase align with these new dependency paths.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1ff6ad and eb1f2ab.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (24)
  • Cargo.toml (4 hunks)
  • crates/api/Cargo.toml (1 hunks)
  • crates/api/src/api.rs (1 hunks)
  • crates/api/src/builder.rs (1 hunks)
  • crates/api/src/lib.rs (1 hunks)
  • crates/api/src/types.rs (1 hunks)
  • crates/client/Cargo.toml (1 hunks)
  • crates/client/src/http_client.rs (1 hunks)
  • crates/client/src/lib.rs (1 hunks)
  • crates/common/src/account.rs (2 hunks)
  • crates/common/src/lib.rs (1 hunks)
  • crates/common/src/test_transaction_builder.rs (11 hunks)
  • crates/common/src/transaction.rs (4 hunks)
  • crates/keys/src/signatures.rs (1 hunks)
  • crates/keys/src/verifying_keys.rs (3 hunks)
  • crates/node_types/prover/Cargo.toml (2 hunks)
  • crates/node_types/prover/src/prover/mod.rs (6 hunks)
  • crates/node_types/prover/src/prover/tests.rs (5 hunks)
  • crates/node_types/prover/src/webserver.rs (3 hunks)
  • crates/tests/src/lib.rs (2 hunks)
  • crates/tree/Cargo.toml (0 hunks)
  • crates/tree/src/proofs.rs (1 hunks)
  • crates/tree/src/tests.rs (12 hunks)
  • crates/zk/sp1-script/src/main.rs (5 hunks)
💤 Files with no reviewable changes (1)
  • crates/tree/Cargo.toml
✅ Files skipped from review due to trivial changes (1)
  • crates/common/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/api/src/lib.rs
  • crates/client/src/lib.rs
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: clippy
  • GitHub Check: unit-test
  • GitHub Check: unused dependencies
  • GitHub Check: build-and-push-image
  • GitHub Check: integration-test
🔇 Additional comments (33)
crates/api/src/api.rs (1)

24-25: Consider documenting potential error conditions.
Both get_account and get_commitment only expose a Result type without clarifying (in doc comments) under what conditions an error might occur (e.g., network errors, missing records, etc.). Documenting these error scenarios can improve maintainability and user understanding.

Also applies to: 26-27

crates/common/src/test_transaction_builder.rs (1)

37-44: Confirm concurrency assumptions for account key management.
Removing account keys from the builder’s internal map is done in-place. If tests run in parallel, this could lead to data races unless each test obtains its own instance of TestTransactionBuilder. Confirm your concurrency model before using this code in multi-threaded tests.

crates/common/src/transaction.rs (2)

12-21: LGTM! Well-structured UnsignedTransaction implementation.

The struct is well-documented and includes all necessary fields for transaction handling.


57-60: LGTM! Robust signature verification.

The signature verification is properly implemented using the unsigned transaction data.

crates/keys/src/signatures.rs (1)

16-22: LGTM! Clean removal of Placeholder variant.

The Signature enum is now more focused with only the necessary variants.

crates/common/src/account.rs (1)

100-100: LGTM! Good encapsulation of signature verification.

The change simplifies the code by moving the signature verification logic into the Transaction struct, following the Single Responsibility Principle.

crates/tests/src/lib.rs (2)

7-7: LGTM! Good separation of test utilities.

The change improves code organization by using a dedicated test transaction builder.


98-98: LGTM! Consistent use of test transaction builder.

The change maintains consistency with the import changes while preserving test functionality.

crates/tree/src/proofs.rs (2)

221-236: LGTM! Clear and focused implementation.

The new implementation provides a cleaner way to construct HashedMerkleProof by directly extracting the required hashes.


238-242: LGTM! Simplified struct definition.

The struct has been streamlined to contain only the essential fields needed for Merkle proof verification.

crates/node_types/prover/src/prover/tests.rs (2)

2-2: LGTM! Consistent test utility usage.

The change maintains consistency with other test files by using the dedicated test transaction builder.


20-20: LGTM! Consistent builder instantiations.

All transaction builder instantiations have been updated to use TestTransactionBuilder, maintaining consistency while preserving test functionality.

Also applies to: 39-39, 54-54, 91-91

crates/api/src/builder.rs (3)

11-37: LGTM! Well-structured builder pattern implementation.

The RequestBuilder provides a clean and intuitive API for creating accounts, registering services, and modifying accounts.


39-112: LGTM! Robust account creation implementation with proper validation.

The CreateAccountRequestBuilder includes:

  • Proper validation of required fields
  • Secure challenge signing
  • Basic validation of operations

295-321: LGTM! Clean separation of signing and sending concerns.

The separation of SigningTransactionRequestBuilder and SendingTransactionRequestBuilder follows the single responsibility principle well.

Also applies to: 323-343

crates/keys/src/verifying_keys.rs (1)

120-120: LGTM! Improved error messages with signature type information.

The error messages now include the specific signature type (ed25519, secp256k1, secp256r1) being verified, which will help with debugging.

Also applies to: 130-130, 140-140

crates/tree/src/tests.rs (1)

4-4: LGTM! Consistent use of TestTransactionBuilder across tests.

The change from TransactionBuilder to TestTransactionBuilder improves test isolation and makes it clear that these are test-specific transactions.

Also applies to: 14-14, 45-45, 65-65, 97-97, 122-122, 146-146, 164-164, 249-249, 288-288, 325-325, 342-342

crates/node_types/prover/src/prover/mod.rs (1)

467-478: LGTM! Improved encapsulation with private helper methods.

The renaming of methods to get_commitment_from_tree and get_account_from_tree with private visibility improves encapsulation.

crates/zk/sp1-script/src/main.rs (7)

93-93: LGTM!

The function signature has been correctly updated to use TestTransactionBuilder.


100-100: LGTM!

The function signature has been correctly updated to use TestTransactionBuilder.


107-107: LGTM!

The function signature has been correctly updated to use TestTransactionBuilder.


114-114: LGTM!

The function signature has been correctly updated to use TestTransactionBuilder.


122-122: LGTM!

The function parameter has been correctly updated to use TestTransactionBuilder.


257-257: LGTM!

The variable declaration has been correctly updated to use TestTransactionBuilder.


16-16:

✅ Verification successful

Verify test-specific usage of TestTransactionBuilder.

The script is using a test-specific builder. Ensure this is intentional and not meant for production use.


🏁 Script executed:

#!/bin/bash
# Description: Check if this file is in a test directory or has test-specific usage.
# Test: Search for test-related markers. Expect: Test-related markers or test directory path.
rg -l "test|mock|bench" crates/zk/sp1-script/src/main.rs

Length of output: 91


Test-specific usage verified.
The grep result confirms that "crates/zk/sp1-script/src/main.rs" contains test-related markers, which validates the intentional use of the test-specific builder (TestTransactionBuilder). No changes are required here.

crates/api/Cargo.toml (1)

1-27: LGTM! Package structure aligns with discussed design.

The package configuration and dependencies are well-organized. The decision to keep this as a separate crate from common was previously discussed and agreed upon for separation of concerns.

crates/client/Cargo.toml (1)

1-31: LGTM! Well-structured package configuration.

The package configuration and dependencies are well-organized, with clear categorization of dependencies. The inclusion of HTTP client libraries (reqwest, url) aligns with the client implementation purpose.

crates/node_types/prover/Cargo.toml (2)

16-16: LGTM! Required dependency for async traits.

The addition of async-trait is necessary for implementing async traits in the prover.


27-27: LGTM! Integration with new API crate.

The addition of prism-api aligns with the API redesign, enabling the prover to implement the new API trait.

Cargo.toml (4)

19-21: New Crates Added to Workspace Default-members.
The addition of "crates/api" and "crates/client" in the default-members section ensures that these new crates will be included in workspace builds. Please verify that these crates are correctly configured with their respective Cargo.toml files and adhere to workspace conventions.


35-37: Updated Workspace Members Array.
The members array now explicitly includes "crates/api" and "crates/client". This update guarantees that the new crates are part of the project’s member list. Ensure that any paths or project-specific configuration settings in the new crates match the overall repository standards.


69-71: Addition of HTTP Client Dependencies.
The inclusion of reqwest = { version = "0.12", features = ["json"] } and url = { version = "2.5" } under the [workspace.dependencies] section is important for enabling HTTP requests and URL parsing in the redesigned client API. Confirm that these versions are compatible with other dependencies and that no dependency conflicts arise.


78-78: Async-trait Version Bump.
Upgrading async-trait from "0.1.68" to "0.1.86" can provide improvements and bug fixes for asynchronous traits. Please ensure that the updated version has been tested with all async functionalities across the project, paying special attention to compatibility with the new API implementations.

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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb1f2ab and dda0c37.

📒 Files selected for processing (2)
  • Cargo.toml (6 hunks)
  • justfile (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: unused dependencies
  • GitHub Check: unit-test
  • GitHub Check: clippy
  • GitHub Check: build-and-push-image
  • GitHub Check: integration-test
🔇 Additional comments (6)
justfile (1)

91-91:

❓ Verification inconclusive

Verify the output directory exists.

The build command now outputs to elf/ directory in the repository root. Ensure this directory exists or is created before building.

Run this script to check and create the output directory:


🏁 Script executed:

#!/bin/bash
# Description: Check if the output directory exists and create it if needed.

# Check if elf/ directory exists at repository root
if [ ! -d "elf" ]; then
  echo "Creating elf/ directory..."
  mkdir -p elf
fi

Length of output: 20


Ensure the ELF Output Directory Is Set Up Correctly

The build command now directs the output to the elf/ directory at the repository root:

cd crates/zk/sp1 && cargo prove build --output-directory ../../../elf/ --elf-name riscv32im-succinct-zkvm-elf

A shell script was provided to check and create the directory if it doesn't exist. Note that the script produced no output—this likely means the directory already exists, but it can also make it difficult to distinguish between an already-present directory and an execution issue.

  • Action: Manually verify that the elf/ directory exists in the repository root after running the build command (or in your CI environment).
  • Suggestion: Consider enhancing the script to always log a confirmation message (e.g., “elf/ directory exists” or “elf/ directory created”) to improve clarity during execution.
Cargo.toml (5)

5-7: LGTM!

The author list is properly formatted.


19-32: LGTM!

The workspace configuration is properly updated to include the new api and client crates, maintaining consistency between default-members and members sections.

Also applies to: 35-50


105-108: LGTM!

The secp256k1 features are properly configured for the required functionality.


134-136: LGTM!

The new prism crates are properly added to the workspace dependencies.


69-71:

❓ Verification inconclusive

Verify reqwest version compatibility.

The reqwest version 0.12 is very recent. Ensure it's stable and compatible with your deployment environment.


🌐 Web query:

What is the latest stable version of reqwest? Are there any known issues with version 0.12?

💡 Result:

The latest stable version of reqwest as of February 2025 is v0.12.12 based on changelog entries[1][4][7]. Key updates in the 0.12.x series include HTTP/3 support (under reqwest_unstable), rustls TLS improvements, and WASM compatibility fixes[1][4][9].

Known issues in v0.12.x:

  1. HTTP/2 timeout errors: Some users experience timeouts when using HTTP/2[9].

    • Workaround: Force HTTP/1.1 via ClientBuilder::http1_only() or adjust ALPN settings[9].
  2. rustls TLS certificate validation: Issues with self-signed certificates and truncated peer certificates were reported[2][4].

    • Partially addressed in v0.12.6 with danger_accept_invalid_hostnames option[4].
  3. Proxy handling: Earlier 0.12.x versions had proxy priority conflicts between environment variables[4]:

    // Fixed in v0.12.6: HTTP_PROXY now takes precedence over ALL_PROXY
    ClientBuilder::new().proxy(Proxy::custom(...))
  4. Breaking API changes:

    • Conversion from http::Request now uses TryFrom instead of infallible From[5][4].
    • Removed several Error::is_* inspector methods in v0.10+[4].

Recent patches (v0.12.7+) addressed decompression errors with HTTP/2 empty data frames and improved WASM compilation[4]. Users encountering issues should verify TLS configuration and consider constraining to HTTP/1 if experiencing connection problems[2][9].

Citations:


Action Required: Confirm reqwest v0.12 Compatibility with Deployment Environment

The dependency in your Cargo.toml (lines 69–71) specifies:

reqwest = { version = "0.12", features = ["json"] }

This aligns with the latest stable release (v0.12.12 as of February 2025). However, please note the following known considerations for the 0.12.x series:

  • HTTP/2 Timeouts: Some users report timeout errors when using HTTP/2. If you experience these, consider forcing HTTP/1.1 using ClientBuilder::http1_only() or review your ALPN settings.
  • TLS Certificate Validation: There have been issues with self-signed or truncated certificates. If applicable, check your TLS configurations; the danger_accept_invalid_hostnames option was introduced as a partial remedy.
  • Proxy Handling and API Changes: Earlier versions had proxy priority issues and API adjustments (e.g., conversion changes from infallible From to fallible TryFrom). Ensure that these do not impact your usage.

Please verify that your deployment environment can handle these edge cases or adjust your configurations accordingly.

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: 0

🧹 Nitpick comments (2)
.github/workflows/docker.yml (1)

53-57: Consistent Dependency Installation in Docker Workflow

The newly added "Install dependencies" step correctly installs the required packages (fontconfig and libfontconfig1-dev) before the Docker image build step. This helps ensure that all necessary system libraries are present. However, the commands in the run block have extra indentation compared to typical style in GitHub Actions workflows. Consider reducing the leading whitespace for improved readability and consistency with other steps.

.github/workflows/ci.yml (1)

117-122: Ensure System Dependencies Are Prepared for Clippy

The addition of the "Install dependencies" step in the clippy job is a prudent update. By running an update and installing fontconfig and libfontconfig1-dev prior to setting up the Rust toolchain with Clippy, you mitigate potential issues arising from missing system libraries required by some dependencies (such as those brought by the new crates).

If these installation steps are common across multiple jobs, you might consider refactoring them into a reusable workflow to reduce duplication.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b45ddd and cfb6e24.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • .github/workflows/ci.yml (1 hunks)
  • .github/workflows/docker.yml (1 hunks)
  • Cargo.toml (7 hunks)
  • crates/keys/Cargo.toml (0 hunks)
💤 Files with no reviewable changes (1)
  • crates/keys/Cargo.toml
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: integration-test
  • GitHub Check: clippy
  • GitHub Check: unused dependencies
  • GitHub Check: build-and-push-image
  • GitHub Check: unit-test

@jns-ps jns-ps changed the title feat: http client and client API redesign feat: http client and request builders Feb 15, 2025
@jns-ps
Copy link
Contributor Author

jns-ps commented Feb 15, 2025

So I would say we open issues for:

  1. Updating tutorial in docs + Adding rustdocs, including example usage (high priority, should be done next week)
  2. Creating integration tests with the http client (can probably be punted back a bit, medium priority)

Opened issues #237 , #238 , #239 , #240 and #241 for future improvements.

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: 1

♻️ Duplicate comments (1)
crates/api/src/builder.rs (1)

280-292: ⚠️ Potential issue

Improve nonce validation in validate_id_and_nonce.

The current implementation only checks if nonce is zero, which might not be sufficient for preventing replay attacks.

🧹 Nitpick comments (5)
crates/api/src/types.rs (1)

28-43: Consider adding validation for the Merkle proof siblings.

The HashedMerkleProof struct could benefit from validation of the siblings vector to ensure it maintains a valid Merkle proof structure.

 impl HashedMerkleProof {
+    /// Validates that the proof structure is consistent with a binary Merkle tree
+    pub fn validate(&self) -> bool {
+        // For a binary Merkle tree, the number of siblings should be log2(n) where n is the number of leaves
+        self.siblings.len() <= 32  // Assuming max tree depth of 32 for reasonable size
+    }
+
     pub fn empty() -> Self {
         Self {
             leaf: None,
             siblings: vec![],
         }
     }
 }
crates/common/src/transaction.rs (1)

25-36: Consider adding nonce validation in the sign method.

The sign method could validate the nonce before creating a signed transaction to prevent invalid transactions from being created.

 pub fn sign(self, sk: &SigningKey) -> Result<Transaction, TransactionError> {
+    if self.nonce == 0 {
+        return Err(TransactionError::InvalidNonce(self.nonce));
+    }
     let bytes = self.encode_to_bytes().map_err(|_| TransactionError::EncodingFailed)?;
     let signature = sk.sign(&bytes);
crates/node_types/prover/src/webserver.rs (1)

146-146: Consider adding error details in the success response.

While the success case returns a 200 status code, it might be helpful to include additional context or metadata in the response for better observability.

-    (StatusCode::OK, Json(account_response)).into_response()
+    (
+        StatusCode::OK,
+        Json(json!({
+            "status": "success",
+            "data": account_response,
+            "metadata": {
+                "timestamp": chrono::Utc::now(),
+                "version": env!("CARGO_PKG_VERSION"),
+            }
+        }))
+    ).into_response()
crates/tree/src/proofs.rs (1)

240-244: Consider adding documentation for HashedMerkleProof.

The struct lacks documentation explaining its purpose and usage.

+/// Represents a hashed version of a Merkle proof, containing the leaf hash and sibling hashes.
+///
+/// This struct is used to provide a simplified view of a Merkle proof where only the hashed values
+/// are needed, rather than the full proof structure.
 #[derive(Debug, Clone)]
 pub struct HashedMerkleProof {
+    /// The hash of the leaf node, if it exists
     pub leaf: Option<Digest>,
+    /// The hashes of the sibling nodes in the proof path
     pub siblings: Vec<Digest>,
 }
crates/common/src/test_transaction_builder.rs (1)

129-136: Consider extracting common transaction creation logic.

The pattern of creating and signing an UnsignedTransaction is repeated across multiple methods.

+    fn create_signed_transaction(
+        &self,
+        id: String,
+        operation: Operation,
+        nonce: u64,
+        signing_key: &SigningKey,
+    ) -> Transaction {
+        let unsigned_tx = UnsignedTransaction {
+            id,
+            operation,
+            nonce,
+        };
+        unsigned_tx.sign(signing_key).unwrap()
+    }

Also applies to: 199-206, 260-267, 297-304, 439-446, 549-556

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cfb6e24 and d4c1701.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (27)
  • Cargo.toml (7 hunks)
  • crates/api/Cargo.toml (1 hunks)
  • crates/api/src/api.rs (1 hunks)
  • crates/api/src/builder.rs (1 hunks)
  • crates/api/src/lib.rs (1 hunks)
  • crates/api/src/types.rs (1 hunks)
  • crates/client/Cargo.toml (1 hunks)
  • crates/client/src/http_client.rs (1 hunks)
  • crates/client/src/lib.rs (1 hunks)
  • crates/common/src/account.rs (2 hunks)
  • crates/common/src/lib.rs (1 hunks)
  • crates/common/src/test_transaction_builder.rs (11 hunks)
  • crates/common/src/transaction.rs (4 hunks)
  • crates/keys/Cargo.toml (0 hunks)
  • crates/keys/src/signatures.rs (1 hunks)
  • crates/keys/src/verifying_keys.rs (3 hunks)
  • crates/node_types/prover/Cargo.toml (2 hunks)
  • crates/node_types/prover/src/prover/mod.rs (6 hunks)
  • crates/node_types/prover/src/prover/tests.rs (5 hunks)
  • crates/node_types/prover/src/webserver.rs (3 hunks)
  • crates/tests/src/lib.rs (2 hunks)
  • crates/tree/Cargo.toml (0 hunks)
  • crates/tree/src/proofs.rs (1 hunks)
  • crates/tree/src/tests.rs (12 hunks)
  • crates/zk/sp1-script/Cargo.toml (0 hunks)
  • crates/zk/sp1-script/src/main.rs (5 hunks)
  • justfile (1 hunks)
💤 Files with no reviewable changes (3)
  • crates/tree/Cargo.toml
  • crates/keys/Cargo.toml
  • crates/zk/sp1-script/Cargo.toml
🚧 Files skipped from review as they are similar to previous changes (13)
  • crates/api/src/lib.rs
  • crates/common/src/lib.rs
  • justfile
  • crates/tests/src/lib.rs
  • crates/node_types/prover/Cargo.toml
  • crates/common/src/account.rs
  • crates/client/Cargo.toml
  • crates/keys/src/verifying_keys.rs
  • crates/client/src/lib.rs
  • crates/api/Cargo.toml
  • crates/tree/src/tests.rs
  • crates/node_types/prover/src/prover/tests.rs
  • crates/api/src/api.rs
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: clippy
  • GitHub Check: unused dependencies
  • GitHub Check: integration-test
  • GitHub Check: unit-test
  • GitHub Check: build-and-push-image
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (19)
crates/api/src/types.rs (1)

5-19: LGTM! Well-structured account request/response types.

The types are well-documented and implement appropriate traits for serialization and API schema generation.

crates/common/src/transaction.rs (1)

57-60: LGTM! Robust signature verification.

The verify_signature method correctly verifies the transaction signature by reconstructing the original message.

crates/keys/src/signatures.rs (1)

17-24: LGTM! Simplified signature enum.

The removal of the Placeholder variant makes the signature handling more robust and explicit.

crates/client/src/http_client.rs (2)

111-113: Handle cases where err.status() could be None.

Relying on expect("Status error should contain status") can lead to unexpected panics if the underlying error doesn't provide a status.

-            PrismHttpClientError::Status(
-                err.status().expect("Status error should contain status").into(),
-            )
+            match err.status() {
+                Some(status) => PrismHttpClientError::Status(status.as_u16()),
+                None => PrismHttpClientError::Unknown,
+            }

126-130: Improve error mapping for TransactionError.

The current implementation maps all transaction errors to a generic request error, losing valuable context.

 impl From<TransactionError> for PrismHttpClientError {
-    fn from(_: TransactionError) -> Self {
-        PrismHttpClientError::Request
+    fn from(err: TransactionError) -> Self {
+        match err {
+            TransactionError::InvalidOp(msg) => PrismHttpClientError::InvalidRequest(msg),
+            TransactionError::InvalidNonce(nonce) => PrismHttpClientError::InvalidRequest(format!("Invalid nonce: {}", nonce)),
+            _ => PrismHttpClientError::Request,
+        }
     }
 }
crates/node_types/prover/src/webserver.rs (2)

4-7: LGTM! Good modularization of API types.

The imports from prism_api module show good separation of concerns, moving common API types to a centralized location.


161-161: Consider adding error details in the success response.

Similar to the account endpoint, consider adding metadata to the commitment response.

-        Ok(commitment_response) => (StatusCode::OK, Json(commitment_response)).into_response(),
+        Ok(commitment_response) => (
+            StatusCode::OK,
+            Json(json!({
+                "status": "success",
+                "data": commitment_response,
+                "metadata": {
+                    "timestamp": chrono::Utc::now(),
+                    "version": env!("CARGO_PKG_VERSION"),
+                }
+            }))
+        ).into_response(),
crates/tree/src/proofs.rs (1)

223-238: LGTM! Clean implementation of the hashed method.

The implementation efficiently extracts leaf hash and sibling hashes from the SparseMerkleProof.

crates/api/src/builder.rs (1)

11-37: LGTM! Well-structured request builder implementation.

The RequestBuilder provides a clean interface for creating different types of requests.

crates/common/src/test_transaction_builder.rs (1)

60-67: LGTM! Good renaming to clarify test-specific code.

The rename to TestTransactionBuilder better reflects its purpose as a test utility.

crates/node_types/prover/src/prover/mod.rs (4)

2-2: LGTM!

The imports are correctly added to support the new PrismApi trait implementation.

Also applies to: 4-7


467-470: LGTM!

The method has been correctly renamed and made private, as it's now an internal implementation detail used by the public trait method.


472-477: LGTM!

The method has been correctly renamed and made private, with an appropriate return type for the internal implementation.


516-554: LGTM!

The PrismApi trait implementation is well-structured and correctly maps the API methods to internal functionality:

  • get_account properly transforms the internal account response into the API response type
  • get_commitment appropriately wraps the internal commitment
  • post_transaction correctly delegates to the existing validation logic
crates/zk/sp1-script/src/main.rs (1)

16-16:

❓ Verification inconclusive

Verify test coverage with the new builder.

The change from TransactionBuilder to TestTransactionBuilder is consistent across all functions. However, ensure that the test builder provides equivalent functionality and test coverage.

Run this script to verify test coverage:

Also applies to: 93-93, 100-100, 107-107, 114-114, 122-122, 159-159, 324-324


🏁 Script executed:

#!/bin/bash
# Description: Check test coverage for TestTransactionBuilder

# Search for test functions using TestTransactionBuilder
echo "Checking test coverage..."
rg "fn.*test.*TestTransactionBuilder" -A 5

Length of output: 105


Action Required: Manual Test Coverage Verification for TestTransactionBuilder

The static search for test functions using TestTransactionBuilder did not yield any results. Please manually verify that test cases covering the functionality of the new builder exist and offer equivalent coverage to those for TransactionBuilder. Specifically, ensure that:

  • The new TestTransactionBuilder is correctly integrated in your tests.
  • All functions previously covered by tests using TransactionBuilder have corresponding tests using TestTransactionBuilder.

The affected locations include the changes at:

  • crates/zk/sp1-script/src/main.rs on lines: 16, 93, 100, 107, 114, 122, 159, 324.
Cargo.toml (4)

19-20: LGTM!

The new api and client crates are correctly added to both default-members and members sections.

Also applies to: 21-21, 36-37, 38-38


71-74: LGTM!

The new dependencies reqwest and url are appropriate for implementing HTTP client functionality.


81-81: Verify SP1 version compatibility.

The SP1 dependencies have been updated to version 4.1.0, but some patch dependencies still reference version 4.0.0.

Run this script to check for any mismatched SP1 versions:

#!/bin/bash
# Description: Check for mismatched SP1 versions in dependencies and patches.

# Search for SP1 version references
echo "Checking SP1 versions in dependencies and patches..."
rg "sp1-[a-z]+" -A 1
rg "patch-.*sp1-[0-9]" -A 1

Also applies to: 101-103


139-139: LGTM!

The new workspace dependencies prism-api and prism-client are correctly added with appropriate paths.

Also applies to: 141-141

jns-ps and others added 9 commits February 16, 2025 10:03
Because we are using tokio in prism-api, it was transitively included in prism-tree. This led to compile errors for tokio on sp1.
Before, ecdsa was added to specify "der" feature, which was not re-exported in p256 crate. By now, however, "der" is transitively activated by "serde", which we use already. Therefore, ecdsa can be removed as a 1st class dependency.
@distractedm1nd distractedm1nd merged commit 2b38313 into main Feb 16, 2025
9 of 10 checks passed
@jns-ps jns-ps deleted the reuse-types-for-client branch February 17, 2025 23:27
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.

2 participants