Skip to content

Refactor with sdk and removal of nip59 mod #100

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

Closed
wants to merge 7 commits into from
Closed

Conversation

arkanoider
Copy link
Collaborator

@arkanoider arkanoider commented Dec 20, 2024

Remove of nip59.rs mod

testing to replace lot of lines of code with internal Sdk functions:

  • Added a cleaner way to fetch events removing old code to do that.
  • Tested a full cycle of sell order with new nip59 functions directly from sdk with success.
  • Need to understand if we can manage also user messages in similar way.

Temporary note:

At the moment to make this compile we need to point to Nost-sdk in cargo.toml of mostro-cli and mostro-core like this:

nostr-sdk = { git  = "https://github.com/rust-nostr/nostr", features = ["nip06", "nip44", "nip59"], rev ="70db575d51965240aab1e1b3f1edab782c0ef625"}

and also use a local override of mostro-core to point to same nostr-sdk like, this:

[patch.crates-io]
mostro-core = { path = "../mostro-core" }

these 2 patches can be removed as soon as new release of sdk has been shipped.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Updated dependencies for improved functionality and performance.
    • Introduced expiration handling in direct message sending.
  • Bug Fixes

    • Enhanced parsing of trade keys for better performance.
  • Refactor

    • Restructured event handling logic for clarity and efficiency.
    • Removed obsolete functions related to relay requests.
  • Chores

    • Removed unused module and related functions to streamline the codebase.

Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Walkthrough

This pull request introduces several significant changes to the Mostro CLI project, focusing on dependency management, code refactoring, and module restructuring. The modifications include updating dependencies in Cargo.toml, removing the nip59 module, and making substantial changes to utility functions for message handling and event processing. The changes aim to streamline the codebase, update dependency references, and improve the overall structure of message and event management.

Changes

File Change Summary
Cargo.toml - Updated nostr-sdk to use Git repository reference
- Incremented mostro-core version from 0.6.17 to 0.6.18
src/cli/add_invoice.rs - Modified trade_keys parsing to use reference
src/cli/send_msg.rs - Updated trade_keys_str parsing to use reference
src/lib.rs - Removed pub mod nip59; module declaration
src/nip59.rs - Completely removed file with gift wrap-related functions
src/util.rs - Extensive refactoring of message and event handling functions
- Updated send_dm with expiration parameter
- Removed requests_relay, send_relays_requests, and get_events_of_mostro
- Modified get_direct_messages, get_orders_list, and get_disputes_list

Sequence Diagram

sequenceDiagram
    participant Client
    participant SendDM
    participant EventBuilder
    participant Message
    
    Client->>SendDM: send_dm(payload, keys, expiration)
    SendDM->>Message: Create message
    Message-->>EventBuilder: Build event
    EventBuilder->>Client: Return signed event
Loading

Possibly Related PRs

Poem

🐰 A Rabbit's Refactor Tale 🐰

Dependencies dance, versions take flight,
Modules vanish in the coder's delight.
Gift wraps unwrapped, messages soar,
Rust's magic opens a brand new door.
Mostro CLI, leaner and bright!


📜 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 bbb0f4c and 6c9c4f3.

📒 Files selected for processing (1)
  • Cargo.toml (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml

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)
src/util.rs (1)

Line range hint 161-222: Potential unwrapping vulnerabilities.
Multiple unwraps occur in the decryption and unwrapping processes. Attacks on manipulated or invalid data could cause panics. Replace these unwraps with structured error handling or the “? operator” to gracefully handle malformed data.

- let unwrapped_gift = match nip59::extract_rumor(my_key, dm).await {
-     Ok(u) => u,
-     Err(_) => {
-         println!("Error unwrapping gift");
-         continue;
-     }
- };
- let (mmessage, sig): (Message, nostr_sdk::secp256k1::schnorr::Signature) =
-     serde_json::from_str(&unwrapped_gift.rumor.content).unwrap();
+ let unwrapped_gift = nip59::extract_rumor(my_key, dm).await;
+ if unwrapped_gift.is_err() {
+     println!("Error unwrapping gift");
+     continue;
+ }
+ let unwrapped_gift = unwrapped_gift.unwrap(); // or match to handle error
+
+ let deser_result = serde_json::from_str(&unwrapped_gift.rumor.content);
+ if deser_result.is_err() {
+     println!("Error parsing unwrapped rumor content");
+     continue;
+ }
+ let (mmessage, sig): (Message, nostr_sdk::secp256k1::schnorr::Signature) = deser_result.unwrap();
🧹 Nitpick comments (5)
src/util.rs (3)

Line range hint 33-38: Handle encryption errors with more descriptive feedback.
Although you’re correctly checking for an error, consider returning a more explicit error message or logging additional context (like the receiver’s pubkey or the payload length) to improve troubleshooting.


