chore: fix some gossip and nip4e bugs (#23)

Reviewed-on: #23
Co-authored-by: Ren Amamiya <reya@lume.nu>
Co-committed-by: Ren Amamiya <reya@lume.nu>
This commit was merged in pull request #23.
This commit is contained in:
2026-03-18 08:21:39 +00:00
committed by reya
parent 40e7ca368b
commit 94cbb4aa0e
9 changed files with 207 additions and 228 deletions

112
Cargo.lock generated
View File

@@ -1949,7 +1949,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -2013,18 +2013,6 @@ dependencies = [
"zune-inflate", "zune-inflate",
] ]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "1.9.0" version = "1.9.0"
@@ -3778,17 +3766,6 @@ dependencies = [
"redox_syscall 0.7.3", "redox_syscall 0.7.3",
] ]
[[package]]
name = "libsqlite3-sys"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "linebender_resource_handle" name = "linebender_resource_handle"
version = "0.1.1" version = "0.1.1"
@@ -4274,7 +4251,7 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]] [[package]]
name = "nostr" name = "nostr"
version = "0.44.1" version = "0.44.1"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"aes", "aes",
"base64", "base64",
@@ -4298,7 +4275,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-blossom" name = "nostr-blossom"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"base64", "base64",
"nostr", "nostr",
@@ -4309,7 +4286,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-connect" name = "nostr-connect"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"futures-core", "futures-core",
@@ -4322,7 +4299,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-database" name = "nostr-database"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"btreecap", "btreecap",
"flatbuffers", "flatbuffers",
@@ -4332,27 +4309,27 @@ dependencies = [
[[package]] [[package]]
name = "nostr-gossip" name = "nostr-gossip"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"nostr", "nostr",
] ]
[[package]] [[package]]
name = "nostr-gossip-sqlite" name = "nostr-gossip-memory"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "indexmap",
"lru",
"nostr", "nostr",
"nostr-gossip", "nostr-gossip",
"rusqlite",
"tokio", "tokio",
] ]
[[package]] [[package]]
name = "nostr-lmdb" name = "nostr-lmdb"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"flume 0.12.0", "flume 0.12.0",
@@ -4366,7 +4343,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-memory" name = "nostr-memory"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"btreecap", "btreecap",
"nostr", "nostr",
@@ -4377,7 +4354,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-sdk" name = "nostr-sdk"
version = "0.44.1" version = "0.44.1"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"async-wsocket", "async-wsocket",
@@ -4409,7 +4386,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -5271,7 +5248,7 @@ dependencies = [
"once_cell", "once_cell",
"socket2", "socket2",
"tracing", "tracing",
"windows-sys 0.60.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -5696,30 +5673,6 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "rsqlite-vfs"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d"
dependencies = [
"hashbrown 0.16.1",
"thiserror 2.0.18",
]
[[package]]
name = "rusqlite"
version = "0.38.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3"
dependencies = [
"bitflags 2.11.0",
"fallible-iterator",
"fallible-streaming-iterator",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]] [[package]]
name = "rust-embed" name = "rust-embed"
version = "8.11.0" version = "8.11.0"
@@ -5815,7 +5768,7 @@ dependencies = [
"errno", "errno",
"libc", "libc",
"linux-raw-sys 0.12.1", "linux-raw-sys 0.12.1",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -6458,18 +6411,6 @@ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
] ]
[[package]]
name = "sqlite-wasm-rs"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4206ed3a67690b9c29b77d728f6acc3ce78f16bf846d83c94f76400320181b"
dependencies = [
"cc",
"js-sys",
"rsqlite-vfs",
"wasm-bindgen",
]
[[package]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
version = "1.2.1" version = "1.2.1"
@@ -6524,7 +6465,7 @@ dependencies = [
"nostr", "nostr",
"nostr-blossom", "nostr-blossom",
"nostr-connect", "nostr-connect",
"nostr-gossip-sqlite", "nostr-gossip-memory",
"nostr-lmdb", "nostr-lmdb",
"nostr-memory", "nostr-memory",
"nostr-sdk", "nostr-sdk",
@@ -6826,7 +6767,7 @@ dependencies = [
"getrandom 0.4.2", "getrandom 0.4.2",
"once_cell", "once_cell",
"rustix 1.1.4", "rustix 1.1.4",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -7662,12 +7603,6 @@ dependencies = [
"sval_serde", "sval_serde",
] ]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.5" version = "0.9.5"
@@ -8231,7 +8166,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.48.0",
] ]
[[package]] [[package]]
@@ -8554,15 +8489,6 @@ dependencies = [
"windows-targets 0.52.6", "windows-targets 0.52.6",
] ]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.61.2" version = "0.61.2"

