Skip to content
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

sdk: allow to change Keys #170

Merged
merged 3 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions bindings/nostr-sdk-js/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ impl JsClient {

/// Get current `Keys`
#[wasm_bindgen(getter)]
pub fn keys(&self) -> JsKeys {
self.inner.keys().into()
pub async fn keys(&self) -> JsKeys {
Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't turning a synchronous function into an asynchronous one in the public API a breaking change?

Copy link
Member Author

@yukibtc yukibtc Sep 18, 2023

Choose a reason for hiding this comment

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

Yes, it's a breaking change. I usually try to avoid breaking change, but in the last versions happened more frequently to implement new features.

In the README.md I written that, since the library it's in ALPHA state, the APIs could/will change in breaking ways.

self.inner.keys().await.into()
}

/// Completely shutdown `Client`
Expand Down
2 changes: 1 addition & 1 deletion crates/nostr-sdk/examples/nostr-connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn main() -> Result<()> {
client.add_relay(relay_url, None).await?;

let metadata = NostrConnectMetadata::new("Nostr SDK").url(Url::parse("https://example.com")?);
let nostr_connect_uri: NostrConnectURI = client.nostr_connect_uri(metadata)?;
let nostr_connect_uri: NostrConnectURI = client.nostr_connect_uri(metadata).await?;

println!("\n###############################################\n");
println!("Nostr Connect URI: {nostr_connect_uri}");
Expand Down
7 changes: 6 additions & 1 deletion crates/nostr-sdk/src/client/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,12 @@ impl Client {

/// Get current [`Keys`]
pub fn keys(&self) -> Keys {
self.client.keys()
RUNTIME.block_on(async { self.client.keys().await })
}

/// Change [`Keys`]
pub fn set_keys(&self, keys: &Keys) {
RUNTIME.block_on(async { self.client.set_keys(keys).await })
}

/// Start a previously stopped client
Expand Down
51 changes: 33 additions & 18 deletions crates/nostr-sdk/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use nostr::{
Metadata, Result, Tag,
};
use nostr_sdk_net::futures_util::Future;
use tokio::sync::broadcast;
use tokio::sync::{broadcast, RwLock};

#[cfg(feature = "blocking")]
pub mod blocking;
Expand Down Expand Up @@ -111,7 +111,7 @@ pub enum Error {
#[derive(Debug, Clone)]
pub struct Client {
pool: RelayPool,
keys: Keys,
keys: Arc<RwLock<Keys>>,
opts: Options,
dropped: Arc<AtomicBool>,
#[cfg(feature = "nip46")]
Expand Down Expand Up @@ -167,7 +167,7 @@ impl Client {
pub fn with_opts(keys: &Keys, opts: Options) -> Self {
Self {
pool: RelayPool::new(opts.pool),
keys: keys.clone(),
keys: Arc::new(RwLock::new(keys.clone())),
opts,
dropped: Arc::new(AtomicBool::new(false)),
#[cfg(feature = "nip46")]
Expand All @@ -190,7 +190,7 @@ impl Client {
) -> Self {
Self {
pool: RelayPool::new(opts.pool),
keys: app_keys.clone(),
keys: Arc::new(RwLock::new(app_keys.clone())),
opts,
dropped: Arc::new(AtomicBool::new(false)),
remote_signer: Some(remote_signer),
Expand All @@ -203,8 +203,15 @@ impl Client {
}

/// Get current [`Keys`]
pub fn keys(&self) -> Keys {
self.keys.clone()
pub async fn keys(&self) -> Keys {
Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't turning a synchronous function into an asynchronous one in the public API a breaking change?

let keys = self.keys.read().await;
keys.clone()
}

/// Change [`Keys`]
pub async fn set_keys(&self, keys: &Keys) {
let mut current_keys = self.keys.write().await;
*current_keys = keys.clone();
}

/// Get [`RelayPool`]
Expand All @@ -214,16 +221,17 @@ impl Client {

/// Get NIP46 uri
#[cfg(feature = "nip46")]
pub fn nostr_connect_uri(
pub async fn nostr_connect_uri(
Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't turning a synchronous function into an asynchronous one in the public API a breaking change?

&self,
metadata: NostrConnectMetadata,
) -> Result<NostrConnectURI, Error> {
let signer = self
.remote_signer
.as_ref()
.ok_or(Error::SignerNotConfigured)?;
let keys = self.keys.read().await;
Ok(NostrConnectURI::new(
self.keys.public_key(),
keys.public_key(),
signer.relay_url(),
metadata.name,
))
Expand Down Expand Up @@ -725,20 +733,22 @@ impl Client {
}
} else {
let difficulty: u8 = self.opts.get_difficulty();
let keys = self.keys.read().await;
if difficulty > 0 {
builder.to_pow_event(&self.keys, difficulty)?
builder.to_pow_event(&keys, difficulty)?
} else {
builder.to_event(&self.keys)?
builder.to_event(&keys)?
}
};

#[cfg(not(feature = "nip46"))]
let event: Event = {
let difficulty: u8 = self.opts.get_difficulty();
let keys = self.keys.read().await;
if difficulty > 0 {
builder.to_pow_event(&self.keys, difficulty)?
builder.to_pow_event(&keys, difficulty)?
} else {
builder.to_event(&self.keys)?
builder.to_event(&keys)?
}
};

Expand Down Expand Up @@ -847,17 +857,21 @@ impl Client {

filter = filter.author(signer_public_key.to_string());
} else {
filter = filter.author(self.keys.public_key().to_string());
let keys = self.keys.read().await;
filter = filter.author(keys.public_key().to_string());
}

filter
};

#[cfg(not(feature = "nip46"))]
let filter = Filter::new()
.author(self.keys.public_key().to_string())
.kind(Kind::ContactList)
.limit(1);
let filter: Filter = {
let keys = self.keys.read().await;
Filter::new()
.author(keys.public_key().to_string())
.kind(Kind::ContactList)
.limit(1)
};

Ok(vec![filter])
}
Expand Down Expand Up @@ -1012,7 +1026,8 @@ impl Client {
return Err(Error::ResponseNotMatchRequest);
}
} else {
EventBuilder::new_encrypted_direct_msg(&self.keys, receiver, msg, reply_to)?
let keys = self.keys.read().await;
EventBuilder::new_encrypted_direct_msg(&keys, receiver, msg, reply_to)?
};

#[cfg(not(feature = "nip46"))]
Expand Down
38 changes: 22 additions & 16 deletions crates/nostr-sdk/src/client/signer/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,14 @@ impl Client {
.ok_or(Error::SignerNotConfigured)?;

if signer.signer_public_key().await.is_none() {
let keys = self.keys.read().await;
let public_key = keys.public_key();
let secret_key = keys.secret_key()?;
drop(keys);

let id = SubscriptionId::generate();
let filter = Filter::new()
.pubkey(self.keys.public_key())
.pubkey(public_key)
.kind(Kind::NostrConnect)
.since(Timestamp::now());

Expand All @@ -127,14 +132,11 @@ impl Client {
while let Ok(notification) = notifications.recv().await {
if let RelayPoolNotification::Event(_url, event) = notification {
if event.kind == Kind::NostrConnect {
let msg: String = nip04::decrypt(
&self.keys.secret_key()?,
&event.pubkey,
&event.content,
)?;
let msg: String =
nip04::decrypt(&secret_key, &event.pubkey, &event.content)?;
let msg = Message::from_json(msg)?;
if let Ok(Request::Connect(public_key)) = msg.to_request() {
signer.set_signer_public_key(public_key).await;
if let Ok(Request::Connect(pk)) = msg.to_request() {
signer.set_signer_public_key(pk).await;
break;
}
}
Expand Down Expand Up @@ -172,14 +174,22 @@ impl Client {
let msg = Message::request(req.clone());
let req_id = msg.id();

let keys = self.keys.read().await;
let public_key = keys.public_key();
let secret_key = keys.secret_key()?;

// Build request
let event = EventBuilder::nostr_connect(&keys, signer_pubkey, msg)?.to_event(&keys)?;

// Drop keys
drop(keys);

// Send request to signer
let event =
EventBuilder::nostr_connect(&self.keys, signer_pubkey, msg)?.to_event(&self.keys)?;
self.send_event_to(signer.relay_url(), event).await?;

let sub_id = SubscriptionId::generate();
let filter = Filter::new()
.pubkey(self.keys.public_key())
.pubkey(public_key)
.kind(Kind::NostrConnect)
.since(Timestamp::now());

Expand All @@ -195,11 +205,7 @@ impl Client {
while let Ok(notification) = notifications.recv().await {
if let RelayPoolNotification::Event(_url, event) = notification {
if event.kind == Kind::NostrConnect {
let msg = nip04::decrypt(
&self.keys.secret_key()?,
&event.pubkey,
&event.content,
)?;
let msg = nip04::decrypt(&secret_key, &event.pubkey, &event.content)?;
let msg = Message::from_json(msg)?;

tracing::debug!("New message received: {msg:?}");
Expand Down
4 changes: 0 additions & 4 deletions crates/nostr-sdk/src/relay/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use async_utility::futures_util::stream::AbortHandle;
use async_utility::{futures_util, thread, time};
use nostr::message::relay::NegentropyErrorCode;
use nostr::message::MessageHandleError;
use nostr::negentropy::hex;
use nostr::negentropy::{self, Bytes, Negentropy};
#[cfg(feature = "nip11")]
use nostr::nips::nip11::RelayInformationDocument;
Expand All @@ -47,9 +46,6 @@ pub enum Error {
/// Negentropy error
#[error(transparent)]
Negentropy(#[from] negentropy::Error),
/// Hex error
#[error(transparent)]
Hex(#[from] hex::Error),
/// Channel timeout
#[error("channel timeout")]
ChannelTimeout,
Expand Down
2 changes: 1 addition & 1 deletion crates/nostr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ bip39 = { version = "2.0", default-features = false, optional = true }
bitcoin = { version = "0.30", default-features = false, features = ["rand", "serde"] }
cbc = { version = "0.1", optional = true }
chacha20 = { version = "0.9", optional = true }
negentropy = { git = "https://github.com/yukibtc/rust-negentropy", rev = "547592168356f423dd10773384b798e7c7139893", default-features = false }
negentropy = { version = "0.3", default-features = false }
nostr-ots = { version = "0.2", optional = true }
once_cell = { workspace = true, optional = true }
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-webpki-roots", "socks"], optional = true }
Expand Down