WIP: feat: add self implement nostr sdk (nostrkit) #31

Closed
reya wants to merge 2 commits from feat/nostrkit into master
19 changed files with 630 additions and 612 deletions
Showing only changes of commit d2a17e54c4 - Show all commits

566
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -24,7 +24,7 @@ nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ] }
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44" ] }
# Others
anyhow = "1.0.44"

View File

@@ -373,10 +373,7 @@ impl ChatRegistry {
}
/// Get all messages for the provided signer
fn get_messages<T>(&mut self, signer: T, cx: &mut Context<Self>)
where
T: NostrSigner + 'static,
{
fn get_messages(&mut self, signer: Arc<dyn AsyncNostrSigner>, cx: &mut Context<Self>) {
let task = self.subscribe_gift_wrap_events(signer, cx);
self.tasks.push(cx.spawn(async move |this, cx| {
@@ -421,7 +418,7 @@ impl ChatRegistry {
while let Some((_url, res)) = stream.next().await {
if let Ok(event) = res {
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
let urls: Vec<RelayUrl> = nip17::extract_relay_list(&event).collect();
return Ok(urls);
}
}
@@ -431,10 +428,11 @@ impl ChatRegistry {
}
/// Continuously get gift wrap events for the signer
fn subscribe_gift_wrap_events<T>(&self, signer: T, cx: &App) -> Task<Result<(), Error>>
where
T: NostrSigner + 'static,
{
fn subscribe_gift_wrap_events(
&self,
signer: Arc<dyn AsyncNostrSigner>,
cx: &App,
) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let urls = self.get_messaging_relays(cx);
@@ -579,10 +577,9 @@ impl ChatRegistry {
I: Into<Room> + 'static,
{
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
cx.spawn(async move |this, cx| {
let signer = client.signer()?;
let public_key = signer.get_public_key().await.ok()?;
let room: Room = room.into().organize(&public_key);
@@ -712,9 +709,9 @@ impl ChatRegistry {
fn get_rooms_from_database(&self, cx: &App) -> Task<Result<HashSet<Room>, Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
// Get contacts
@@ -871,10 +868,10 @@ async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<Unwra
}
/// Attempts to unwrap a gift wrap event with a given signer.
async fn try_unwrap_with<T>(gift_wrap: &Event, signer: &T) -> Result<UnwrappedGift, Error>
where
T: NostrSigner + 'static,
{
async fn try_unwrap_with(
gift_wrap: &Event,
signer: &Arc<dyn AsyncNostrSigner>,
) -> Result<UnwrappedGift, Error> {
// Get the sealed event
let seal = signer
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)
@@ -906,26 +903,17 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
tags.push(Tag::identifier(id));
// Add a reference to the rumor's author
tags.push(Tag::custom(
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::A)),
[author],
));
tags.push(Tag::custom("a", [author]));
// Add a conversation id
tags.push(Tag::custom(
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::C)),
[conversation.to_string()],
));
tags.push(Tag::custom("c", [conversation.to_string()]));
// Add a reference to the rumor's id
tags.push(Tag::event(rumor_id));
// Add references to the rumor's participants
for receiver in rumor.tags.public_keys().copied() {
tags.push(Tag::custom(
TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::P)),
[receiver],
));
for receiver in rumor.tags.public_keys() {
tags.push(Tag::public_key(receiver));
}
// Convert rumor to json
@@ -934,7 +922,7 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
// Construct the event
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
.tags(tags)
.sign(&Keys::generate())
.sign_async(&Keys::generate())
.await?;
// Save the event to the database
@@ -960,7 +948,7 @@ async fn get_rumor(client: &Client, gift_wrap: EventId) -> Result<UnsignedEvent,
/// Get the conversation ID for a given rumor (message).
fn conversation_id(rumor: &UnsignedEvent) -> u64 {
let mut hasher = DefaultHasher::new();
let mut pubkeys: Vec<PublicKey> = rumor.tags.public_keys().copied().collect();
let mut pubkeys: Vec<PublicKey> = rumor.tags.public_keys().collect();
pubkeys.push(rumor.pubkey);
pubkeys.sort();
pubkeys.dedup();

View File

@@ -242,13 +242,13 @@ fn extract_mentions(content: &str) -> Vec<Mention> {
fn extract_reply_ids(inner: &Tags) -> Vec<EventId> {
let mut replies_to = vec![];
for tag in inner.filter(TagKind::e()) {
for tag in inner.iter().filter(|tag| tag.kind() == "e") {
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
replies_to.push(id);
}
}
for tag in inner.filter(TagKind::q()) {
for tag in inner.iter().filter(|tag| tag.kind() == "q") {
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
replies_to.push(id);
}

View File

@@ -1,15 +1,16 @@
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Error, anyhow};
use anyhow::Error;
use common::EventExt;
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use person::{Person, PersonRegistry};
use settings::{RoomConfig, SignerKind};
use state::{NostrRegistry, TIMEOUT};
use state::{CoopSigner, NostrRegistry, TIMEOUT};
use crate::NewMessage;
@@ -171,7 +172,8 @@ impl From<&UnsignedEvent> for Room {
let members = val.extract_public_keys();
let subject = val
.tags
.find(TagKind::Subject)
.iter()
.find(|tag| tag.kind() == "subject")
.and_then(|tag| tag.content().map(|s| s.to_owned().into()));
Room {
@@ -440,9 +442,7 @@ impl Room {
// Add subject tag if present
if let Some(value) = self.subject.as_ref() {
tags.push(Tag::from_standardized_without_cell(TagStandard::Subject(
value.to_string(),
)));
tags.push(Tag::custom("subject", vec![value.to_string()]));
}
// Add all reply tags
@@ -452,14 +452,13 @@ impl Room {
// Add all receiver tags
for member in members.into_iter() {
tags.push(Tag::from_standardized_without_cell(
TagStandard::PublicKey {
tags.push(
Nip01Tag::PublicKey {
public_key: member.public_key(),
relay_url: member.messaging_relay_hint(),
alias: None,
uppercase: false,
},
));
relay_hint: member.messaging_relay_hint(),
}
.to_tag(),
);
}
// Construct a direct message rumor event
@@ -474,9 +473,9 @@ impl Room {
/// Send rumor event to all members's messaging relays
pub fn send(&self, rumor: UnsignedEvent, cx: &App) -> Option<Task<Vec<SendReport>>> {
let config = self.config.clone();
let persons = PersonRegistry::global(cx);
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
@@ -484,6 +483,8 @@ impl Room {
let public_key = nostr.read(cx).signer().public_key()?;
let sender = persons.read(cx).get(&public_key, cx);
let config = self.config.clone();
// Get all members (excluding sender)
let members: Vec<Person> = self
.members
@@ -492,12 +493,10 @@ impl Room {
.map(|member| persons.read(cx).get(member, cx))
.collect();
Some(cx.background_spawn(async move {
Some(cx.spawn(async move |_cx| {
let signer_kind = config.signer_kind();
let backup = config.backup();
let user_signer = signer.get().await;
let encryption_signer = signer.get_encryption_signer().await;
let has_encryption_signer = signer.has_encryption_signer().await;
let mut sents = 0;
let mut reports = Vec::new();
@@ -516,33 +515,21 @@ impl Room {
}
// Sender didn't set up a decoupled encryption key
if encryption_signer.is_none() {
if !has_encryption_signer {
reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY));
continue;
}
}
// Determine the signer to use
let signer = match signer_kind {
SignerKind::Auto => {
if announcement.is_some()
&& let Some(encryption_signer) = encryption_signer.clone()
{
// Safe to unwrap due to earlier checks
encryption_signer
} else {
user_signer.clone()
}
}
SignerKind::Encryption => {
// Safe to unwrap due to earlier checks
encryption_signer.as_ref().unwrap().clone()
}
SignerKind::User => user_signer.clone(),
let use_encryption = match signer_kind {
SignerKind::Auto => announcement.is_some() && has_encryption_signer,
SignerKind::Encryption => true,
SignerKind::User => false,
};
// Send the gift wrap event and collect the report
match send_gift_wrap(&client, &signer, &member, &rumor, signer_kind).await {
match send_gift_wrap(&client, &signer, &member, &rumor, use_encryption).await {
Ok(report) => {
reports.push(report);
sents += 1;
@@ -559,25 +546,13 @@ impl Room {
let public_key = sender.public_key();
// Determine the signer to use
let signer = match signer_kind {
SignerKind::Auto => {
if sender.announcement().is_some()
&& let Some(encryption_signer) = encryption_signer.clone()
{
// Safe to unwrap due to earlier checks
encryption_signer
} else {
user_signer.clone()
}
}
SignerKind::Encryption => {
// Safe to unwrap due to earlier checks
encryption_signer.as_ref().unwrap().clone()
}
SignerKind::User => user_signer.clone(),
let use_encryption = match signer_kind {
SignerKind::Auto => sender.announcement().is_some() && has_encryption_signer,
SignerKind::Encryption => true,
SignerKind::User => false,
};
match send_gift_wrap(&client, &signer, &sender, &rumor, signer_kind).await {
match send_gift_wrap(&client, &signer, &sender, &rumor, use_encryption).await {
Ok(report) => reports.push(report),
Err(error) => {
let report = SendReport::new(public_key).error(error.to_string());
@@ -592,22 +567,19 @@ impl Room {
}
// Helper function to send a gift-wrapped event
async fn send_gift_wrap<T>(
async fn send_gift_wrap(
client: &Client,
signer: &T,
signer: &Arc<CoopSigner>,
receiver: &Person,
rumor: &UnsignedEvent,
config: &SignerKind,
) -> Result<SendReport, Error>
where
T: NostrSigner + 'static,
{
let k_tag = Tag::custom(TagKind::k(), vec!["14"]);
encryption: bool,
) -> Result<SendReport, Error> {
let k_tag = Tag::custom("k", vec!["14"]);
let mut extra_tags = vec![k_tag];
// Determine the receiver public key based on the config
let receiver = match config {
SignerKind::Auto => {
let receiver = match encryption {
true => {
if let Some(announcement) = receiver.announcement().as_ref() {
extra_tags.push(Tag::public_key(receiver.public_key()));
announcement.public_key()
@@ -615,19 +587,20 @@ where
receiver.public_key()
}
}
SignerKind::Encryption => {
if let Some(announcement) = receiver.announcement().as_ref() {
extra_tags.push(Tag::public_key(receiver.public_key()));
announcement.public_key()
} else {
return Err(anyhow!("User has no encryption announcement"));
}
}
SignerKind::User => receiver.public_key(),
false => receiver.public_key(),
};
// Construct the gift wrap event
let event = EventBuilder::gift_wrap(signer, &receiver, rumor.clone(), extra_tags).await?;
let event = match encryption {
true => {
let signer = signer.get_encryption_signer().await.unwrap();
EventBuilder::gift_wrap_async(&signer, &receiver, rumor.clone(), extra_tags).await?
}
false => {
let signer = signer.get().await;
EventBuilder::gift_wrap_async(&signer, &receiver, rumor.clone(), extra_tags).await?
}
};
// Send the gift wrap event and collect the report
let report = client

View File

@@ -18,7 +18,7 @@ impl EventExt for Event {
}
fn extract_public_keys(&self) -> Vec<PublicKey> {
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().collect();
public_keys.push(self.pubkey);
public_keys.into_iter().unique().collect()
@@ -46,7 +46,7 @@ impl EventExt for UnsignedEvent {
}
fn extract_public_keys(&self) -> Vec<PublicKey> {
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().collect();
public_keys.push(self.pubkey);
public_keys.into_iter().unique().sorted().collect()
}

View File

@@ -2,6 +2,7 @@ use std::cell::Cell;
use std::collections::HashSet;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow};
@@ -11,7 +12,7 @@ use gpui::{
};
use nostr_sdk::prelude::*;
use person::PersonRegistry;
use state::{Announcement, NostrRegistry, StateEvent, TIMEOUT, app_name};
use state::{Announcement, CoopSigner, NostrRegistry, StateEvent, TIMEOUT, app_name};
use theme::ActiveTheme;
use ui::avatar::Avatar;
use ui::button::Button;
@@ -110,6 +111,8 @@ impl DeviceRegistry {
fn handle_notifications(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let (tx, rx) = flume::bounded::<Event>(100);
self.tasks.push(cx.background_spawn(async move {
@@ -127,12 +130,12 @@ impl DeviceRegistry {
match event.kind {
Kind::Custom(4454) => {
if verify_author(&client, event.as_ref()).await {
if verify_author(&signer, event.as_ref()).await {
tx.send_async(event.into_owned()).await?;
}
}
Kind::Custom(4455) => {
if verify_author(&client, event.as_ref()).await {
if verify_author(&signer, event.as_ref()).await {
tx.send_async(event.into_owned()).await?;
}
}
@@ -181,7 +184,7 @@ impl DeviceRegistry {
/// Set the decoupled encryption key for the current user
fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
where
S: NostrSigner + 'static,
S: AsyncNostrSigner,
{
let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer();
@@ -203,9 +206,10 @@ impl DeviceRegistry {
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
cx.background_spawn(async move {
let keys = get_keys(&client).await?;
let keys = get_keys(&client, &signer).await?;
let content = keys.secret_key().to_bech32()?;
smol::fs::write(path, &content).await?;
@@ -218,9 +222,10 @@ impl DeviceRegistry {
pub fn get_announcement(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let task: Task<Result<Event, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let signer = signer.get().await;
let public_key = signer.get_public_key().await?;
// Construct the filter for the device announcement event
@@ -293,19 +298,24 @@ impl DeviceRegistry {
fn create_encryption(&self, keys: Keys, cx: &App) -> Task<Result<Keys, Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let secret = keys.secret_key().to_secret_hex();
let n = keys.public_key();
cx.background_spawn(async move {
// Construct an announcement event
let builder = EventBuilder::new(Kind::Custom(10044), "").tags(vec![
Tag::custom(TagKind::custom("n"), vec![n]),
Tag::client(app_name()),
]);
// Sign the event with user's signer
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::new(Kind::Custom(10044), "")
.tags(vec![
Tag::custom("n", vec![n]),
Nip89Tag::Client {
name: app_name().to_string(),
address: None,
}
.to_tag(),
])
.sign_async(&signer.get().await)
.await?;
// Publish announcement
client
@@ -315,7 +325,7 @@ impl DeviceRegistry {
.await?;
// Save device keys to the database
set_keys(&client, &secret).await?;
set_keys(&client, &signer, &secret).await?;
Ok(keys)
})
@@ -325,13 +335,14 @@ impl DeviceRegistry {
fn set_encryption(&mut self, event: &Event, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let announcement = Announcement::from(event);
let device_pubkey = announcement.public_key();
// Get encryption key from the database and compare with the announcement
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
let keys = get_keys(&client).await?;
let keys = get_keys(&client, &signer).await?;
// Compare the public key from the announcement with the one from the database
if keys.public_key() != device_pubkey {
@@ -403,14 +414,20 @@ impl DeviceRegistry {
Some(event) => Ok(Some(event)),
// No approval event found, construct a request event
None => {
// Construct an event for device key request
let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
Tag::client(app_name()),
]);
let signer = signer.get().await;
// Sign the event with user's signer
let event = client.sign_event_builder(builder).await?;
// Construct an event for device key request
let event = EventBuilder::new(Kind::Custom(4454), "")
.tags(vec![
Tag::custom("P", vec![app_pubkey]),
Nip89Tag::Client {
name: app_name().to_string(),
address: None,
}
.to_tag(),
])
.sign_async(&signer)
.await?;
// Send the event to write relays
client.send_event(&event).to_nip65().await?;
@@ -471,17 +488,19 @@ impl DeviceRegistry {
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let app_keys = nostr.read(cx).keys();
let app_signer: Arc<dyn AsyncNostrSigner> = Arc::new(app_keys);
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
let master = event
.tags
.find(TagKind::custom("P"))
.iter()
.find(|tag| tag.kind() == "P")
.and_then(|tag| tag.content())
.and_then(|content| PublicKey::parse(content).ok())
.context("Invalid event's tags")?;
let payload = event.content.as_str();
let decrypted = app_keys.nip44_decrypt(&master, payload).await?;
let decrypted = app_signer.nip44_decrypt(&master, payload).await?;
let secret = SecretKey::from_hex(&decrypted)?;
let keys = Keys::new(secret);
@@ -510,6 +529,7 @@ impl DeviceRegistry {
fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
// Get user's write relays
let event = event.clone();
@@ -517,31 +537,36 @@ impl DeviceRegistry {
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
// Get device keys
let keys = get_keys(&client).await?;
let keys = get_keys(&client, &signer).await?;
let public_key = keys.public_key();
let secret = keys.secret_key().to_secret_hex();
let device_signer: Arc<dyn AsyncNostrSigner> = Arc::new(keys);
let signer = signer.get().await;
// Extract the target public key from the event tags
let target = event
.tags
.find(TagKind::custom("P"))
.iter()
.find(|tag| tag.kind() == "P")
.and_then(|tag| tag.content())
.and_then(|content| PublicKey::parse(content).ok())
.context("Target is not a valid public key")?;
// Encrypt the device keys with the user's signer
let payload = keys.nip44_encrypt(&target, &secret).await?;
let payload = device_signer.nip44_encrypt(&target, &secret).await?;
// Construct the response event
//
// P tag: the current device's public key
// p tag: the requester's public key
let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![
Tag::custom(TagKind::custom("P"), vec![keys.public_key().to_hex()]),
Tag::public_key(target),
]);
// Sign the builder
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::new(Kind::Custom(4455), payload)
.tags(vec![
Tag::custom("P", vec![public_key.to_hex()]),
Tag::public_key(target),
])
.sign_async(&signer)
.await?;
// Send the response event to the user's relay list
client.send_event(&event).to_nip65().await?;
@@ -689,18 +714,15 @@ impl DeviceRegistry {
struct DeviceNotification;
/// Verify the author of an event
async fn verify_author(client: &Client, event: &Event) -> bool {
if let Some(signer) = client.signer()
&& let Ok(public_key) = signer.get_public_key().await
{
async fn verify_author(signer: &Arc<CoopSigner>, event: &Event) -> bool {
if let Ok(public_key) = signer.get_public_key().await {
return public_key == event.pubkey;
}
false
}
/// Encrypt and store device keys in the local database.
async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
let signer = client.signer().context("Signer not found")?;
async fn set_keys(client: &Client, signer: &Arc<CoopSigner>, secret: &str) -> Result<(), Error> {
let public_key = signer.get_public_key().await?;
// Encrypt the value
@@ -710,7 +732,7 @@ async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
let event = EventBuilder::new(Kind::ApplicationSpecificData, content)
.tag(Tag::identifier(IDENTIFIER))
.build(public_key)
.sign(&Keys::generate())
.sign_async(&Keys::generate())
.await?;
// Save the event to the database
@@ -720,8 +742,7 @@ async fn set_keys(client: &Client, secret: &str) -> Result<(), Error> {
}
/// Get device keys from the local database.
async fn get_keys(client: &Client) -> Result<Keys, Error> {
let signer = client.signer().context("Signer not found")?;
async fn get_keys(client: &Client, signer: &Arc<CoopSigner>) -> Result<Keys, Error> {
let public_key = signer.get_public_key().await?;
let filter = Filter::new()

View File

@@ -242,7 +242,7 @@ impl PersonRegistry {
/// Set messaging relays for a person
fn set_messaging_relays(&mut self, event: &Event, cx: &mut App) {
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).cloned().collect();
let urls: Vec<RelayUrl> = nip17::extract_relay_list(event).collect();
if let Some(person) = self.persons.get(&event.pubkey) {
person.update(cx, |person, cx| {

View File

@@ -193,15 +193,19 @@ impl RelayAuth {
fn auth(&self, req: &Arc<AuthRequest>, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let req = req.clone();
// Get all pending events for the relay
let pending_events = self.get_pending_events(req.url(), cx);
cx.background_spawn(async move {
let signer = signer.get().await;
// Construct event
let builder = EventBuilder::auth(req.challenge(), req.url().clone());
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::auth(req.challenge(), req.url().clone())
.sign_async(&signer)
.await?;
// Get the event ID
let id = event.id;

View File

@@ -16,14 +16,15 @@ impl From<&Event> for Announcement {
let public_key = val
.tags
.iter()
.find(|tag| tag.kind().as_str() == "n")
.find(|tag| tag.kind() == "n")
.and_then(|tag| tag.content())
.and_then(|c| PublicKey::parse(c).ok())
.unwrap_or(val.pubkey);
let client_name = val
.tags
.find(TagKind::Client)
.iter()
.find(|tag| tag.kind() == "client")
.and_then(|tag| tag.content())
.map(|c| c.to_string());

View File

@@ -3,7 +3,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow};
use anyhow::{Error, anyhow};
use common::config_dir;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
use nostr_connect::prelude::*;
@@ -130,10 +130,8 @@ impl NostrRegistry {
// Construct the nostr client
let client = ClientBuilder::default()
.signer(signer.clone())
.database(lmdb)
.gossip(NostrGossipMemory::unbounded())
.automatic_authentication(false)
.connect_timeout(Duration::from_secs(10))
.sleep_when_idle(SleepWhenIdle::Enabled {
timeout: Duration::from_secs(600),
@@ -236,10 +234,7 @@ impl NostrRegistry {
}
// Connect to all added relays
client
.connect()
.and_wait(Duration::from_secs(TIMEOUT))
.await;
client.connect().await;
Ok(())
});
@@ -262,70 +257,73 @@ impl NostrRegistry {
}));
}
/// Get the secret for a given npub.
pub fn get_secret(
&self,
public_key: PublicKey,
cx: &App,
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
/// Switch to a different account by public key
pub fn switch_account(&self, public_key: PublicKey, cx: &App) -> Result<(), Error> {
let client = self.client();
let signer = self.signer();
let npub = public_key.to_bech32().unwrap();
let key_path = self.key_dir.join(format!("{}.npub", npub));
let app_keys = self.app_keys.clone();
let app_signer: Arc<dyn NostrSigner> = Arc::new(app_keys.clone());
if let Ok(payload) = std::fs::read_to_string(key_path) {
if !payload.is_empty() {
cx.background_spawn(async move {
let decrypted = app_keys.nip44_decrypt(&public_key, &payload).await?;
let secret = SecretKey::parse(&decrypted)?;
let keys = Keys::new(secret);
if let Ok(payload) = std::fs::read_to_string(key_path)
&& !payload.is_empty()
{
let decrypted = app_signer.nip44_decrypt(&public_key, &payload)?;
Ok(keys.into_nostr_signer())
if let Ok(secret) = SecretKey::parse(&decrypted) {
let keys = Keys::new(secret);
cx.spawn(async move |_cx| {
signer.switch(keys).await;
client.unsubscribe_all().await.ok();
})
} else {
self.get_secret_keyring(&npub, cx)
.detach();
return Ok(());
} else if let Ok(uri) = NostrConnectUri::parse(decrypted) {
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
nip46.auth_url_handler(CoopAuthUrlHandler);
cx.spawn(async move |_cx| {
signer.switch(nip46).await;
client.unsubscribe_all().await.ok();
})
.detach();
return Ok(());
}
} else {
self.get_secret_keyring(&npub, cx)
}
Err(anyhow!("Secret not found"))
}
/// Get the secret for a given npub in the OS credentials store.
#[deprecated = "Use get_secret instead"]
fn get_secret_keyring(
&self,
user: &str,
cx: &App,
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
let read = cx.read_credentials(user);
/// Get the secret for a given npub.
pub fn get_secret(&self, public_key: PublicKey) -> Result<Arc<dyn AsyncNostrSigner>, Error> {
let npub = public_key.to_bech32().unwrap();
let key_path = self.key_dir.join(format!("{}.npub", npub));
let app_keys = self.app_keys.clone();
let app_signer: Arc<dyn NostrSigner> = Arc::new(self.app_keys.clone());
cx.background_spawn(async move {
let (_, secret) = read
.await
.map_err(|_| anyhow!("Failed to get signer. Please re-import the secret key"))?
.ok_or_else(|| anyhow!("Failed to get signer. Please re-import the secret key"))?;
if let Ok(payload) = std::fs::read_to_string(key_path)
&& !payload.is_empty()
{
let decrypted = app_signer.nip44_decrypt(&public_key, &payload)?;
// Try to parse as a direct secret key first
if let Ok(secret_key) = SecretKey::from_slice(&secret) {
return Ok(Keys::new(secret_key).into_nostr_signer());
if let Ok(secret) = SecretKey::parse(&decrypted) {
let keys = Keys::new(secret);
return Ok(Arc::new(keys));
} else if let Ok(uri) = NostrConnectUri::parse(decrypted) {
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
nip46.auth_url_handler(CoopAuthUrlHandler);
return Ok(Arc::new(nip46));
}
}
// Convert the secret into string
let sec = String::from_utf8(secret)
.map_err(|_| anyhow!("Failed to parse secret as UTF-8"))?;
// Try to parse as a NIP-46 URI
let uri =
NostrConnectUri::parse(&sec).map_err(|_| anyhow!("Failed to parse NIP-46 URI"))?;
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
// Set the auth URL handler
nip46.auth_url_handler(CoopAuthUrlHandler);
Ok(nip46.into_nostr_signer())
})
Err(anyhow!("Secret not found"))
}
/// Add a new npub to the keys directory
@@ -337,7 +335,7 @@ impl NostrRegistry {
) -> Task<Result<(), Error>> {
let npub = public_key.to_bech32().unwrap();
let key_path = self.key_dir.join(format!("{}.npub", npub));
let app_keys = self.app_keys.clone();
let app_keys: Arc<dyn AsyncNostrSigner> = Arc::new(self.app_keys.clone());
cx.background_spawn(async move {
// If the secret starts with "bunker://" (nostr connect), use it directly; otherwise, encrypt it
@@ -386,11 +384,11 @@ impl NostrRegistry {
// Run async tasks in background
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = async_keys.into_nostr_signer();
// Construct relay list event
let relay_list = default_relay_list();
let event = EventBuilder::relay_list(relay_list).sign(&signer).await?;
let event = EventBuilder::relay_list(relay_list)
.sign_async(&async_keys)
.await?;
// Publish relay list
client
@@ -403,7 +401,9 @@ impl NostrRegistry {
let name = petname::petname(2, "-").unwrap_or("Cooper".to_string());
let avatar = Url::parse(&format!("https://avatar.vercel.sh/{name}")).unwrap();
let metadata = Metadata::new().display_name(&name).picture(avatar);
let event = EventBuilder::metadata(&metadata).sign(&signer).await?;
let event = EventBuilder::metadata(&metadata)
.sign_async(&async_keys)
.await?;
// Publish metadata event
client
@@ -414,7 +414,9 @@ impl NostrRegistry {
// Construct the default contact list
let contacts = vec![Contact::new(PublicKey::parse(COOP_PUBKEY).unwrap())];
let event = EventBuilder::contact_list(contacts).sign(&signer).await?;
let event = EventBuilder::contact_list(contacts)
.sign_async(&async_keys)
.await?;
// Publish contact list event
client
@@ -425,7 +427,9 @@ impl NostrRegistry {
// Construct the default messaging relay list
let relays = default_messaging_relays();
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
let event = EventBuilder::nip17_relay_list(relays)
.sign_async(&async_keys)
.await?;
// Publish messaging relay list event
client.send_event(&event).to_nip65().await?;
@@ -440,56 +444,7 @@ impl NostrRegistry {
match task.await {
Ok(_) => {
this.update(cx, |this, cx| {
this.set_signer(keys, cx);
})?;
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string()));
})?;
}
};
Ok(())
}));
}
/// Set the signer for the nostr client and verify the public key
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
where
T: NostrSigner + 'static,
{
let client = self.client();
let signer = self.signer();
// Create a task to update the signer and verify the public key
let task: Task<Result<PublicKey, Error>> = cx.background_spawn(async move {
// Update signer and unsubscribe
signer.switch(new).await;
client.unsubscribe_all().await?;
// Verify and get public key
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
log::info!("Signer's public key: {}", public_key);
Ok(public_key)
});
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(public_key) => {
this.update(cx, |this, cx| {
// Add public key to npubs if not already present
this.npubs.update(cx, |this, cx| {
if !this.contains(&public_key) {
this.push(public_key);
cx.notify();
}
});
// Emit signer changed event
cx.emit(StateEvent::SignerSet);
this.switch_account(keys.public_key(), cx);
})?;
}
Err(e) => {
@@ -513,7 +468,7 @@ impl NostrRegistry {
match write_secret.await {
Ok(_) => {
this.update(cx, |this, cx| {
this.set_signer(keys, cx);
this.switch_account(keys.public_key(), cx);
})?;
}
Err(e) => {
@@ -552,7 +507,7 @@ impl NostrRegistry {
match write_secret.await {
Ok(_) => {
this.update(cx, |this, cx| {
this.set_signer(nip46, cx);
this.switch_account(public_key, cx);
})?;
}
Err(e) => {
@@ -670,14 +625,19 @@ impl NostrRegistry {
pub fn wot_search(&self, query: &str, cx: &App) -> Task<Result<Vec<PublicKey>, Error>> {
let client = self.client();
let query = query.to_string();
let signer = self.signer();
cx.background_spawn(async move {
let signer = signer.get().await;
// Construct a vertex request event
let builder = EventBuilder::new(Kind::Custom(5315), "").tags(vec![
Tag::custom(TagKind::custom("param"), vec!["search", &query]),
Tag::custom(TagKind::custom("param"), vec!["limit", "10"]),
]);
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::new(Kind::Custom(5315), "")
.tags(vec![
Tag::custom("param", vec!["search", &query]),
Tag::custom("param", vec!["limit", "10"]),
])
.sign_async(&signer)
.await?;
// Send the event to vertex relays
let output = client.send_event(&event).to(WOT_RELAYS).await?;

View File

@@ -7,38 +7,42 @@ use smol::lock::RwLock;
#[derive(Debug)]
pub struct CoopSigner {
/// User's signer
signer: RwLock<Arc<dyn NostrSigner>>,
signer: Arc<RwLock<Arc<dyn AsyncNostrSigner>>>,
/// User's signer public key
signer_pkey: RwLock<Option<PublicKey>>,
signer_pkey: Arc<RwLock<Option<PublicKey>>>,
/// Specific signer for encryption purposes
encryption_signer: RwLock<Option<Arc<dyn NostrSigner>>>,
encryption_signer: Arc<RwLock<Option<Arc<dyn AsyncNostrSigner>>>>,
}
impl CoopSigner {
pub fn new<T>(signer: T) -> Self
where
T: IntoNostrSigner,
T: AsyncNostrSigner,
{
Self {
signer: RwLock::new(signer.into_nostr_signer()),
signer_pkey: RwLock::new(None),
encryption_signer: RwLock::new(None),
signer: Arc::new(RwLock::new(Arc::new(signer))),
signer_pkey: Arc::new(RwLock::new(None)),
encryption_signer: Arc::new(RwLock::new(None)),
}
}
/// Get the current signer.
pub async fn get(&self) -> Arc<dyn NostrSigner> {
pub async fn get(&self) -> Arc<dyn AsyncNostrSigner> {
self.signer.read().await.clone()
}
/// Get the encryption signer.
pub async fn get_encryption_signer(&self) -> Option<Arc<dyn NostrSigner>> {
pub async fn get_encryption_signer(&self) -> Option<Arc<dyn AsyncNostrSigner>> {
self.encryption_signer.read().await.clone()
}
/// Check if the encryption signer is available.
pub async fn has_encryption_signer(&self) -> bool {
self.encryption_signer.read().await.is_some()
}
/// Get public key
///
/// Ensure to call this method after the signer has been initialized.
@@ -50,19 +54,17 @@ impl CoopSigner {
/// Switch the current signer to a new signer.
pub async fn switch<T>(&self, new: T)
where
T: IntoNostrSigner,
T: AsyncNostrSigner,
{
let new_signer = new.into_nostr_signer();
let public_key = new_signer.get_public_key().await.ok();
let mut signer = self.signer.write().await;
let mut signer_pkey = self.signer_pkey.write().await;
let mut encryption_signer = self.encryption_signer.write().await;
// Switch to the new signer
*signer = new_signer;
// Update the public key
*signer_pkey = public_key;
*signer_pkey = new.get_public_key().await.ok();
// Switch to the new signer
*signer = Arc::new(new);
// Reset the encryption signer
*encryption_signer = None;
@@ -71,35 +73,33 @@ impl CoopSigner {
/// Set the encryption signer.
pub async fn set_encryption_signer<T>(&self, new: T)
where
T: IntoNostrSigner,
T: AsyncNostrSigner,
{
let mut encryption_signer = self.encryption_signer.write().await;
*encryption_signer = Some(new.into_nostr_signer());
*encryption_signer = Some(Arc::new(new));
}
}
impl NostrSigner for CoopSigner {
#[allow(mismatched_lifetime_syntaxes)]
fn backend(&self) -> SignerBackend {
SignerBackend::Custom(Cow::Borrowed("custom"))
}
fn get_public_key<'a>(&'a self) -> BoxedFuture<'a, Result<PublicKey, SignerError>> {
impl AsyncGetPublicKey for CoopSigner {
fn get_public_key(&self) -> BoxedFuture<'_, Result<PublicKey, SignerError>> {
Box::pin(async move { self.get().await.get_public_key().await })
}
}
fn sign_event<'a>(
&'a self,
unsigned: UnsignedEvent,
) -> BoxedFuture<'a, Result<Event, SignerError>> {
impl AsyncSignEvent for CoopSigner {
fn sign_event(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, SignerError>> {
Box::pin(async move { self.get().await.sign_event(unsigned).await })
}
}
impl AsyncNip04 for CoopSigner {
type Error = SignerError;
fn nip04_encrypt<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
) -> BoxedFuture<'a, Result<String, Self::Error>> {
Box::pin(async move { self.get().await.nip04_encrypt(public_key, content).await })
}
@@ -107,7 +107,7 @@ impl NostrSigner for CoopSigner {
&'a self,
public_key: &'a PublicKey,
encrypted_content: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
) -> BoxedFuture<'a, Result<String, Self::Error>> {
Box::pin(async move {
self.get()
.await
@@ -115,12 +115,16 @@ impl NostrSigner for CoopSigner {
.await
})
}
}
impl AsyncNip44 for CoopSigner {
type Error = SignerError;
fn nip44_encrypt<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
) -> BoxedFuture<'a, Result<String, Self::Error>> {
Box::pin(async move { self.get().await.nip44_encrypt(public_key, content).await })
}
@@ -128,7 +132,13 @@ impl NostrSigner for CoopSigner {
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
) -> BoxedFuture<'a, Result<String, Self::Error>> {
Box::pin(async move { self.get().await.nip44_decrypt(public_key, payload).await })
}
}
impl AsyncNostrSigner for CoopSigner {
fn backend(&self) -> SignerBackend<'_> {
SignerBackend::Custom(Cow::Borrowed("custom"))
}
}

View File

@@ -91,26 +91,18 @@ impl AccountSelector {
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let task = nostr.read(cx).get_secret(public_key, cx);
// Mark the public key as being logged in
self.set_logging_in(public_key, cx);
self.tasks.push(cx.spawn_in(window, async move |this, cx| {
match task.await {
Ok(signer) => {
nostr.update(cx, |this, cx| {
this.set_signer(signer, cx);
});
}
Err(e) => {
this.update(cx, |this, cx| {
this.set_error(e.to_string(), cx);
})?;
}
};
Ok(())
}));
match nostr.read(cx).switch_account(public_key, cx) {
Ok(()) => {
//
}
Err(e) => {
self.set_error(e.to_string(), cx);
}
};
}
fn remove(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {

View File

@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error};
use anyhow::Error;
use common::TimestampExt;
use gpui::prelude::FluentBuilder;
use gpui::{
@@ -76,10 +76,10 @@ impl Screening {
fn check_contact(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let public_key = self.public_key;
let task: Task<Result<bool, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let signer_pubkey = signer.get_public_key().await?;
// Check if user is in contact list
@@ -103,10 +103,10 @@ impl Screening {
fn check_wot(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let public_key = self.public_key;
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let signer_pubkey = signer.get_public_key().await?;
// Check mutual contacts
@@ -222,12 +222,21 @@ impl Screening {
fn report(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let public_key = self.public_key;
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let tag = Tag::public_key_report(public_key, Report::Impersonation);
let builder = EventBuilder::report(vec![tag], "");
let event = client.sign_event_builder(builder).await?;
let signer = signer.get().await;
let tag = Nip56Tag::PublicKey {
public_key,
report: Report::Impersonation,
}
.to_tag();
let event = EventBuilder::report(vec![tag], "")
.sign_async(&signer)
.await?;
// Send the report to the public relays
client.send_event(&event).to(BOOTSTRAP_RELAYS).await?;

View File

@@ -1,7 +1,7 @@
use std::collections::HashSet;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error};
use anyhow::Error;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
@@ -81,9 +81,9 @@ impl ContactListPanel {
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
let contact_list = client.database().contacts_public_keys(public_key).await?;
@@ -156,6 +156,7 @@ impl ContactListPanel {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
// Get contacts
let contacts: Vec<Contact> = self
@@ -168,9 +169,12 @@ impl ContactListPanel {
self.set_updating(true, cx);
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = signer.get().await;
// Construct contact list event builder
let builder = EventBuilder::contact_list(contacts);
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::contact_list(contacts)
.sign_async(&signer)
.await?;
// Set contact list
client.send_event(&event).to_nip65().await?;

View File

@@ -1,7 +1,7 @@
use std::collections::HashSet;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow};
use anyhow::{Error, anyhow};
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
@@ -82,9 +82,9 @@ impl MessagingRelayPanel {
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let task: Task<Result<Vec<RelayUrl>, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
@@ -93,7 +93,7 @@ impl MessagingRelayPanel {
.limit(1);
if let Some(event) = client.database().query(filter).await?.first_owned() {
Ok(nip17::extract_owned_relay_list(event).collect())
Ok(nip17::extract_relay_list(&event).collect())
} else {
Err(anyhow!("Not found."))
}
@@ -170,21 +170,26 @@ impl MessagingRelayPanel {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
// Construct event tags
let tags: Vec<Tag> = self
.relays
.iter()
.map(|relay| Tag::relay(relay.clone()))
.map(|relay| Tag::custom("relay", vec![relay.to_string()]))
.collect();
// Set updating state
self.set_updating(true, cx);
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = signer.get().await;
// Construct nip17 event builder
let builder = EventBuilder::new(Kind::InboxRelays, "").tags(tags);
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::new(Kind::InboxRelays, "")
.tags(tags)
.sign_async(&signer)
.await?;
// Set messaging relays
client.send_event(&event).to_nip65().await?;

View File

@@ -207,12 +207,16 @@ impl ProfilePanel {
fn publish(&self, metadata: &Metadata, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let metadata = metadata.clone();
cx.background_spawn(async move {
let signer = signer.get().await;
// Build and sign the metadata event
let builder = EventBuilder::metadata(&metadata);
let event = client.sign_event_builder(builder).await?;
let event = EventBuilder::metadata(&metadata)
.sign_async(&signer)
.await?;
// Send event to user's relays
client.send_event(&event).await?;

View File

@@ -1,7 +1,7 @@
use std::collections::HashSet;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow};
use anyhow::{Error, anyhow};
use gpui::prelude::FluentBuilder;
use gpui::{
Action, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable,
@@ -99,10 +99,10 @@ impl RelayListPanel {
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let task: Task<Result<Vec<(RelayUrl, Option<RelayMetadata>)>, Error>> = cx
.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
@@ -111,7 +111,7 @@ impl RelayListPanel {
.limit(1);
if let Some(event) = client.database().query(filter).await?.first_owned() {
Ok(nip65::extract_owned_relay_list(event).collect())
Ok(nip65::extract_relay_list(&event).collect())
} else {
Err(anyhow!("Not found."))
}
@@ -206,6 +206,7 @@ impl RelayListPanel {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
// Get all relays
let relays = self.relays.clone();
@@ -214,8 +215,8 @@ impl RelayListPanel {
self.set_updating(true, cx);
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let builder = EventBuilder::relay_list(relays);
let event = client.sign_event_builder(builder).await?;
let signer = signer.get().await;
let event = EventBuilder::relay_list(relays).sign_async(&signer).await?;
// Set relay list for current user
client.send_event(&event).await?;

View File

@@ -2,7 +2,7 @@ use std::collections::HashSet;
use std::ops::Range;
use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error};
use anyhow::Error;
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
use common::{DebouncedDelay, TimestampExt, coop_cache};
use entry::RoomEntry;
@@ -158,9 +158,9 @@ impl Sidebar {
fn get_contact_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?;
let contacts = client.database().contacts_public_keys(public_key).await?;