Skip to content

feat: added correct pow management#51

Merged
arkanoider merged 3 commits intomainfrom
pow-fix
Apr 11, 2026
Merged

feat: added correct pow management#51
arkanoider merged 3 commits intomainfrom
pow-fix

Conversation

@arkanoider
Copy link
Copy Markdown
Collaborator

@arkanoider arkanoider commented Apr 11, 2026

Summary

  • PoW source: Remove local pow from settings.toml / Settings. NIP-13 difficulty for published events comes from the Mostro instance status event (kind 38385, tag pow), via nostr_pow_from_instance (src/util/mostro_info.rs).
  • Threading: AppState.mostro_info is passed through EnterKeyContext and into send_dm, all order/dispute/admin paths that publish to Mostro, and admin dispute chat (chat_utils / input_helpers).
  • Gift Wrap fix: EventBuilder::gift_wrap in rust-nostr does not apply PoW to the outer kind 1059 event. We build the seal with EventBuilder::seal + sign, then wrap with a local gift_wrap_from_seal_with_pow that mirrors the SDK’s gift_wrap_from_seal but adds .pow(pow) before signing the published Gift Wrap so instances that require PoW accept the event.

Breaking / migration

  • pow removed from settings: Existing settings.toml files may still contain pow = …; serde ignores unknown keys. Users should rely on instance info (Mostro Info tab / startup fetch).

Docs

  • README and docs/STARTUP_AND_CONFIG.md updated to describe PoW from 38385, not settings.

Summary by CodeRabbit

  • Configuration

    • Proof-of-work difficulty is now sourced from the Mostro instance status event (kind 38385); the pow setting was removed from settings.toml and UI-generated defaults.
  • Behavior

    • Outbound messages (DMs and wrapped Gift Wrap events) apply instance-derived PoW when publishing.
  • Documentation

    • Updated docs to describe instance-based PoW sourcing and outbound PoW handling.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 11, 2026

Warning

Rate limit exceeded

@arkanoider has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 13 minutes and 34 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 13 minutes and 34 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d1eece70-2c3e-4c2e-a408-34b1c49f6d57

📥 Commits

Reviewing files that changed from the base of the PR and between 9af9daa and 419b873.

📒 Files selected for processing (1)
  • src/util/dm_utils/dm_helpers.rs

Walkthrough

Removed the static pow setting and wiring from configuration and Settings; PoW is now derived from cached Mostro instance status (kind 38385) and threaded through UI handlers, order/DM utilities, and GiftWrap construction for outbound Nostr events.

Changes

Cohort / File(s) Summary
Configuration & Docs
README.md, docs/STARTUP_AND_CONFIG.md, docs/POW_AND_OUTBOUND_EVENTS.md, docs/MESSAGE_FLOW_AND_PROTOCOL.md, docs/SETTINGS_ANALYSIS.md, docs/README.md, settings.toml
Removed pow from settings examples and docs; added new PoW docs describing instance-sourced PoW (kind 38385) and outbound event behavior.
Settings Struct
src/settings.rs
Removed pow: u8 from Settings, its Default/init/test fixtures and first-run generated settings.
Mostro Instance Utilities
src/util/mostro_info.rs, src/util/mod.rs
Added nostr_pow_from_instance(instance: Option<&MostroInstanceInfo>) -> u8, exported via util re-exports; added unit tests for behavior and clamping.
DM / Chat Utilities
src/util/dm_utils/mod.rs, src/util/dm_utils/dm_helpers.rs, src/util/chat_utils.rs
Replaced global SETTINGS usage with instance-derived PoW; added gift_wrap_from_seal_with_pow helper to apply PoW to outer GiftWrap and updated DM/chat send APIs to accept mostro_instance.
Order Utilities
src/util/order_utils/... (send_new_order.rs, take_order.rs, execute_*.rs, send_new_order.rs, execute_send_msg.rs, etc.)
Threaded mostro_instance: Option<&MostroInstanceInfo> through send/take/execute functions; removed &Settings param from take_order; updated all calls to forward instance info into send_dm.
UI Key Handlers
src/ui/key_handler/mod.rs, src/ui/key_handler/async_tasks.rs, src/ui/key_handler/user_handlers.rs, src/ui/key_handler/admin_handlers.rs, src/ui/key_handler/confirmation.rs, src/ui/key_handler/enter_handlers.rs, src/ui/key_handler/input_helpers.rs, src/ui/key_handler/message_handlers.rs
Added mostro_info: Option<MostroInstanceInfo> to EnterKeyContext; populate it from app.mostro_info and clone-forward into spawned async tasks and execution callsites; adjusted function signatures/use sites where needed and removed on-demand settings load in take-order flow.
Misc exports & re-exports
src/util/mod.rs
Re-exported nostr_pow_from_instance alongside existing mostro exports.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant UI as UI / KeyHandler
participant EnterCtx as EnterKeyContext
participant Task as Async Task
participant OrderUtil as Order/DM Utilities
participant DMHelpers as DM Helpers (GiftWrap)
participant Relay as Nostr Relay

