Skip to content

feat(protocol): transport-aware DM listener for v2 inbound (step 6)#90

Merged
arkanoider merged 3 commits into
mainfrom
feat/protocol-v2-dm-listener
Jun 19, 2026
Merged

feat(protocol): transport-aware DM listener for v2 inbound (step 6)#90
arkanoider merged 3 commits into
mainfrom
feat/protocol-v2-dm-listener

Conversation

@arkanoider

@arkanoider arkanoider commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

Protocol v2 step 6 — complete inbound cutover for Mostro protocol DMs. v2 nodes can now receive live protocol traffic end-to-end.

  • Remove dm_listener_subscribe_transport GiftWrap clamp; subscribe/replay/waiter filters use filter_protocol_dm_from_mostro(transport, …) directly
  • Event gate: accept event.kind == transport.event_kind() (1059 v1 / 14 v2) instead of hardcoded GiftWrap
  • Listener waiter + tracked paths: unwrap_incoming (builds on feat(protocol): unify inbound DM parse on unwrap_incoming (v2 step 5) #89)
  • Add respawn_trade_dm_listener — restarts DM listener when manual Mostro Info refresh changes app.transport
  • Update contributor docs: protocol v2 DMs complete; P2P/admin chat unchanged (GiftWrap)

Builds on #89 (parse/replay unwrap_incoming), #88 (outbound), #87 (filters), #86 (transport discovery).

Context

Layer v1 v2 (this PR)
Subscribe .pubkey(trade).kind(1059) .author(mostro).pubkey(trade).kind(14)
Event gate GiftWrap kind 14
Decrypt unwrap_incoming unwrap_incoming

Breaking changes

None for v1 nodes.

Summary by CodeRabbit

  • New Features
    • Extended DM handling to support Protocol v2 (NIP-44) as transport-aware routing for both GiftWrap and signed kind-14 messages.
    • Added automatic restart of the trade DM listener when the active transport changes.
    • Improved DM listener subscription tracking and cleanup, including targeted unsubscription of listener-owned subscriptions.
  • Documentation
    • Updated DM/message flow docs to reflect Protocol v2 dual-transport behavior and completed support status.

Remove GiftWrap subscribe clamp; gate relay events on transport.event_kind(),
use unwrap_incoming in waiter/tracked paths, and respawn the listener when
manual Mostro Info refresh changes protocol transport.

Co-authored-by: Cursor <cursoragent@cursor.com>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 55b4b2b6-344a-4ee3-b226-9e20f059067f

📥 Commits

Reviewing files that changed from the base of the PR and between c343686 and 2418ff9.

📒 Files selected for processing (1)
  • src/ui/key_handler/async_tasks.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/ui/key_handler/async_tasks.rs

Walkthrough

The DM listener/router is generalized from GiftWrap-only to transport-aware routing by removing the AtomicBool transport clamp, adding listener-owned relay subscription ID tracking, switching decryptability checks to unwrap_incoming, gating events on transport.event_kind(), and introducing respawn_trade_dm_listener for hot-restart when the Mostro instance transport changes. Documentation is updated to mark Protocol v2 DMs as complete.

Changes

Protocol v2 dual-transport DM listener

Layer / File(s) Summary
Remove transport clamp; add listener-owned subscription tracking
src/util/dm_utils/mod.rs, src/util/mod.rs
Removes the AtomicBool-backed v2-to-GiftWrap clamp and adds register_dm_listener_subscription, unregister_dm_listener_subscription, and unsubscribe_dm_listener_subscriptions to track and clean up listener-owned relay subscriptions independently.
Transport-aware event gating and unwrap_incoming in the router
src/util/dm_utils/mod.rs
Relay notification handler now gates on event.kind == transport.event_kind(), introduces a per-event rumor_cache, and switches waiter-path and tracked-order-path decryptability checks from unwrap_message to unwrap_incoming. Startup replay filter and waiter subscription filter pass transport directly; terminal cleanup calls the new unregister helper.
ensure_order_dm_subscription: direct filter and sub ID registration
src/util/dm_utils/dm_helpers.rs
Builds the protocol-DM subscription filter via filter_protocol_dm_from_mostro(transport, ...) directly (removing dm_listener_subscribe_transport indirection) and registers the subscription ID with register_dm_listener_subscription.
respawn_trade_dm_listener: abort, hydrate, re-register, re-spawn
src/ui/key_handler/async_tasks.rs, src/ui/key_handler/mod.rs
Adds respawn_trade_dm_listener: aborts the current listener task, unsubscribes listener-owned subscriptions, re-hydrates active-order DM state from the DB, recreates the command channel, re-registers the DM router command sender, and spawns a new listen_for_order_messages task. Re-exports via key_handler/mod.rs.
main.rs: conditional DM listener restart on transport change
src/main.rs
In MostroInfoFetchResult::Ok, records the prior transport, applies updated Mostro info, and calls respawn_trade_dm_listener when the transport changed, logging any restart failure.
Docs updated to reflect Protocol v2 dual-transport completion
docs/README.md, docs/DM_LISTENER_FLOW.md, docs/MESSAGE_FLOW_AND_PROTOCOL.md
Describes transport-aware subscription, transport.event_kind() gating, unwrap_incoming, and filter_protocol_dm_from_mostro throughout; marks Protocol v2 DMs as complete and removes GiftWrap-only and asymmetric-inbound language.

Sequence Diagram(s)

sequenceDiagram
    participant MainLoop as main.rs (event loop)
    participant respawn as respawn_trade_dm_listener
    participant Client as nostr Client
    participant DB as SQLite
    participant Router as listen_for_order_messages
    participant Relay

    MainLoop->>MainLoop: MostroInfoFetchResult::Ok — transport changed?
    MainLoop->>respawn: call(app, client, pool, ...)
    respawn->>Router: abort current listener task
    respawn->>Client: unsubscribe_dm_listener_subscriptions
    respawn->>DB: hydrate startup active-order DM state
    respawn->>respawn: recreate dm_subscription_tx channel
    respawn->>respawn: register DM router command sender
    respawn->>Router: spawn listen_for_order_messages (transport-aware)
    Router->>Client: subscribe filter_protocol_dm_from_mostro(transport,...)
    Relay-->>Router: protocol DM event
    Router->>Router: gate event.kind == transport.event_kind()
    Router->>Router: unwrap_incoming(event) → route waiter or tracked order
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • MostroP2P/mostrix#86: Introduced protocol_version parsing and AppState.transport wiring that this PR consumes to detect transport changes and trigger listener restarts.
  • MostroP2P/mostrix#87: Introduced filter_protocol_dm_from_mostro, threaded transport through listen_for_order_messages, and introduced ensure_order_dm_subscription — the direct predecessors of this PR's subscription and gating changes.
  • MostroP2P/mostrix#89: Modified dm_utils/mod.rs to standardize inbound DM decoding through unwrap_incoming, which this PR further extends with transport-aware event kind gating.

Suggested reviewers

  • ermeme

🐇 Two transports hop into view,
GiftWrap and kind-14 too!
The clamp is gone, the router's free,
unwrap_incoming — the key!
Respawn the listener, change the wire,
Protocol v2 leaps ever higher! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: implementing transport-aware DM listener support for protocol v2 inbound messages, which is the primary objective of this PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/protocol-v2-dm-listener

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.

@mostronatorcoder

Copy link
Copy Markdown
Contributor

I think there is a real blocker in respawn_trade_dm_listener().

Right now it does this:

message_listener_handle.abort();
client.unsubscribe_all().await;

The problem is that this Client is shared with more than just the trade DM listener. The order/dispute fetch scheduler also installs live relay subscriptions on the same client:

  • fetch_scheduler.rs subscribes to live order updates
  • fetch_scheduler.rs subscribes to live dispute updates

So unsubscribe_all() here does not just reset DM subscriptions, it also tears down unrelated live subscriptions owned by the scheduler.

That means a transport flip / manual Mostro info refresh can silently break real-time order/dispute updates until some later full reload happens to recreate them.

I think this needs a narrower unsubscribe strategy (DM-listener-owned subscription ids only), or a coordinated respawn of every subscription user on that shared client. But unsubscribe_all() inside a DM-listener helper looks too broad and correctness-breaking.

@ermeme ermeme Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review Summary

Verdict: Request Changes

Blocking

  • respawn_trade_dm_listener() calls client.unsubscribe_all(), which will also drop the live order/dispute subscriptions owned by the fetch schedulers.
    The helper only respawns the DM listener, so after a transport change the app can silently lose order book / dispute updates until those other tasks are restarted too.

Looks Good

  • The inbound parsing cutover to unwrap_incoming() is consistent with the earlier transport work.
  • The test suite passed locally.

Comment thread src/ui/key_handler/async_tasks.rs Outdated
log_context: &str,
) -> Result<(), String> {
message_listener_handle.abort();
client.unsubscribe_all().await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is too broad for a DM-listener respawn: unsubscribe_all() will also remove the live order/dispute subscriptions owned by the fetch schedulers. Unless you respawn those tasks here too, a transport refresh can silently stop order book / dispute updates.

respawn_trade_dm_listener must not call client.unsubscribe_all() because
the shared Client also carries order/dispute scheduler subscriptions.
Track DM listener SubscriptionIds and tear down via
unsubscribe_dm_listener_subscriptions() instead.

Co-authored-by: Cursor <cursoragent@cursor.com>
@mostronatorcoder

Copy link
Copy Markdown
Contributor

Re-checked the latest revision: this resolves the blocker I raised about unsubscribe_all() being too broad.

The respawn path now uses a DM-listener-specific unsubscribe helper instead:

// DM listener subs only — `Client` is shared with order/dispute fetch schedulers.
unsubscribe_dm_listener_subscriptions(client).await;

and the listener now tracks its own subscription ids via register_dm_listener_subscription(...) / unregister_dm_listener_subscription(...).

That is the right fix here, because it avoids tearing down unrelated live subscriptions owned by the order/dispute fetch schedulers when the DM listener is restarted after a transport change.

@ermeme ermeme Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review

Approved.

The previous blocker is fixed: the DM listener now unsubscribes only its own relay subscriptions, so order/dispute fetch schedulers keep their live subscriptions intact during transport respawn.

Also verified with cargo test --lib -- --nocapture (124 passed).

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/util/dm_utils/mod.rs`:
- Around line 91-99: The unsubscribe_dm_listener_subscriptions function drains
subscription IDs once, but there is a race condition where new DM subscriptions
can be registered after the drain completes but before the old listener task has
fully terminated, leaving old relay subscriptions alive and causing
duplicate/misrouted protocol DM handling. Ensure that when
respawn_trade_dm_listener aborts the old listener and calls
unsubscribe_dm_listener_subscriptions, it properly awaits termination of the old
listener task before triggering the unsubscribe operation, so that no new
register_dm_listener_subscription calls can occur between the drain and the
actual unsubscriptions being issued to the client.
🪄 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: 70fbb499-0bb0-47dc-88ca-a91139c8b986

📥 Commits

Reviewing files that changed from the base of the PR and between 37c2e45 and c343686.

📒 Files selected for processing (9)
  • docs/DM_LISTENER_FLOW.md
  • docs/MESSAGE_FLOW_AND_PROTOCOL.md
  • docs/README.md
  • src/main.rs
  • src/ui/key_handler/async_tasks.rs
  • src/ui/key_handler/mod.rs
  • src/util/dm_utils/dm_helpers.rs
  • src/util/dm_utils/mod.rs
  • src/util/mod.rs

Comment thread src/util/dm_utils/mod.rs
Abort alone does not stop register_dm_listener_subscription immediately;
await the join handle so the registry drain cannot miss subs registered
after take() by a still-running listener task.

Co-authored-by: Cursor <cursoragent@cursor.com>
@arkanoider arkanoider merged commit 3926277 into main Jun 19, 2026
13 checks passed
@arkanoider arkanoider deleted the feat/protocol-v2-dm-listener branch June 19, 2026 18:33
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