feat: implement a basic backend (#1)
Reviewed-on: https://git.reya.su/reya/signed/pulls/1
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "signed_nostr"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
signed_core = { path = "../signed_core" }
|
||||
|
||||
nostr.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
nostr-connect.workspace = true
|
||||
nostr-gossip-memory.workspace = true
|
||||
|
||||
anyhow.workspace = true
|
||||
webbrowser.workspace = true
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
nostr-memory.workspace = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
nostr-lmdb.workspace = true
|
||||
@@ -0,0 +1,126 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use nostr_gossip_memory::prelude::*;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use nostr_lmdb::prelude::*;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use nostr_memory::prelude::*;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use crate::signer::UniversalSigner;
|
||||
|
||||
/// Owns the nostr client: relay pool, LMDB database and signer.
|
||||
///
|
||||
/// The SDK manages its own internal tokio runtime; every method here is a
|
||||
/// plain async fn that can be driven by GPUI's executors.
|
||||
#[derive(Clone)]
|
||||
pub struct NostrBackend {
|
||||
client: Client,
|
||||
signer: UniversalSigner,
|
||||
}
|
||||
|
||||
impl NostrBackend {
|
||||
/// Open (or create) the LMDB database at `db_path` and build the client.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub async fn new(db_path: impl AsRef<std::path::Path>) -> Result<Self> {
|
||||
let signer = UniversalSigner::new(Keys::generate());
|
||||
let database = NostrLmdb::open(db_path)
|
||||
.await
|
||||
.context("failed to open nostr database")?;
|
||||
Ok(Self::with_database(signer, database))
|
||||
}
|
||||
|
||||
/// In-memory database on wasm (no LMDB available).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn new() -> Result<Self> {
|
||||
let signer = UniversalSigner::new(Keys::generate());
|
||||
Ok(Self::with_database(signer, MemoryDatabase::unbounded()))
|
||||
}
|
||||
|
||||
fn with_database<D>(signer: UniversalSigner, database: D) -> Self
|
||||
where
|
||||
D: IntoNostrDatabase,
|
||||
{
|
||||
let authenticator = SignerAuthenticator::new(signer.clone());
|
||||
|
||||
let client = ClientBuilder::default()
|
||||
.database(database)
|
||||
.authenticator(authenticator)
|
||||
.gossip(NostrGossipMemory::unbounded())
|
||||
.gossip_config(GossipConfig::default().no_background_refresh())
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.verify_subscriptions(true)
|
||||
.ban_relay_on_mismatch(true)
|
||||
.sleep_when_idle(SleepWhenIdle::Enabled {
|
||||
timeout: Duration::from_secs(600),
|
||||
})
|
||||
.build();
|
||||
|
||||
Self { client, signer }
|
||||
}
|
||||
|
||||
pub fn client(&self) -> Client {
|
||||
self.client.clone()
|
||||
}
|
||||
|
||||
pub fn signer(&self) -> UniversalSigner {
|
||||
self.signer.clone()
|
||||
}
|
||||
|
||||
pub async fn add_relay(&self, url: &str) -> Result<()> {
|
||||
self.client.add_relay(url).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a relay used only for discovery (e.g. NIP-65 indexer relays).
|
||||
/// No subscriptions or writes are routed through it.
|
||||
pub async fn add_discovery_relay(&self, url: &str) -> Result<()> {
|
||||
self.client
|
||||
.add_relay(url)
|
||||
.capabilities(RelayCapabilities::DISCOVERY)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn connect(&self) {
|
||||
self.client.connect().await;
|
||||
}
|
||||
|
||||
/// Start a persistent subscription. Received events are stored in the
|
||||
/// database automatically by the relay pool.
|
||||
pub async fn subscribe(&self, filter: Filter) -> Result<SubscriptionId> {
|
||||
let output = self.client.subscribe(filter).await?;
|
||||
Ok(output.value)
|
||||
}
|
||||
|
||||
/// Query the local database (the single source of truth for the UI).
|
||||
pub async fn query(&self, filter: Filter) -> Result<Vec<Event>> {
|
||||
let events = self.client.database().query(filter).await?;
|
||||
Ok(events.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Sign with the current signer, broadcast, and save locally so the
|
||||
/// event is immediately visible to [`NostrBackend::query`].
|
||||
pub async fn send(&self, builder: EventBuilder) -> Result<Event> {
|
||||
let event = builder.finalize_async(&self.signer).await?;
|
||||
|
||||
let output = self.client.send_event(&event).await?;
|
||||
|
||||
// Keep our own events in the local database; the notification pump
|
||||
// only fires for events received from relays.
|
||||
self.client.database().save_event(&event).await?;
|
||||
|
||||
if output.success.is_empty() && !output.failed.is_empty() {
|
||||
let reasons = output
|
||||
.failed
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
return Err(anyhow!("event not accepted by any relay: {reasons}"));
|
||||
}
|
||||
|
||||
Ok(event)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod backend;
|
||||
mod signer;
|
||||
mod update;
|
||||
|
||||
pub use backend::NostrBackend;
|
||||
pub use signer::{SignedAuthUrlHandler, UniversalSigner};
|
||||
pub use update::Update;
|
||||
@@ -0,0 +1,201 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use nostr_connect::client::AuthUrlHandler;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UniversalSignerError(Box<dyn Error + Send + Sync + 'static>);
|
||||
|
||||
impl fmt::Display for UniversalSignerError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for UniversalSignerError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
Some(&*self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl UniversalSignerError {
|
||||
pub fn new<E>(err: E) -> Self
|
||||
where
|
||||
E: Error + Send + Sync + 'static,
|
||||
{
|
||||
UniversalSignerError(Box::new(err))
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased signer whose inner signer can be swapped in-place
|
||||
/// (e.g. after login/logout). All clones see the swap.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UniversalSigner {
|
||||
inner: Arc<RwLock<Arc<dyn InnerSigner>>>,
|
||||
}
|
||||
|
||||
impl UniversalSigner {
|
||||
pub fn new<T>(signer: T) -> Self
|
||||
where
|
||||
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
||||
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
||||
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
||||
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
||||
{
|
||||
Self {
|
||||
inner: Arc::new(RwLock::new(Arc::new(InnerSignerImpl(signer)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap the inner signer in-place. All clones see the new signer.
|
||||
pub fn swap_inner<T>(&self, new_signer: T)
|
||||
where
|
||||
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
|
||||
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
||||
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
||||
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
||||
{
|
||||
*self.inner.write().expect("RwLock poisoned") = Arc::new(InnerSignerImpl(new_signer));
|
||||
}
|
||||
}
|
||||
|
||||
trait InnerSigner: fmt::Debug + Send + Sync + 'static {
|
||||
fn get_public_key_async(
|
||||
&self,
|
||||
) -> Pin<Box<dyn Future<Output = Result<PublicKey, UniversalSignerError>> + Send + '_>>;
|
||||
fn sign_event_async(
|
||||
&self,
|
||||
unsigned: UnsignedEvent,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Event, UniversalSignerError>> + Send + '_>>;
|
||||
fn nip44_encrypt_async<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
content: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>>;
|
||||
fn nip44_decrypt_async<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
payload: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InnerSignerImpl<T>(T);
|
||||
|
||||
impl<T> InnerSigner for InnerSignerImpl<T>
|
||||
where
|
||||
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Send + Sync + 'static,
|
||||
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
|
||||
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
|
||||
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
|
||||
{
|
||||
fn get_public_key_async(
|
||||
&self,
|
||||
) -> Pin<Box<dyn Future<Output = Result<PublicKey, UniversalSignerError>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
AsyncGetPublicKey::get_public_key_async(&self.0)
|
||||
.await
|
||||
.map_err(UniversalSignerError::new)
|
||||
})
|
||||
}
|
||||
|
||||
fn sign_event_async(
|
||||
&self,
|
||||
unsigned: UnsignedEvent,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Event, UniversalSignerError>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
AsyncSignEvent::sign_event_async(&self.0, unsigned)
|
||||
.await
|
||||
.map_err(UniversalSignerError::new)
|
||||
})
|
||||
}
|
||||
|
||||
fn nip44_encrypt_async<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
content: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
AsyncNip44::nip44_encrypt_async(&self.0, public_key, content)
|
||||
.await
|
||||
.map_err(UniversalSignerError::new)
|
||||
})
|
||||
}
|
||||
|
||||
fn nip44_decrypt_async<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
payload: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
AsyncNip44::nip44_decrypt_async(&self.0, public_key, payload)
|
||||
.await
|
||||
.map_err(UniversalSignerError::new)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncGetPublicKey for UniversalSigner {
|
||||
type Error = UniversalSignerError;
|
||||
|
||||
fn get_public_key_async(
|
||||
&self,
|
||||
) -> Pin<Box<dyn Future<Output = Result<PublicKey, Self::Error>> + Send + '_>> {
|
||||
let inner = self.inner.read().expect("RwLock poisoned").clone();
|
||||
Box::pin(async move { inner.get_public_key_async().await })
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncSignEvent for UniversalSigner {
|
||||
type Error = UniversalSignerError;
|
||||
|
||||
fn sign_event_async(
|
||||
&self,
|
||||
unsigned: UnsignedEvent,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Event, Self::Error>> + Send + '_>> {
|
||||
let inner = self.inner.read().expect("RwLock poisoned").clone();
|
||||
Box::pin(async move { inner.sign_event_async(unsigned).await })
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncNip44 for UniversalSigner {
|
||||
type Error = UniversalSignerError;
|
||||
|
||||
fn nip44_encrypt_async<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
content: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String, Self::Error>> + Send + 'a>> {
|
||||
let inner = self.inner.read().expect("RwLock poisoned").clone();
|
||||
Box::pin(async move { inner.nip44_encrypt_async(public_key, content).await })
|
||||
}
|
||||
|
||||
fn nip44_decrypt_async<'a>(
|
||||
&'a self,
|
||||
public_key: &'a PublicKey,
|
||||
payload: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String, Self::Error>> + Send + 'a>> {
|
||||
let inner = self.inner.read().expect("RwLock poisoned").clone();
|
||||
Box::pin(async move { inner.nip44_decrypt_async(public_key, payload).await })
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the NIP-46 auth URL in the default browser.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SignedAuthUrlHandler;
|
||||
|
||||
impl AuthUrlHandler for SignedAuthUrlHandler {
|
||||
fn on_auth_url(
|
||||
&self,
|
||||
auth_url: Url,
|
||||
) -> Pin<Box<dyn Future<Output = Result<(), nostr_connect::error::Error>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
webbrowser::open(auth_url.as_str()).unwrap();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
/// A lightweight "something changed" signal for the UI.
|
||||
///
|
||||
/// Heavy data stays in the database; consumers re-query on receipt.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Update {
|
||||
pub kind: Kind,
|
||||
/// First `a` tag value of the event, if any (e.g. the repository coordinate).
|
||||
pub coordinate: Option<String>,
|
||||
pub author: PublicKey,
|
||||
pub event_id: EventId,
|
||||
}
|
||||
|
||||
impl Update {
|
||||
/// Build an update from a received event.
|
||||
pub fn from_event(event: &Event) -> Self {
|
||||
let coordinate = event
|
||||
.tags
|
||||
.iter()
|
||||
.find(|t| t.kind() == "a")
|
||||
.and_then(|t| t.content())
|
||||
.map(str::to_owned);
|
||||
|
||||
Self {
|
||||
kind: event.kind,
|
||||
coordinate,
|
||||
author: event.pubkey,
|
||||
event_id: event.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user