Skip to content

v0.8.4-dev to master#190

Merged
pauldelucia merged 5 commits into
masterfrom
v0.8.4-dev
Mar 11, 2025
Merged

v0.8.4-dev to master#190
pauldelucia merged 5 commits into
masterfrom
v0.8.4-dev

Conversation

@pauldelucia
Copy link
Copy Markdown
Member

@pauldelucia pauldelucia commented Mar 11, 2025

Summary by CodeRabbit

  • New Features

    • Introduced dynamic handling of user data directory paths and a robust cookie-based authentication mechanism that falls back to traditional credentials, ensuring smoother client connections.
  • Refactor

    • Streamlined network configuration loading and error handling to enhance reliability and overall system responsiveness.
  • Chores

    • Updated package version from 0.8.3 to 0.8.4 and required Rust version from 1.81 to 1.85.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 11, 2025

Walkthrough

This pull request introduces several new functions to modularize and generalize directory and cookie path handling for application data. It refactors user data directory resolution by adding dedicated functions for generic and DashCore-specific paths. Additionally, the PR refines configuration loading and authentication flows by streamlining error handling and unifying chain lock retrieval logic in the backend task module and context initialization. The changes also update provider initialization to support cookie-based authentication with a fallback to user/password methods.

Changes

File(s) Change Summary
src/app_dir.rs Added functions: user_data_dir_path, core_user_data_dir_path, and core_cookie_path to generalize user data directory and cookie file path construction, with conditional logic based on the operating system and network parameters.
src/backend_task/core/mod.rs Refactored network configuration loading and chain lock retrieval by introducing the get_best_chain_lock method in AppContext, simplifying client creation and error handling for both mainnet and testnet in a unified way.
src/context.rs and src/context_provider.rs Updated provider initialization to include a direct Network parameter and integrated cookie-based client authentication (using core_cookie_path) with a fallback to the user/password approach, alongside necessary dependency imports and method signature updates.

Sequence Diagram(s)

sequenceDiagram
  participant App as Application
  participant Provider as Provider
  participant CookieManager as CookieManager
  participant Client as Client

  App->>Provider: Initialize with (db, network, config)
  Provider->>CookieManager: Retrieve cookie path (via core_cookie_path)
  CookieManager-->>Provider: Return cookie path or error
  alt Cookie exists
      Provider->>Client: Attempt cookie-based authentication
      Client-->>Provider: Authentication successful
  else Cookie missing/invalid
      Provider->>Client: Fallback to user/password authentication
      Client-->>Provider: Authentication successful/failure
  end
Loading
sequenceDiagram
  participant AppContext as AppContext
  participant Config as NetworkConfig
  participant Client as Client
  participant ErrorHandler as ErrorHandler

  AppContext->>Config: Retrieve configuration
  AppContext->>Client: Call get_best_chain_lock(config, network)
  Client-->>AppContext: Return ChainLock or error
  alt Successful lock retrieval
      AppContext-->>Caller: Return ChainLock
  else Error encountered
      AppContext->>ErrorHandler: Handle error and report
      ErrorHandler-->>AppContext: Error details
  end
Loading

Possibly related PRs

  • feat: core rpc cookie #189: The changes in the main PR and the retrieved PR are related as both introduce the same new functions (user_data_dir_path, core_user_data_dir_path, and core_cookie_path) in src/app_dir.rs, indicating a direct connection at the code level.
  • feat: better error message for having no env file #15: The changes in the main PR, particularly the introduction of the core_cookie_path function, are directly related to the modifications in the retrieved PR, which also involves enhancements to error handling and the use of core_cookie_path for authentication.
  • feat: retry vote poll end times query and insert proof logs #81: The changes in the main PR are related to the retrieved PR as both involve modifications to the AppContext implementation, specifically with the introduction of new functions that enhance error handling and authentication processes, including the use of core_cookie_path.

Suggested reviewers

  • QuantumExplorer
  • ogabrielides

Poem

Hopping through the code meadows, I bound with delight,
New paths for data and cookies shining so bright.
With each function added, the structure's a treat,
Modular magic in every line so neat.
A bunny's joyful hop, where logic and whimsy meet!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01f1b49 and 01bb604.

