Skip to content

Commit 677cb7f

Browse files
committed
nostr: rework nip46 module
- Rename the `Message` and `Request` structs to `NostrConnectMessage` and `NostrConnectRequest`. - Rename the `Method` enum to `NostrConnectMethod`. - Add `NostrConnectResponse` struct. - Change types of `NostrConnectMessage` variants. - Required to pass the request method when deserializing the response, to make sure to deserialize the correct type. Closes #863 Pull-Request: #865 Signed-off-by: Yuki Kishimoto <[email protected]>
1 parent 8efe87d commit 677cb7f

File tree

7 files changed

+491
-345
lines changed

7 files changed

+491
-345
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
### Breaking changes
3131

32+
- nostr: rework nip46 module ([Yuki Kishimoto] at https://github.com/rust-nostr/nostr/pull/865)
3233
- pool: drop support for deprecated negentropy protocol ([Yuki Kishimoto] at https://github.com/rust-nostr/nostr/pull/853)
3334
- connect: encrypt NIP-46 events with NIP-44 instead of NIP-04 ([reyamir] at https://github.com/rust-nostr/nostr/pull/862)
3435
- connect: drop support for NIP-46 event decryption with NIP-04 ([Yuki Kishimoto] at https://github.com/rust-nostr/nostr/pull/864)

crates/nostr-cli/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ async fn handle_command(command: ShellCommand, client: &Client) -> Result<()> {
361361
struct CustomActions;
362362

363363
impl NostrConnectSignerActions for CustomActions {
364-
fn approve(&self, public_key: &PublicKey, req: &nip46::Request) -> bool {
364+
fn approve(&self, public_key: &PublicKey, req: &NostrConnectRequest) -> bool {
365365
println!("Public key: {public_key}");
366366
println!("{req:#?}\n");
367367
io::ask("Approve request?").unwrap_or_default()

crates/nostr-connect/examples/nostr-connect-signer.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
// Distributed under the MIT software license
44

55
use dialoguer::Confirm;
6-
use nostr::nips::nip46::Request;
76
use nostr_connect::prelude::*;
87

98
const SIGNER_SECRET_KEY: &str = "nsec12kcgs78l06p30jz7z7h3n2x2cy99nw2z6zspjdp7qc206887mwvs95lnkx";
@@ -38,7 +37,7 @@ async fn main() -> Result<()> {
3837
struct CustomActions;
3938

4039
impl NostrConnectSignerActions for CustomActions {
41-
fn approve(&self, public_key: &PublicKey, req: &Request) -> bool {
40+
fn approve(&self, public_key: &PublicKey, req: &NostrConnectRequest) -> bool {
4241
println!("Public key: {public_key}");
4342
println!("{req:#?}\n");
4443
Confirm::new()

crates/nostr-connect/src/client.rs

Lines changed: 63 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::sync::Arc;
1010
use std::time::Duration;
1111

1212
use async_utility::time;
13-
use nostr::nips::nip46::{Message, Request, ResponseResult};
13+
use nostr::nips::nip46::ResponseResult;
1414
use nostr_relay_pool::prelude::*;
1515
use tokio::sync::broadcast::Receiver;
1616
use tokio::sync::OnceCell;
@@ -224,7 +224,7 @@ impl NostrConnect {
224224
}
225225

226226
#[inline]
227-
async fn send_request(&self, req: Request) -> Result<ResponseResult, Error> {
227+
async fn send_request(&self, req: NostrConnectRequest) -> Result<ResponseResult, Error> {
228228
// Get remote signer public key
229229
let remote_signer_public_key: PublicKey = *self.remote_signer_public_key().await?;
230230

@@ -235,13 +235,13 @@ impl NostrConnect {
235235

236236
async fn send_request_with_pk(
237237
&self,
238-
req: Request,
238+
req: NostrConnectRequest,
239239
remote_signer_public_key: PublicKey,
240240
) -> Result<ResponseResult, Error> {
241241
let secret_key: &SecretKey = self.app_keys.secret_key();
242242

243243
// Convert request to event
244-
let msg = Message::request(req);
244+
let msg = NostrConnectMessage::request(&req);
245245
tracing::debug!("Sending '{msg}' NIP46 message");
246246

247247
let req_id = msg.id().to_string();
@@ -260,40 +260,40 @@ impl NostrConnect {
260260
if event.kind == Kind::NostrConnect {
261261
let msg: String =
262262
nip44::decrypt(secret_key, &event.pubkey, event.content.as_str())?;
263-
let msg: Message = Message::from_json(msg)?;
263+
let msg: NostrConnectMessage = NostrConnectMessage::from_json(msg)?;
264264

265265
tracing::debug!("Received NIP46 message: '{msg}'");
266266

267-
if let Message::Response { id, result, error } = &msg {
268-
if &req_id == id {
269-
if msg.is_auth_url() {
270-
if let (Some(auth_url), Some(handler)) =
271-
(error, &self.auth_url_handler)
272-
{
273-
match Url::parse(auth_url) {
274-
Ok(url) => {
275-
if let Err(e) = handler.on_auth_url(url).await {
276-
tracing::error!(
277-
"Impossible to handle `auth_url`: {e}"
278-
);
279-
}
280-
}
281-
Err(e) => {
282-
tracing::error!("Can't parse `auth_url`: {e}")
267+
if req_id == msg.id() && msg.is_response() {
268+
let response: NostrConnectResponse = msg.to_response(req.method())?;
269+
270+
if response.is_auth_url() {
271+
if let (Some(auth_url), Some(handler)) =
272+
(response.error, &self.auth_url_handler)
273+
{
274+
match Url::parse(&auth_url) {
275+
Ok(url) => {
276+
if let Err(e) = handler.on_auth_url(url).await {
277+
tracing::error!(
278+
"Impossible to handle `auth_url`: {e}"
279+
);
283280
}
284281
}
282+
Err(e) => {
283+
tracing::error!("Can't parse `auth_url`: {e}")
284+
}
285285
}
286-
} else {
287-
if let Some(result) = result {
288-
return Ok(result.clone());
289-
}
290-
291-
if let Some(error) = error {
292-
return Err(Error::Response(error.to_owned()));
293-
}
286+
}
287+
} else {
288+
if let Some(error) = response.error {
289+
return Err(Error::Response(error));
290+
}
294291

295-
break;
292+
if let Some(result) = response.result {
293+
return Ok(result);
296294
}
295+
296+
break;
297297
}
298298
}
299299
}
@@ -308,35 +308,35 @@ impl NostrConnect {
308308

309309
/// Connect msg
310310
async fn connect(&self, remote_signer_public_key: PublicKey) -> Result<(), Error> {
311-
let req = Request::Connect {
311+
let req = NostrConnectRequest::Connect {
312312
public_key: remote_signer_public_key,
313313
secret: self.secret.clone(),
314314
};
315315
let res = self
316316
.send_request_with_pk(req, remote_signer_public_key)
317317
.await?;
318-
Ok(res.to_connect()?)
318+
Ok(res.to_ack()?)
319319
}
320320

321321
/// Sign an [UnsignedEvent]
322322
pub async fn get_relays(&self) -> Result<HashMap<RelayUrl, RelayPermissions>, Error> {
323-
let req = Request::GetRelays;
323+
let req = NostrConnectRequest::GetRelays;
324324
let res = self.send_request(req).await?;
325325
Ok(res.to_get_relays()?)
326326
}
327327

328328
async fn _get_public_key(&self) -> Result<&PublicKey, Error> {
329329
self.user_public_key
330330
.get_or_try_init(|| async {
331-
let res = self.send_request(Request::GetPublicKey).await?;
331+
let res = self.send_request(NostrConnectRequest::GetPublicKey).await?;
332332
Ok(res.to_get_public_key()?)
333333
})
334334
.await
335335
}
336336

337337
/// Sign an [UnsignedEvent]
338338
async fn _sign_event(&self, unsigned: UnsignedEvent) -> Result<Event, Error> {
339-
let req = Request::SignEvent(unsigned);
339+
let req = NostrConnectRequest::SignEvent(unsigned);
340340
let res = self.send_request(req).await?;
341341
Ok(res.to_sign_event()?)
342342
}
@@ -346,51 +346,51 @@ impl NostrConnect {
346346
public_key: PublicKey,
347347
content: String,
348348
) -> Result<String, Error> {
349-
let req = Request::Nip04Encrypt {
349+
let req = NostrConnectRequest::Nip04Encrypt {
350350
public_key,
351351
text: content,
352352
};
353353
let res = self.send_request(req).await?;
354-
Ok(res.to_encrypt_decrypt()?)
354+
Ok(res.to_nip04_encrypt()?)
355355
}
356356

357357
async fn _nip04_decrypt(
358358
&self,
359359
public_key: PublicKey,
360360
ciphertext: String,
361361
) -> Result<String, Error> {
362-
let req = Request::Nip04Decrypt {
362+
let req = NostrConnectRequest::Nip04Decrypt {
363363
public_key,
364364
ciphertext,
365365
};
366366
let res = self.send_request(req).await?;
367-
Ok(res.to_encrypt_decrypt()?)
367+
Ok(res.to_nip04_decrypt()?)
368368
}
369369

370370
async fn _nip44_encrypt(
371371
&self,
372372
public_key: PublicKey,
373373
content: String,
374374
) -> Result<String, Error> {
375-
let req = Request::Nip44Encrypt {
375+
let req = NostrConnectRequest::Nip44Encrypt {
376376
public_key,
377377
text: content,
378378
};
379379
let res = self.send_request(req).await?;
380-
Ok(res.to_encrypt_decrypt()?)
380+
Ok(res.to_nip44_encrypt()?)
381381
}
382382

383383
async fn _nip44_decrypt(
384384
&self,
385385
public_key: PublicKey,
386386
payload: String,
387387
) -> Result<String, Error> {
388-
let req = Request::Nip44Decrypt {
388+
let req = NostrConnectRequest::Nip44Decrypt {
389389
public_key,
390390
ciphertext: payload,
391391
};
392392
let res = self.send_request(req).await?;
393-
Ok(res.to_encrypt_decrypt()?)
393+
Ok(res.to_nip44_decrypt()?)
394394
}
395395

396396
/// Completely shutdown
@@ -423,25 +423,29 @@ async fn get_remote_signer_public_key(
423423
tracing::debug!("Received Nostr Connect message: '{msg}'");
424424

425425
// Parse message
426-
let msg: Message = Message::from_json(msg)?;
426+
let msg: NostrConnectMessage = NostrConnectMessage::from_json(msg)?;
427427

428428
// Match message
429-
match msg {
430-
Message::Request {
431-
req: Request::Connect { public_key, .. },
432-
..
433-
} => {
434-
return Ok(GetRemoteSignerPublicKey::WithUserPublicKey {
435-
remote: event.pubkey,
436-
user: public_key,
437-
});
429+
match &msg {
430+
NostrConnectMessage::Request { .. } => {
431+
if let Ok(NostrConnectRequest::Connect { public_key, .. }) =
432+
msg.to_request()
433+
{
434+
return Ok(GetRemoteSignerPublicKey::WithUserPublicKey {
435+
remote: event.pubkey,
436+
user: public_key,
437+
});
438+
}
439+
}
440+
NostrConnectMessage::Response { .. } => {
441+
if let Ok(NostrConnectResponse {
442+
result: Some(ResponseResult::Ack),
443+
error: None,
444+
}) = msg.to_response(NostrConnectMethod::Connect)
445+
{
446+
return Ok(GetRemoteSignerPublicKey::RemoteOnly(event.pubkey));
447+
}
438448
}
439-
Message::Response {
440-
result: Some(ResponseResult::Connect),
441-
error: None,
442-
..
443-
} => return Ok(GetRemoteSignerPublicKey::RemoteOnly(event.pubkey)),
444-
_ => {}
445449
}
446450
}
447451
}

0 commit comments

Comments
 (0)