From fa6df0ff4f8b72978f32531594686832218aa546 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 9 Nov 2026 23:40:57 -0500 Subject: [PATCH 1/2] test(payments): pin the NWC reply arriving the moment the wallet sees the request --- crates/nostream-services/tests/nwc_relay.rs | 120 ++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/crates/nostream-services/tests/nwc_relay.rs b/crates/nostream-services/tests/nwc_relay.rs index 0a217bc1..78da2c09 100644 --- a/crates/nostream-services/tests/nwc_relay.rs +++ b/crates/nostream-services/tests/nwc_relay.rs @@ -9,6 +9,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; +use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; @@ -108,6 +109,100 @@ async fn relay( format!("ws://127.0.0.1:{port}") } +/// What a [`strict_relay`] read: the verbs, in order, and whether it had to drop the reply. +#[derive(Default)] +struct Seen { + verbs: Mutex>, + dropped: AtomicBool, +} + +impl Seen { + fn verbs(&self) -> Vec<&'static str> { + self.verbs.lock().expect("the record").clone() + } + + fn dropped(&self) -> bool { + self.dropped.load(Ordering::SeqCst) + } +} + +/// A websocket relay that registers a `REQ` and answers the `EVENT` at once. +/// +/// A kind-23195 reply is ephemeral, so a relay live-forwards it to the subscriptions already +/// registered on the connection and stores nothing. This double behaves that way: it answers +/// from its `EVENT` arm only when a `REQ` has registered a subscription, and otherwise drops +/// the reply and closes — so a client that publishes the request first never reads one. +async fn strict_relay(payload: serde_json::Value) -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let port = listener.local_addr().expect("local addr").port(); + let seen = Arc::new(Seen::default()); + let record = Arc::clone(&seen); + + tokio::spawn(async move { + let (socket, _) = listener.accept().await.expect("accept"); + let mut socket = tokio_tungstenite::accept_async(socket) + .await + .expect("the handshake"); + let mut subscription: Option = None; + + while let Some(Ok(Message::Text(frame))) = socket.next().await { + let frame: serde_json::Value = serde_json::from_str(&frame).expect("a frame"); + let parts = frame.as_array().expect("a frame array"); + + match parts.first().and_then(serde_json::Value::as_str) { + Some("REQ") => { + record.verbs.lock().expect("the record").push("REQ"); + subscription = Some(parts[1].as_str().expect("the subscription").to_owned()); + } + Some("EVENT") => { + record.verbs.lock().expect("the record").push("EVENT"); + let Some(subscription) = subscription.as_deref() else { + record.dropped.store(true, Ordering::SeqCst); + break; + }; + let request: Event = + serde_json::from_value(parts[1].clone()).expect("the request event"); + let content = nip04::encrypt( + &WALLET_SECRET, + &request.pubkey, + &payload.to_string(), + &[3u8; 16], + ) + .expect("the wallet encrypts its reply"); + + let mut reply = Event { + id: EventId::from_byte_array([0; 32]), + pubkey: request.pubkey, + created_at: chrono::Utc::now().timestamp(), + kind: Kind(23_195), + tags: vec![ + vec!["e".to_owned(), request.id.to_string()], + vec!["p".to_owned(), request.pubkey.to_string()], + ], + content, + sig: Signature::from_byte_array([0; 64]), + }; + sign_event(&WALLET_SECRET, &mut reply).expect("the wallet signs its reply"); + + let _ = socket + .send(Message::Text( + json!(["EVENT", subscription, reply]).to_string().into(), + )) + .await; + break; + } + _ => {} + } + } + + // The client reads until the socket closes; closing here makes a reply that was never + // sent fail the request instead of waiting for the transport's own deadline. + let _ = socket.close(None).await; + }); + + (format!("ws://127.0.0.1:{port}"), seen) +} + fn make_invoice() -> Nip47Request { Nip47Request { method: "make_invoice".to_owned(), @@ -115,6 +210,31 @@ fn make_invoice() -> Nip47Request { } } +/// A wallet answers the moment it decrypts the request, so its reply can be published while +/// the client is still setting up. The reply is ephemeral and live-forwarded only to +/// registered subscriptions, so the `REQ` has to reach the relay before the `EVENT`. +#[tokio::test] +async fn a_reply_published_the_moment_the_wallet_sees_the_event_is_received() { + let invoice = json!({ "invoice": "lnbc1", "payment_hash": "ab" }); + let (relay, seen) = strict_relay(json!({ + "result_type": "make_invoice", + "result": invoice.clone(), + "error": null, + })) + .await; + + let transport = NwcRelayTransport::new(&nwc_url(&relay)).expect("the url parses"); + let reply = transport.request(&make_invoice()).await; + + assert_eq!(seen.verbs(), vec!["REQ", "EVENT"]); + assert!( + !seen.dropped(), + "the relay dropped the reply: no subscription was registered when the EVENT arrived" + ); + let response = reply.expect("the reply"); + assert_eq!(response.result, invoice); +} + #[tokio::test] async fn a_reply_is_correlated_by_its_e_tag_not_by_a_payload_id() { let relay = relay(|published| { From cce07fb6b8a0605d88f73afdc87fbb95a73200e2 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 9 Nov 2026 23:40:57 -0500 Subject: [PATCH 2/2] fix(payments): send the NWC subscription before the request it asks about --- .changeset/nwc-request-before-event.md | 11 +++++++++++ .../src/payments/processors/nwc_relay.rs | 6 +++++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 .changeset/nwc-request-before-event.md diff --git a/.changeset/nwc-request-before-event.md b/.changeset/nwc-request-before-event.md new file mode 100644 index 00000000..d7ea2662 --- /dev/null +++ b/.changeset/nwc-request-before-event.md @@ -0,0 +1,11 @@ +--- +--- + +fix(payments): send the NWC subscription before the request it asks about (#1099) + +`NwcRelayTransport::request` published its kind-23194 request before the `REQ` that +registers the subscription for the kind-23195 reply. A reply is ephemeral, so the relay +live-forwards it only to subscriptions already registered and stores nothing: a wallet that +answered the moment it decrypted the request had its reply dropped, and the payment call +failed as a 10-second `reply timeout` rather than as an error. The two frames now go out +`REQ` first. No other behaviour changes. diff --git a/crates/nostream-services/src/payments/processors/nwc_relay.rs b/crates/nostream-services/src/payments/processors/nwc_relay.rs index bdca8e74..22f58276 100644 --- a/crates/nostream-services/src/payments/processors/nwc_relay.rs +++ b/crates/nostream-services/src/payments/processors/nwc_relay.rs @@ -145,7 +145,11 @@ impl Nip47Transport for NwcRelayTransport { }); let request_frame = serde_json::json!(["REQ", subscription, subscription_filter]); - for frame in [event_frame, request_frame] { + // The subscription registers before the request it asks about: a kind-23195 reply + // is ephemeral, so the relay live-forwards it only to subscriptions already + // registered and stores nothing. Publishing the `EVENT` first would lose a wallet's + // immediate reply rather than delay it. + for frame in [request_frame, event_frame] { socket .send(Message::Text(frame.to_string().into())) .await