📒 Files selected for processing (1)
  • Cargo.toml (1 hunks)
🔇 Additional comments (2)
Cargo.toml (2)

3-3: Version Bump: Updated package version to "0.8.4".

The version update is straightforward and aligns with the PR objectives. Ensure that any related documentation, release notes, and dependency configurations are updated to reflect this change.


7-7: Rust Version Update: Updated rust-version to "1.85".

This update requires using a newer Rust toolchain. Please verify that your CI/CD environment, local build setups, and all dependencies are compatible with Rust 1.85 to avoid unexpected build issues.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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
Copy Markdown
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

🧹 Nitpick comments (3)
src/context_provider.rs (1)

43-44: Preserve error context when mapping the core client creation error.
Currently, map_err(|e| e.to_string())? discards the original error type, which can lose valuable error context. Consider adopting an error type or more descriptive error messages.

src/context.rs (1)

113-116: Consider more robust error handling instead of .expect().
Using .expect() here will panic on failure to create the client, which may not be ideal for production. Consider handling and returning the error gracefully or using a logging approach.

src/backend_task/core/mod.rs (1)

97-139: Retain original client creation error for better debugging.
The code uses .map_err(|_| format!("Failed to create {} client", network.to_string()))?, which hides the underlying error detail. Preserving the original error message can greatly help debugging.