UI->>EnterCtx: create with mostro_info snapshot
EnterCtx->>Task: spawn with cloned mostro_info
Task->>OrderUtil: call send_dm / send_new_order (mostro_info)
OrderUtil->>DMHelpers: build event, call nostr_pow_from_instance(mostro_info)
DMHelpers->>DMHelpers: apply .pow(pow) and gift_wrap_from_seal_with_pow
DMHelpers->>Relay: publish signed event

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • AndreaDiazCorreia
  • Catrya
  • grunch
  • mostronatorcoder

"🐰 Removed pow from files, I hop with glee,
Instance tags now whisper the PoW to me.
I thread it through handlers, async and bright,
GiftWraps get mined in the soft moonlight. ✨"

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: added correct pow management' accurately describes the primary change: the PR refactors proof-of-work (PoW) management by removing it from settings and sourcing it from the Mostro instance status event instead.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pow-fix

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@arkanoider
Copy link
Copy Markdown
Collaborator Author

@coderabbitai review!

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 11, 2026

@arkanoider Sure, I'll review the changes in this PR right away!

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/ui/key_handler/user_handlers.rs (1)

53-62: ⚠️ Potential issue | 🟡 Minor

Fix clippy error: too many arguments (8/7).

The CI pipeline is failing because execute_take_order_action now has 8 parameters, exceeding clippy's default limit of 7. Since this function needs all these parameters and follows the established pattern (similar functions like spawn_take_order_task in async_tasks.rs already use #[allow(clippy::too_many_arguments)]), add the attribute to suppress this warning.

🔧 Proposed fix
 /// Execute taking an order.
 ///
 /// This avoids code duplication between Enter key and 'y' key handlers.
 /// Validates the take_state, sets the UI mode to waiting, and spawns an async task to take the order.