110-110: Double-check the "None" expiration usage in send_message_sync.
Here, “expiration” is explicitly set to None. If that’s intended, confirm that the broader system logic does not rely on an expiration for short-lived messages.


Line range hint 242-265: Check for concurrency or pagination issues in fetch_events.
When retrieving multiple events from multiple relays, ensure any concurrency or pagination edge cases are handled. If events come in out of sequence or partial sets, data might be incomplete, especially for large volumes.

Cargo.toml (1)

52-53: Local path override for "mostro-core".
Using a local path may ease development but could complicate CI/CD if the environment lacks the local version. Consider using a dedicated branch or Git reference for better integration in multi-dev workflows.

src/cli/send_msg.rs (1)

55-55: LGTM! Consistent with the refactoring pattern.

The change to use reference passing with Keys::parse matches the pattern in add_invoice.rs and maintains proper error handling.

Consider adding a brief comment explaining the Keys parsing pattern, as it's part of a larger SDK integration effort:

+                // Parse trade keys using SDK's reference-based parsing
                 let trade_keys = Keys::parse(&trade_keys_str)?;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 08adcb4 and bbb0f4c.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • Cargo.toml (2 hunks)
  • src/cli/add_invoice.rs (1 hunks)
  • src/cli/send_msg.rs (1 hunks)
  • src/lib.rs (0 hunks)
  • src/nip59.rs (0 hunks)
  • src/util.rs (10 hunks)
💤 Files with no reviewable changes (2)
  • src/lib.rs
  • src/nip59.rs
🔇 Additional comments (5)
src/util.rs (2)

25-25: Ensure proper handling of the new "expiration" parameter.
If the event content is time-sensitive, consider validating its timestamp before passing it to this function. Also, verify that relays reliably honor the new "expiration" tag.


44-63: Strengthen error checks around message signing & rumor creation.
You’re assuming successful JSON parsing and signature creation without fallback or additional logging in case of errors. Consider adding checks to handle partial or incorrect data in the content.

Cargo.toml (2)

25-26: Confirm all Nostr SDK features are still needed.
You continue to include "nip59" in the features, even though the PR’s summary indicates a removal of the nip59 module. Confirm that the Nostr SDK’s nip59 capability is still required.


43-43: Upgrade verification for "mostro-core".
Version 0.6.18 might introduce changes that require code updates. Confirm that these changes are minimal and tested thoroughly, especially if they introduce new message/event handling logic.

src/cli/add_invoice.rs (1)

24-24: LGTM! Consistent with SDK integration objectives.

The change to pass a reference to Keys::parse is a good practice for memory efficiency and aligns with the PR's goal of SDK integration.

Let's verify this pattern is consistently applied across the codebase:

✅ Verification successful

Reference passing to Keys::parse is consistently implemented

Based on the comprehensive search results, the pattern of passing references to Keys::parse is consistently applied across the codebase:

  • src/cli/add_invoice.rs: Keys::parse(&trade_keys)
  • src/cli/get_dm.rs: Keys::parse(keys)
  • src/cli/send_msg.rs: Keys::parse(&trade_keys_str)

The usage pattern shows that Keys is a core type used throughout the application for identity and trade key management, and the reference passing approach is uniformly implemented in all instances where Keys::parse is called.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct Keys::parse calls that might need similar updates
ast-grep --pattern 'Keys::parse($x)' 

Length of output: 38


Script:

#!/bin/bash
# Let's try a more comprehensive search for Keys::parse usage
rg "Keys::parse" -A 2

Length of output: 623


Script:

#!/bin/bash
# Also search for the Keys type usage to understand the context
rg "use.*Keys" --type rust

Length of output: 28


Script:

#!/bin/bash
# Look for the Keys struct/type definition
fd -e rs -x ast-grep --pattern 'struct Keys {$$$}'

Length of output: 52


Script:

#!/bin/bash
# Let's look for Keys imports to find its module
rg "Keys" --type rust -B 2

Length of output: 3860


Script:

#!/bin/bash
# Check the actual implementation of Keys::parse
fd Keys.rs -x cat {} \;

Length of output: 28

Comment on lines +347 to +352
if let Ok(mostro_req) = client
.fetch_events(vec![filter], Duration::from_secs(15))
.await
{
// Scan events to extract all disputes
for d in mostro_req.iter() {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refine error handling for dispute extraction.
Similar to orders, the dispute extraction loop silently discards errors. Investigate adding logging or returning partial results to facilitate debugging and error recovery in production.

@arkanoider arkanoider mentioned this pull request Dec 23, 2024
@arkanoider
Copy link
Collaborator Author

Check #102 that wraps also this pr.

@arkanoider arkanoider closed this Dec 23, 2024
@grunch grunch deleted the refactor-with-sdk branch March 4, 2025 14:23
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.

1 participant