- .map_err(|_| format!("Failed to create {} client", network.to_string()))?;
+ .map_err(|e| format!("Failed to create {} client: {}", network, 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 02103f3 and 01f1b49.

📒 Files selected for processing (14)
  • src/app_dir.rs (1 hunks)
  • src/backend_task/core/mod.rs (3 hunks)
  • src/context.rs (2 hunks)
  • src/context_provider.rs (3 hunks)
  • src/app_dir.rs (2 hunks)
  • src/backend_task/core/mod.rs (4 hunks)
  • src/context.rs (4 hunks)
  • src/context_provider.rs (2 hunks)
  • src/backend_task/core/mod.rs (1 hunks)
  • src/context.rs (2 hunks)
  • src/app_dir.rs (1 hunks)
  • src/backend_task/core/mod.rs (3 hunks)
  • src/context.rs (3 hunks)
  • src/context_provider.rs (2 hunks)
🔇 Additional comments (9)
src/context_provider.rs (1)

1-11: No major concerns.
The new imports look straightforward and are properly used in subsequent code.

src/app_dir.rs (2)

1-4: No issues found.
Imports from directories and dashcore::Network are straightforward and correct.


26-44: Good approach for cross-platform user data directory detection.
The conditional code for Linux vs. other platforms is clear. The usage of UserDirs is correct and will preserve the .dashcore folder approach for Linux.

src/context.rs (3)

1-1: No issues found.
The additional import is aligned with the usage of core_cookie_path.


74-74: Signature change to include network is consistent with usage.
This looks good, ensuring the provider is aware of the active network.


90-90: Cookie path retrieval.
Using core_cookie_path(network, &network_config.devnet_name) centralizes path logic and is consistent with approach in src/context_provider.rs.

src/backend_task/core/mod.rs (3)

4-6: No major concerns.
The added imports for core_cookie_path, core_user_data_dir_path and NetworkConfig are consistent with the introduced logic.


57-58: Clean error handling for configuration loading.
Mapping the error into a concise message is appropriate here.


60-65: Integration for retrieving mainnet and testnet chain locks is succinct.
The approach to handle partial failures separately is clear and maintains continuity even if one network fails.

Comment thread src/context_provider.rs
Comment on lines +25 to +42
pub fn new(db: Arc<Database>, network: Network, config: &NetworkConfig) -> Result<Self, String> {
let cookie_path = core_cookie_path(network, &config.devnet_name)
.expect("Failed to get core cookie path");

// Read the cookie from disk
let cookie = std::fs::read_to_string(cookie_path);
let (user, pass) = if let Ok(cookie) = cookie {
// split the cookie at ":", first part is user (__cookie__), second part is password
let cookie_parts: Vec<&str> = cookie.split(':').collect();
let user = cookie_parts[0];
let password = cookie_parts[1];
(user.to_string(), password.to_string())
} else {
// Fall back to the pre-set user / pass if needed
(
config.core_rpc_user.clone(),
config.core_rpc_password.clone(),
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate cookie file content and handle potential errors.
The code inline-panics with .unwrap() for the user data directory, which may cause a crash if retrieving the home directory fails. Also, splitting on : might panic if there's no delimiter or the file is empty. Consider gracefully handling these errors:

Here is an example diff making error handling more robust:

- let cookie_path = core_user_data_dir_path().unwrap().join(".cookie");
+ let cookie_path = match core_user_data_dir_path() {
+     Ok(dir) => dir.join(".cookie"),
+     Err(e) => return Err(format!("Failed to get user data directory: {}", e)),
+ };

...

- let user = cookie_parts[0];
- let password = cookie_parts[1];
- (user.to_string(), password.to_string())
+ if cookie_parts.len() < 2 {
+     return Err("Invalid cookie format in .cookie file; expected 'user:password'".into());
+ }
+ (cookie_parts[0].to_string(), cookie_parts[1].to_string())

Committable suggestion skipped: line range outside the PR's diff.

Comment thread src/app_dir.rs
Comment on lines +46 to +56
pub fn core_cookie_path(network: Network, devnet_name: &Option<String>) -> Result<PathBuf, std::io::Error> {
core_user_data_dir_path().map(|path| {
let network_dir = match network {
Network::Dash => "",
Network::Testnet => "testnet3",
Network::Devnet => devnet_name.as_deref().unwrap_or(""),
Network::Regtest => "regtest",
_ => unimplemented!(),
};
path.join(network_dir).join(".cookie")
})
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider handling unsupported networks gracefully.
Using unimplemented!() for unknown networks causes a runtime panic. Returning a descriptive error or fallback path would enhance stability.

- _ => unimplemented!(),
+ other => return Err(std::io::Error::new(
+     std::io::ErrorKind::Unsupported,
+     format!("Unsupported network variant: {:?}", other)
+ ))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn core_cookie_path(network: Network, devnet_name: &Option<String>) -> Result<PathBuf, std::io::Error> {
core_user_data_dir_path().map(|path| {
let network_dir = match network {
Network::Dash => "",
Network::Testnet => "testnet3",
Network::Devnet => devnet_name.as_deref().unwrap_or(""),
Network::Regtest => "regtest",
_ => unimplemented!(),
};
path.join(network_dir).join(".cookie")
})
pub fn core_cookie_path(network: Network, devnet_name: &Option<String>) -> Result<PathBuf, std::io::Error> {
core_user_data_dir_path().map(|path| {
let network_dir = match network {
Network::Dash => "",
Network::Testnet => "testnet3",
Network::Devnet => devnet_name.as_deref().unwrap_or(""),
Network::Regtest => "regtest",
other => return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!("Unsupported network variant: {:?}", other)
))
};
path.join(network_dir).join(".cookie")
})
}

Comment thread src/context.rs
Comment on lines +98 to +101
"Failed to authenticate using .cookie file at {:?}, falling back to user/pass",
cookie_path,
);
Client::new(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Hide sensitive credentials in logs.
Printing network_config.core_rpc_user or core_rpc_password can expose credentials in logs, representing a security risk. Mask or remove these values to avoid accidental leakage.

- eprintln!(
-     "Failed to authenticate using .cookie file at {:?}, falling back to user/pass1, {:?}, {:?}",
-     cookie_path,
-     network_config.core_rpc_user.to_string(),
-     network_config.core_rpc_password.to_string(),
- );
+ eprintln!(
+     "Failed to authenticate using .cookie file at {:?}, falling back to user/pass credentials",
+     cookie_path
+ );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"Failed to authenticate using .cookie file at {:?}, falling back to user/pass",
cookie_path,
);
Client::new(
eprintln!(
"Failed to authenticate using .cookie file at {:?}, falling back to user/pass credentials",
cookie_path
);
Client::new(

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