View File

@@ -23,7 +23,7 @@ nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
nostr-memory = { git = "https://github.com/rust-nostr/nostr" } nostr-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-connect = { git = "https://github.com/rust-nostr/nostr" } nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" } nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
nostr-gossip-sqlite = { 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-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 = [ "nip96", "nip59", "nip49", "nip44" ] }

View File

@@ -16,7 +16,7 @@ use gpui::{
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use smol::lock::RwLock; use smol::lock::RwLock;
use state::{DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP}; use state::{CoopSigner, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP};
mod message; mod message;
mod room; mod room;
@@ -154,7 +154,6 @@ impl ChatRegistry {
let rx = self.signal_rx.clone(); let rx = self.signal_rx.clone();
self.tasks.push(cx.background_spawn(async move { self.tasks.push(cx.background_spawn(async move {
let device_signer = signer.get_encryption_signer().await;
let mut notifications = client.notifications(); let mut notifications = client.notifications();
let mut processed_events = HashSet::new(); let mut processed_events = HashSet::new();
@@ -183,7 +182,7 @@ impl ChatRegistry {
} }
// Extract the rumor from the gift wrap event // Extract the rumor from the gift wrap event
match extract_rumor(&client, &device_signer, event.as_ref()).await { match extract_rumor(&client, &signer, event.as_ref()).await {
Ok(rumor) => { Ok(rumor) => {
if rumor.tags.is_empty() { if rumor.tags.is_empty() {
let error: SharedString = "No room for message".into(); let error: SharedString = "No room for message".into();
@@ -682,7 +681,7 @@ impl ChatRegistry {
/// Unwraps a gift-wrapped event and processes its contents. /// Unwraps a gift-wrapped event and processes its contents.
async fn extract_rumor( async fn extract_rumor(
client: &Client, client: &Client,
device_signer: &Option<Arc<dyn NostrSigner>>, signer: &Arc<CoopSigner>,
gift_wrap: &Event, gift_wrap: &Event,
) -> Result<UnsignedEvent, Error> { ) -> Result<UnsignedEvent, Error> {
// Try to get cached rumor first // Try to get cached rumor first
@@ -691,7 +690,7 @@ async fn extract_rumor(
} }
// Try to unwrap with the available signer // Try to unwrap with the available signer
let unwrapped = try_unwrap(client, device_signer, gift_wrap).await?; let unwrapped = try_unwrap(signer, gift_wrap).await?;
let mut rumor = unwrapped.rumor; let mut rumor = unwrapped.rumor;
// Generate event id for the rumor if it doesn't have one // Generate event id for the rumor if it doesn't have one
@@ -706,30 +705,27 @@ async fn extract_rumor(
} }
/// Helper method to try unwrapping with different signers /// Helper method to try unwrapping with different signers
async fn try_unwrap( async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
client: &Client,
device_signer: &Option<Arc<dyn NostrSigner>>,
gift_wrap: &Event,
) -> Result<UnwrappedGift, Error> {
// Try with the device signer first // Try with the device signer first
if let Some(signer) = device_signer if let Some(signer) = signer.get_encryption_signer().await {
&& let Ok(unwrapped) = try_unwrap_with(gift_wrap, signer).await log::info!("trying with encryption key");
{ if let Ok(unwrapped) = try_unwrap_with(gift_wrap, &signer).await {
return Ok(unwrapped); return Ok(unwrapped);
}; }
}
// Try with the user's signer // Fallback to the user's signer
let user_signer = client.signer().context("Signer not found")?; let user_signer = signer.get().await;
let unwrapped = try_unwrap_with(gift_wrap, user_signer).await?; let unwrapped = try_unwrap_with(gift_wrap, &user_signer).await?;
Ok(unwrapped) Ok(unwrapped)
} }
/// Attempts to unwrap a gift wrap event with a given signer. /// Attempts to unwrap a gift wrap event with a given signer.
async fn try_unwrap_with( async fn try_unwrap_with<T>(gift_wrap: &Event, signer: &T) -> Result<UnwrappedGift, Error>
gift_wrap: &Event, where
signer: &Arc<dyn NostrSigner>, T: NostrSigner + 'static,
) -> Result<UnwrappedGift, Error> { {
// Get the sealed event // Get the sealed event
let seal = signer let seal = signer
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content) .nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)

View File

@@ -2,7 +2,7 @@ use std::cmp::Ordering;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::time::Duration; use std::time::Duration;
use anyhow::Error; use anyhow::{Error, anyhow};
use common::EventUtils; use common::EventUtils;
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task}; use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
use itertools::Itertools; use itertools::Itertools;
@@ -354,17 +354,7 @@ impl Room {
pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> { pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let members = self.members();
let signer = nostr.read(cx).signer();
let sender = signer.public_key();
// Get all members, excluding the sender
let members: Vec<PublicKey> = self
.members
.iter()
.filter(|public_key| Some(**public_key) != sender)
.copied()
.collect();
cx.background_spawn(async move { cx.background_spawn(async move {
let opts = SubscribeAutoCloseOptions::default() let opts = SubscribeAutoCloseOptions::default()
@@ -515,45 +505,46 @@ impl Room {
// Handle encryption signer requirements // Handle encryption signer requirements
if signer_kind.encryption() { if signer_kind.encryption() {
// Receiver didn't set up a decoupled encryption key
if announcement.is_none() { if announcement.is_none() {
reports.push(SendReport::new(public_key).error(NO_DEKEY)); reports.push(SendReport::new(public_key).error(NO_DEKEY));
continue; continue;
} }
// Sender didn't set up a decoupled encryption key
if encryption_signer.is_none() { if encryption_signer.is_none() {
reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY)); reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY));
continue; continue;
} }
} }
// Determine receiver and signer // Determine the signer to use
let (receiver, signer) = match signer_kind { let signer = match signer_kind {
SignerKind::Auto => { SignerKind::Auto => {
if let Some(announcement) = announcement { if announcement.is_some()
if let Some(enc_signer) = encryption_signer.as_ref() { && let Some(encryption_signer) = encryption_signer.clone()
(announcement.public_key(), enc_signer.clone()) {
} else { // Safe to unwrap due to earlier checks
(member.public_key(), user_signer.clone()) encryption_signer
}
} else { } else {
(member.public_key(), user_signer.clone()) user_signer.clone()
} }
} }
SignerKind::Encryption => { SignerKind::Encryption => {
// Safe to unwrap due to earlier checks // Safe to unwrap due to earlier checks
( encryption_signer.as_ref().unwrap().clone()
announcement.unwrap().public_key(),
encryption_signer.as_ref().unwrap().clone(),
)
} }
SignerKind::User => (member.public_key(), user_signer.clone()), SignerKind::User => user_signer.clone(),
}; };
match send_gift_wrap(&client, &signer, &receiver, &rumor, public_key).await { // Send the gift wrap event and collect the report
Ok((report, _)) => { match send_gift_wrap(&client, &signer, &member, &rumor, signer_kind).await {
Ok(report) => {
reports.push(report); reports.push(report);
sents += 1; sents += 1;
} }
Err(report) => { Err(error) => {
let report = SendReport::new(public_key).error(error.to_string());
reports.push(report); reports.push(report);
} }
} }
@@ -562,11 +553,32 @@ impl Room {
// Send backup to current user if needed // Send backup to current user if needed
if backup && sents >= 1 { if backup && sents >= 1 {
let public_key = sender.public_key(); let public_key = sender.public_key();
let signer = encryption_signer.as_ref().unwrap_or(&user_signer);
match send_gift_wrap(&client, signer, &public_key, &rumor, public_key).await { // Determine the signer to use
Ok((report, _)) => reports.push(report), let signer = match signer_kind {
Err(report) => reports.push(report), 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(),
};
match send_gift_wrap(&client, &signer, &sender, &rumor, signer_kind).await {
Ok(report) => reports.push(report),
Err(error) => {
let report = SendReport::new(public_key).error(error.to_string());
reports.push(report);
}
} }
} }
@@ -579,30 +591,50 @@ impl Room {
async fn send_gift_wrap<T>( async fn send_gift_wrap<T>(
client: &Client, client: &Client,
signer: &T, signer: &T,
receiver: &PublicKey, receiver: &Person,
rumor: &UnsignedEvent, rumor: &UnsignedEvent,
public_key: PublicKey, config: &SignerKind,
) -> Result<(SendReport, bool), SendReport> ) -> Result<SendReport, Error>
where where
T: NostrSigner + 'static, T: NostrSigner + 'static,
{ {
match EventBuilder::gift_wrap(signer, receiver, rumor.clone(), []).await { let mut extra_tags = vec![];
Ok(event) => {
match client // Determine the receiver public key based on the config
.send_event(&event) let receiver = match config {
.to_nip17() SignerKind::Auto => {
.ack_policy(AckPolicy::none()) if let Some(announcement) = receiver.announcement().as_ref() {
.await extra_tags.push(Tag::public_key(receiver.public_key()));
{ announcement.public_key()
Ok(output) => Ok(( } else {
SendReport::new(public_key) receiver.public_key()
.gift_wrap_id(event.id)
.output(output),
true,
)),
Err(e) => Err(SendReport::new(public_key).error(e.to_string())),
} }
} }
Err(e) => Err(SendReport::new(public_key).error(e.to_string())), 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(),
};
// Construct the gift wrap event
let event = EventBuilder::gift_wrap(signer, &receiver, rumor.clone(), extra_tags).await?;
// Send the gift wrap event and collect the report
let report = client
.send_event(&event)
.to_nip17()
.ack_policy(AckPolicy::none())
.await
.map(|output| {
SendReport::new(receiver)
.gift_wrap_id(event.id)
.output(output)
})?;
Ok(report)
} }

View File

@@ -379,9 +379,13 @@ impl ChatPanel {
/// Send message in the background and wait for the response /// Send message in the background and wait for the response
fn send_and_wait(&mut self, rumor: UnsignedEvent, window: &mut Window, cx: &mut Context<Self>) { fn send_and_wait(&mut self, rumor: UnsignedEvent, window: &mut Window, cx: &mut Context<Self>) {
let sent_ids = self.sent_ids.clone(); let sent_ids = self.sent_ids.clone();
// This can't fail, because we already ensured that the ID is set // This can't fail, because we already ensured that the ID is set
let id = rumor.id.unwrap(); let id = rumor.id.unwrap();
// Add empty reports
self.insert_reports(id, vec![], cx);
// Upgrade room reference // Upgrade room reference
let Some(room) = self.room.upgrade() else { let Some(room) = self.room.upgrade() else {
return; return;
@@ -430,7 +434,7 @@ impl ChatPanel {
/// Insert reports /// Insert reports
fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) { fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) {
self.reports_by_id.update(cx, |this, cx| { self.reports_by_id.update(cx, |this, cx| {
this.insert(id, reports); this.entry(id).or_default().extend(reports);
cx.notify(); cx.notify();
}); });
} }
@@ -465,14 +469,6 @@ impl ChatPanel {
} }
} }
/// Check if a message is pending
fn sent_pending(&self, id: &EventId, cx: &App) -> bool {
self.reports_by_id
.read(cx)
.get(id)
.is_some_and(|reports| reports.iter().all(|r| r.pending()))
}
/// Check if a message has any reports /// Check if a message has any reports
fn has_reports(&self, id: &EventId, cx: &App) -> bool { fn has_reports(&self, id: &EventId, cx: &App) -> bool {
self.reports_by_id.read(cx).get(id).is_some() self.reports_by_id.read(cx).get(id).is_some()
@@ -802,8 +798,6 @@ impl ChatPanel {
let replies = message.replies_to.as_slice(); let replies = message.replies_to.as_slice();
let has_replies = !replies.is_empty(); let has_replies = !replies.is_empty();
let sent_pending = self.sent_pending(&id, cx);
let has_reports = self.has_reports(&id, cx); let has_reports = self.has_reports(&id, cx);
// Hide avatar setting // Hide avatar setting
@@ -851,9 +845,6 @@ impl ChatPanel {
.child(author.name()), .child(author.name()),
) )
.child(message.created_at.to_human_time()) .child(message.created_at.to_human_time())
.when(sent_pending, |this| {
this.child(SharedString::from("• Sending..."))
})
.when(has_reports, |this| { .when(has_reports, |this| {
this.child(deferred(self.render_sent_reports(&id, cx))) this.child(deferred(self.render_sent_reports(&id, cx)))
}), }),
@@ -937,20 +928,26 @@ impl ChatPanel {
fn render_sent_reports(&self, id: &EventId, cx: &App) -> impl IntoElement { fn render_sent_reports(&self, id: &EventId, cx: &App) -> impl IntoElement {
let reports = self.sent_reports(id, cx); let reports = self.sent_reports(id, cx);
let pending = reports
.as_ref()
.is_some_and(|reports| reports.is_empty() || reports.iter().any(|r| r.pending()));
let success = reports let success = reports
.as_ref() .as_ref()
.is_some_and(|reports| reports.iter().any(|r| r.success())); .is_some_and(|reports| !reports.is_empty() && reports.iter().any(|r| r.success()));
let failed = reports let failed = reports
.as_ref() .as_ref()
.is_some_and(|reports| reports.iter().all(|r| r.failed())); .is_some_and(|reports| !reports.is_empty() && reports.iter().all(|r| r.failed()));
let label = if success { let label = if success {
SharedString::from("• Sent") SharedString::from("• Sent")
} else if failed { } else if failed {
SharedString::from("Failed") SharedString::from("Error")
} else { } else if pending {
SharedString::from("• Sending...") SharedString::from("• Sending...")
} else {
SharedString::from("• Unknown")
}; };
div() div()
@@ -958,22 +955,24 @@ impl ChatPanel {
.child(label) .child(label)
.when(failed, |this| this.text_color(cx.theme().text_danger)) .when(failed, |this| this.text_color(cx.theme().text_danger))
.when_some(reports, |this, reports| { .when_some(reports, |this, reports| {
this.on_click(move |_e, window, cx| { this.when(!pending, |this| {
let reports = reports.clone(); this.on_click(move |_e, window, cx| {
let reports = reports.clone();
window.open_modal(cx, move |this, _window, cx| { window.open_modal(cx, move |this, _window, cx| {
this.title(SharedString::from("Sent Reports")) this.title(SharedString::from("Sent Reports"))
.show_close(true) .show_close(true)
.child(v_flex().gap_4().children({ .child(v_flex().gap_4().children({
let mut items = Vec::with_capacity(reports.len()); let mut items = Vec::with_capacity(reports.len());
for report in reports.iter() { for report in reports.iter() {
items.push(Self::render_report(report, cx)) items.push(Self::render_report(report, cx))
} }
items items
})) }))
}); });
})
}) })
}) })
} }

View File

@@ -16,7 +16,7 @@ use theme::ActiveTheme;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariants}; use ui::button::{Button, ButtonVariants};
use ui::notification::Notification; use ui::notification::Notification;
use ui::{Disableable, IconName, Sizable, WindowExtension, h_flex, v_flex}; use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
const IDENTIFIER: &str = "coop:device"; const IDENTIFIER: &str = "coop:device";
const MSG: &str = "You've requested an encryption key from another device. \ const MSG: &str = "You've requested an encryption key from another device. \
@@ -85,6 +85,9 @@ pub struct DeviceRegistry {
/// Whether the registry is waiting for encryption key approval from other devices /// Whether the registry is waiting for encryption key approval from other devices
pub requesting: bool, pub requesting: bool,
/// Whether there is a pending request for encryption key approval
pub has_pending_request: bool,
/// Async tasks /// Async tasks
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
@@ -130,6 +133,7 @@ impl DeviceRegistry {
Self { Self {
subscribing: false, subscribing: false,
requesting: false, requesting: false,
has_pending_request: false,
tasks: vec![], tasks: vec![],
_subscription: Some(subscription), _subscription: Some(subscription),
} }
@@ -208,6 +212,12 @@ impl DeviceRegistry {
cx.notify(); cx.notify();
} }
/// Set whether there is a pending request for encryption key approval
fn set_has_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
self.has_pending_request = pending;
cx.notify();
}
/// Set the decoupled encryption key for the current user /// Set the decoupled encryption key for the current user
fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>) fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
where where
@@ -611,7 +621,6 @@ impl DeviceRegistry {
fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) { fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
// Get user's write relays // Get user's write relays
let event = event.clone(); let event = event.clone();
@@ -631,14 +640,14 @@ impl DeviceRegistry {
.context("Target is not a valid public key")?; .context("Target is not a valid public key")?;
// Encrypt the device keys with the user's signer // Encrypt the device keys with the user's signer
let payload = signer.nip44_encrypt(&target, &secret).await?; let payload = keys.nip44_encrypt(&target, &secret).await?;
// Construct the response event // Construct the response event
// //
// P tag: the current device's public key // P tag: the current device's public key
// p tag: the requester's public key // p tag: the requester's public key
let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![ let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![
Tag::custom(TagKind::custom("P"), vec![keys.public_key()]), Tag::custom(TagKind::custom("P"), vec![keys.public_key().to_hex()]),
Tag::public_key(target), Tag::public_key(target),
]); ]);
@@ -675,15 +684,15 @@ impl DeviceRegistry {
/// Handle encryption request /// Handle encryption request
fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) { fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) {
let notification = self.notification(event, cx); // Ignore if there is already a pending request
if self.has_pending_request {
return;
}
self.set_has_pending_request(true, cx);
cx.spawn_in(window, async move |_this, cx| { // Show notification
cx.update(|window, cx| { let notification = self.notification(event, cx);
window.push_notification(notification, cx); window.push_notification(notification, cx);
})
.ok();
})
.detach();
} }
/// Build a notification for the encryption request. /// Build a notification for the encryption request.
@@ -720,13 +729,14 @@ impl DeviceRegistry {
.text_sm() .text_sm()
.child( .child(
div() div()
.font_semibold()
.text_xs() .text_xs()
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
.child(SharedString::from("Requester:")), .child(SharedString::from("Requester:")),
) )
.child( .child(
div() div()
.h_7() .h_8()
.w_full() .w_full()
.px_2() .px_2()
.rounded(cx.theme().radius) .rounded(cx.theme().radius)
@@ -745,13 +755,14 @@ impl DeviceRegistry {
.text_sm() .text_sm()
.child( .child(
div() div()
.font_semibold()
.text_xs() .text_xs()
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
.child(SharedString::from("Client:")), .child(SharedString::from("Client:")),
) )
.child( .child(
div() div()
.h_7() .h_8()
.w_full() .w_full()
.px_2() .px_2()
.rounded(cx.theme().radius) .rounded(cx.theme().radius)

View File

@@ -11,7 +11,7 @@ nostr.workspace = true
nostr-sdk.workspace = true nostr-sdk.workspace = true
nostr-lmdb.workspace = true nostr-lmdb.workspace = true
nostr-memory.workspace = true nostr-memory.workspace = true
nostr-gossip-sqlite.workspace = true nostr-gossip-memory.workspace = true
nostr-connect.workspace = true nostr-connect.workspace = true
nostr-blossom.workspace = true nostr-blossom.workspace = true

View File

@@ -36,14 +36,16 @@ pub const NOSTR_CONNECT_RELAY: &str = "wss://relay.nip46.com";
/// Default vertex relays /// Default vertex relays
pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"]; pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"];
/// Default search relays
pub const INDEXER_RELAYS: [&str; 1] = ["wss://indexer.coracle.social"];
/// Default search relays /// Default search relays
pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.today"]; pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.today"];
/// Default bootstrap relays /// Default bootstrap relays
pub const BOOTSTRAP_RELAYS: [&str; 4] = [ pub const BOOTSTRAP_RELAYS: [&str; 3] = [
"wss://relay.damus.io", "wss://relay.damus.io",
"wss://relay.primal.net", "wss://relay.primal.net",
"wss://indexer.coracle.social",
"wss://user.kindpag.es", "wss://user.kindpag.es",
]; ];

View File

@@ -6,7 +6,7 @@ use anyhow::{Context as AnyhowContext, Error, anyhow};
use common::config_dir; use common::config_dir;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window}; use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
use nostr_connect::prelude::*; use nostr_connect::prelude::*;
use nostr_gossip_sqlite::prelude::*; use nostr_gossip_memory::prelude::*;
use nostr_lmdb::prelude::*; use nostr_lmdb::prelude::*;
use nostr_memory::prelude::*; use nostr_memory::prelude::*;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
@@ -114,17 +114,16 @@ impl NostrRegistry {
// Construct the nostr npubs entity // Construct the nostr npubs entity
let npubs = cx.new(|_| vec![]); let npubs = cx.new(|_| vec![]);
// Construct the nostr gossip instance
let gossip = cx.foreground_executor().block_on(async move {
NostrGossipSqlite::open(config_dir().join("gossip"))
.await
.expect("Failed to initialize gossip instance")
});
// Construct the nostr client builder // Construct the nostr client builder
let mut builder = ClientBuilder::default() let mut builder = ClientBuilder::default()
.signer(signer.clone()) .signer(signer.clone())
.gossip(gossip) .gossip(NostrGossipMemory::unbounded())
.gossip_config(
GossipConfig::default()
.no_background_refresh()
.sync_idle_timeout(Duration::from_secs(TIMEOUT))
.sync_initial_timeout(Duration::from_millis(600)),
)
.automatic_authentication(false) .automatic_authentication(false)
.verify_subscriptions(false) .verify_subscriptions(false)
.connect_timeout(Duration::from_secs(10)) .connect_timeout(Duration::from_secs(10))
@@ -189,7 +188,18 @@ impl NostrRegistry {
let task: Task<Result<(), Error>> = cx.background_spawn(async move { let task: Task<Result<(), Error>> = cx.background_spawn(async move {
// Add search relay to the relay pool // Add search relay to the relay pool
for url in SEARCH_RELAYS.into_iter() { for url in SEARCH_RELAYS.into_iter() {
client.add_relay(url).await?; client
.add_relay(url)
.capabilities(RelayCapabilities::READ)
.await?;
}
// Add indexer relay to the relay pool
for url in INDEXER_RELAYS.into_iter() {
client
.add_relay(url)
.capabilities(RelayCapabilities::DISCOVERY)
.await?;
} }
// Add bootstrap relay to the relay pool // Add bootstrap relay to the relay pool
@@ -198,7 +208,10 @@ impl NostrRegistry {
} }
// Connect to all added relays // Connect to all added relays
client.connect().await; client
.connect()
.and_wait(Duration::from_secs(TIMEOUT))
.await;
Ok(()) Ok(())
}); });