+#[allow(clippy::too_many_arguments)]
 pub(crate) fn execute_take_order_action(
     app: &mut AppState,
     take_state: TakeOrderState,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/ui/key_handler/user_handlers.rs` around lines 53 - 62, Add a clippy allow
attribute to suppress the "too many arguments" lint for the
execute_take_order_action function: place #[allow(clippy::too_many_arguments)]
immediately above the pub(crate) fn execute_take_order_action(...) definition
(consistent with how spawn_take_order_task in async_tasks.rs is handled) so the
function can keep its eight parameters without triggering the lint.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/util/dm_utils/dm_helpers.rs`:
- Around line 16-44: The function gift_wrap_from_seal_with_pow has formatting
inconsistencies (signature/braces, chained call layout, and multi-line result
formatting) that CI flags; fix by running rustfmt (cargo fmt --all) and ensure
the EventBuilder chain
(EventBuilder::new(...).tags(...).custom_created_at(...).pow(pow).sign_with_keys(...).map_err(...))
is formatted as a single consistent chain and the function signature/closing
brace align with project style, leaving the added .pow(pow) and the error
mapping in place.

In `@src/util/dm_utils/mod.rs`:
- Line 33: The module fails cargo fmt --check; run rustfmt to fix formatting for
src/util/dm_utils/mod.rs (the touched import line referencing
nostr_pow_from_instance and MostroInstanceInfo). Run cargo fmt --all (or
rustfmt) and commit the reformatted file so the use statement and module
formatting pass CI; ensure the import line in mod.rs is updated by the formatter
before merging.

In `@src/util/mostro_info.rs`:
- Around line 317-323: The test currently constructs a MostroInstanceInfo with
MostroInstanceInfo::default() and then reassigns the pow field, which triggers
clippy::field_reassign_with_default; instead, create each instance with an
explicit struct literal setting pow (e.g. MostroInstanceInfo { pow: Some(0),
..Default::default() }) for the zero, eight, and u32::MAX cases (or create three
separate instances like info0, info8, info_max) and call
nostr_pow_from_instance(Some(&infoX)) asserting the expected values (use u8::MAX
expectation for the u32::MAX case) to avoid reassigning fields after default
construction.

---

Outside diff comments:
In `@src/ui/key_handler/user_handlers.rs`:
- Around line 53-62: Add a clippy allow attribute to suppress the "too many
arguments" lint for the execute_take_order_action function: place
#[allow(clippy::too_many_arguments)] immediately above the pub(crate) fn
execute_take_order_action(...) definition (consistent with how
spawn_take_order_task in async_tasks.rs is handled) so the function can keep its
eight parameters without triggering the lint.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 25190c44-ac94-4578-ad26-3d3a9157bc92

📥 Commits

Reviewing files that changed from the base of the PR and between a891938 and fb07709.

📒 Files selected for processing (26)
  • README.md
  • docs/STARTUP_AND_CONFIG.md
  • settings.toml
  • src/settings.rs
  • src/ui/key_handler/admin_handlers.rs
  • src/ui/key_handler/async_tasks.rs
  • src/ui/key_handler/confirmation.rs
  • src/ui/key_handler/enter_handlers.rs
  • src/ui/key_handler/input_helpers.rs
  • src/ui/key_handler/message_handlers.rs
  • src/ui/key_handler/mod.rs
  • src/ui/key_handler/user_handlers.rs
  • src/util/chat_utils.rs
  • src/util/dm_utils/dm_helpers.rs
  • src/util/dm_utils/mod.rs
  • src/util/mod.rs
  • src/util/mostro_info.rs
  • src/util/order_utils/execute_add_invoice.rs
  • src/util/order_utils/execute_admin_add_solver.rs
  • src/util/order_utils/execute_admin_cancel.rs
  • src/util/order_utils/execute_admin_settle.rs
  • src/util/order_utils/execute_finalize_dispute.rs
  • src/util/order_utils/execute_send_msg.rs
  • src/util/order_utils/execute_take_dispute.rs
  • src/util/order_utils/send_new_order.rs
  • src/util/order_utils/take_order.rs
💤 Files with no reviewable changes (3)
  • settings.toml
  • README.md
  • src/settings.rs

Comment thread src/util/dm_utils/dm_helpers.rs Outdated
Comment thread src/util/dm_utils/mod.rs Outdated
Comment thread src/util/mostro_info.rs Outdated
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.

🧹 Nitpick comments (2)
src/ui/key_handler/user_handlers.rs (1)

53-63: Consider bundling infrastructure dependencies into a context struct.

The 8-parameter signature warrants the #[allow(clippy::too_many_arguments)] suppression, but the infrastructure-related arguments (pool, client, mostro_pubkey, order_result_tx, dm_subscription_tx, mostro_info) are functionally cohesive and could be consolidated into a single context struct. This would eliminate the suppression, simplify both the function signature and its two call sites, and reduce coupling.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/ui/key_handler/user_handlers.rs` around lines 53 - 63, The function
execute_take_order_action has too many infra arguments; create a single context
struct (e.g., TakeOrderContext or ExecuteTakeOrderCtx) that contains: pool:
SqlitePool, client: Client, mostro_pubkey: nostr_sdk::PublicKey,
order_result_tx: UnboundedSender<crate::ui::OperationResult>,
dm_subscription_tx: UnboundedSender<crate::util::OrderDmSubscriptionCmd>, and
mostro_info: Option<crate::util::MostroInstanceInfo>; replace the multiple
parameters in execute_take_order_action with one ctx: TakeOrderContext (keep
app: &mut AppState and take_state: TakeOrderState), update all call sites to
construct and pass the context, ensure the context derives/uses Clone or is
wrapped in Arc if needed for ownership, and then remove the
#[allow(clippy::too_many_arguments)] on execute_take_order_action.
src/util/dm_utils/dm_helpers.rs (1)

16-45: Remove the review-note comments before merge.

Line 16, Line 23, Line 25, and Line 43 read like reviewer guidance rather than source-facing docs. They add noise without clarifying the helper’s contract. A short doc comment explaining why this wrapper exists would be cleaner.

✂️ Suggested cleanup
-// nip59::RANGE_RANDOM_TIMESTAMP_TWEAK — you already use `nip59::` elsewhere in the project
+/// Mirrors the SDK gift-wrap path, but applies PoW to the outer Gift Wrap
+/// before signing so relays that require NIP-13 accept the published event.
 fn gift_wrap_from_seal_with_pow(
     receiver: &PublicKey,
     seal: &Event,
     extra_tags: impl IntoIterator<Item = Tag>,
     pow: u8,
 ) -> Result<Event> {
-    // or map to anyhow in create_gift_wrap_event
     if seal.kind != nostr_sdk::Kind::Seal {
-        // same validation as upstream, or map_err to anyhow
         return Err(anyhow::anyhow!("Invalid kind"));
     }
@@
     EventBuilder::new(nostr_sdk::Kind::GiftWrap, content)
         .tags(tags)
         .custom_created_at(Timestamp::tweaked(nip59::RANGE_RANDOM_TIMESTAMP_TWEAK))
-        .pow(pow) // <-- this is what the SDK’s gift_wrap path does NOT do
+        .pow(pow)
         .sign_with_keys(&ephem)
         .map_err(|e| anyhow::anyhow!("Failed to sign gift wrap: {e}"))
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/util/dm_utils/dm_helpers.rs` around lines 16 - 45, Remove the inline
reviewer-note comments inside the gift_wrap_from_seal_with_pow helper and
replace them with a concise doc comment that explains the purpose and contract
of the function (why this wrapper exists, what it validates e.g., ensures
seal.kind == nostr_sdk::Kind::Seal, and that it encrypts and signs using an
ephemeral key), while leaving the implementation (use of
nip59::RANGE_RANDOM_TIMESTAMP_TWEAK, constructing content via nip44::encrypt,
pushing Tag::public_key(*receiver), setting custom_created_at on EventBuilder,
and signing with ephem and .pow(pow)) unchanged; specifically delete the
reviewer guidance lines referencing nip59, mapping errors/validation, and the
SDK note, and add a short /// doc comment above gift_wrap_from_seal_with_pow
describing intent and behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/ui/key_handler/user_handlers.rs`:
- Around line 53-63: The function execute_take_order_action has too many infra
arguments; create a single context struct (e.g., TakeOrderContext or
ExecuteTakeOrderCtx) that contains: pool: SqlitePool, client: Client,
mostro_pubkey: nostr_sdk::PublicKey, order_result_tx:
UnboundedSender<crate::ui::OperationResult>, dm_subscription_tx:
UnboundedSender<crate::util::OrderDmSubscriptionCmd>, and mostro_info:
Option<crate::util::MostroInstanceInfo>; replace the multiple parameters in
execute_take_order_action with one ctx: TakeOrderContext (keep app: &mut
AppState and take_state: TakeOrderState), update all call sites to construct and
pass the context, ensure the context derives/uses Clone or is wrapped in Arc if
needed for ownership, and then remove the #[allow(clippy::too_many_arguments)]
on execute_take_order_action.

In `@src/util/dm_utils/dm_helpers.rs`:
- Around line 16-45: Remove the inline reviewer-note comments inside the
gift_wrap_from_seal_with_pow helper and replace them with a concise doc comment
that explains the purpose and contract of the function (why this wrapper exists,
what it validates e.g., ensures seal.kind == nostr_sdk::Kind::Seal, and that it
encrypts and signs using an ephemeral key), while leaving the implementation
(use of nip59::RANGE_RANDOM_TIMESTAMP_TWEAK, constructing content via
nip44::encrypt, pushing Tag::public_key(*receiver), setting custom_created_at on
EventBuilder, and signing with ephem and .pow(pow)) unchanged; specifically
delete the reviewer guidance lines referencing nip59, mapping errors/validation,
and the SDK note, and add a short /// doc comment above
gift_wrap_from_seal_with_pow describing intent and behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c68f9528-9f0b-4b4e-970c-ecb9f81588cc

📥 Commits

Reviewing files that changed from the base of the PR and between fb07709 and 9af9daa.

📒 Files selected for processing (8)
  • docs/MESSAGE_FLOW_AND_PROTOCOL.md
  • docs/POW_AND_OUTBOUND_EVENTS.md
  • docs/README.md
  • docs/SETTINGS_ANALYSIS.md
  • src/ui/key_handler/user_handlers.rs
  • src/util/dm_utils/dm_helpers.rs
  • src/util/dm_utils/mod.rs
  • src/util/mostro_info.rs
✅ Files skipped from review due to trivial changes (4)
  • docs/README.md
  • docs/SETTINGS_ANALYSIS.md
  • docs/MESSAGE_FLOW_AND_PROTOCOL.md
  • docs/POW_AND_OUTBOUND_EVENTS.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/util/dm_utils/mod.rs
  • src/util/mostro_info.rs

Copy link
Copy Markdown
Contributor

@mostronatorcoder mostronatorcoder Bot left a comment

Choose a reason for hiding this comment

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

Deep review completed on latest head (9af9daa).

I validated the architectural change from static settings pow to dynamic PoW resolution from Mostro instance info (kind 38385), including full propagation through user/admin order flows and admin shared-key chat wrapping.

I also verified the custom gift-wrap path now applies .pow(pow) on the outer GiftWrap event and keeps NIP-59 timestamp tweaking intact, which fixes the key protocol gap this PR targets.

Local verification passed on this branch: cargo fmt --all -- --check, cargo clippy --all-targets --all-features -- -D warnings, and cargo test.

No blocking issues found.

@arkanoider arkanoider merged commit 0f8741e into main Apr 11, 2026
11 checks passed
@arkanoider arkanoider deleted the pow-fix branch April 11, 2026 12:51
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