Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remote thread subscriptions & unify filter types #272

Merged
merged 3 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


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

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

10 changes: 7 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ default-run = "notedeck"
[lib]
crate-type = ["lib", "cdylib"]

[workspace.dependencies]
nostrdb = { git = "https://github.com/damus-io/nostrdb-rs", rev = "385a1af481ff8c08949a885248544483a52acbeb" }
#nostrdb = { path = "/Users/jb55/dev/github/damus-io/nostrdb-rs" }
#nostrdb = "0.3.4"

[dependencies]
#egui-android = { git = "https://github.com/jb55/egui-android.git" }
egui = { git = "https://github.com/emilk/egui", rev = "fcb7764e48ce00f8f8e58da10f937410d65b0bfb" }
Expand All @@ -33,14 +38,13 @@ serde_json = "1.0.89"
env_logger = "0.10.0"
puffin_egui = { version = "0.27.0", optional = true }
puffin = { version = "0.19.0", optional = true }
nostrdb = { git = "https://github.com/damus-io/nostrdb-rs", rev = "04e5917b44b0112ecfd0eb93e8a1e2c81fce1d75" }
#nostrdb = { path = "/Users/jb55/dev/github/damus-io/nostrdb-rs" }
#nostrdb = "0.3.4"
hex = "0.4.3"
base32 = "0.4.0"
strum = "0.26"
strum_macros = "0.26"
bitflags = "2.5.0"
uuid = { version = "1.10.0", features = ["v4"] }
nostrdb = { workspace = true }

[target.'cfg(target_os = "macos")'.dependencies]
security-framework = "2.11.0"
Expand Down
4 changes: 2 additions & 2 deletions enostr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ ewebsock = { version = "0.2.0", features = ["tls"] }
serde_derive = "1"
serde = { version = "1", features = ["derive"] } # You only need this if you want app persistence
serde_json = "1.0.89"
tracing = "0.1.37"
nostrdb = { workspace = true }
nostr = { version = "0.30.0" }
hex = "0.4.3"
log = "0.4.20"
tracing = "0.1.40"
env_logger = "0.11.1"
31 changes: 17 additions & 14 deletions enostr/src/client/message.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::{Filter, Note};
use crate::{Error, Note};
use nostrdb::Filter;
use serde_json::json;

/// Messages sent by clients, received by relays
#[derive(Debug, Eq, PartialEq)]
#[derive(Debug)]
pub enum ClientMessage {
Event {
note: Note,
Expand Down Expand Up @@ -34,23 +35,25 @@ impl ClientMessage {
ClientMessage::Close { sub_id }
}

pub fn to_json(&self) -> String {
match self {
pub fn to_json(&self) -> Result<String, Error> {
Ok(match self {
Self::Event { note } => json!(["EVENT", note]).to_string(),
Self::Raw(raw) => raw.clone(),
Self::Req { sub_id, filters } => {
let mut json = json!(["REQ", sub_id]);
let mut filters = json!(filters);

if let Some(json) = json.as_array_mut() {
if let Some(filters) = filters.as_array_mut() {
json.append(filters);
}
if filters.is_empty() {
format!("[\"REQ\",\"{}\",{{ }}]", sub_id)
} else if filters.len() == 1 {
let filters_json_str = filters[0].json()?;
format!("[\"REQ\",\"{}\",{}]", sub_id, filters_json_str)
} else {
let filters_json_str: Result<Vec<String>, Error> = filters
.iter()
.map(|f| f.json().map_err(Into::<Error>::into))
.collect();
format!("[\"REQ\",\"{}\",{}]", sub_id, filters_json_str?.join(","))
}

json.to_string()
}
Self::Close { sub_id } => json!(["CLOSE", sub_id]).to_string(),
}
})
}
}
10 changes: 9 additions & 1 deletion enostr/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//use nostr::prelude::secp256k1;
use serde_json;
use std::array::TryFromSliceError;
use std::fmt;

Expand All @@ -14,6 +13,7 @@ pub enum Error {
InvalidPublicKey,
// Secp(secp256k1::Error),
Json(serde_json::Error),
Nostrdb(nostrdb::Error),
Generic(String),
}

Expand All @@ -29,6 +29,7 @@ impl std::cmp::PartialEq for Error {
// This is slightly wrong but whatevs
(Error::Json(..), Error::Json(..)) => true,
(Error::Generic(left), Error::Generic(right)) => left == right,
(Error::Nostrdb(left), Error::Nostrdb(right)) => left == right,
//(Error::Secp(left), Error::Secp(right)) => left == right,
_ => false,
}
Expand All @@ -47,6 +48,7 @@ impl fmt::Display for Error {
Self::InvalidPublicKey => write!(f, "invalid public key"),
//Self::Secp(e) => write!(f, "{e}"),
Self::Json(e) => write!(f, "{e}"),
Self::Nostrdb(e) => write!(f, "{e}"),
Self::Generic(e) => write!(f, "{e}"),
}
}
Expand Down Expand Up @@ -85,3 +87,9 @@ impl From<serde_json::Error> for Error {
Error::Json(e)
}
}

impl From<nostrdb::Error> for Error {
fn from(e: nostrdb::Error) -> Self {
Error::Nostrdb(e)
}
}
92 changes: 1 addition & 91 deletions enostr/src/filter.rs
Original file line number Diff line number Diff line change
@@ -1,91 +1 @@
use crate::{NoteId, Pubkey};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct Filter {
#[serde(skip_serializing_if = "Option::is_none")]
pub ids: Option<Vec<NoteId>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authors: Option<Vec<Pubkey>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kinds: Option<Vec<u64>>,
#[serde(rename = "#e")]
#[serde(skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<NoteId>>,
#[serde(rename = "#p")]
#[serde(skip_serializing_if = "Option::is_none")]
pub pubkeys: Option<Vec<Pubkey>>,
#[serde(rename = "#t")]
#[serde(skip_serializing_if = "Option::is_none")]
pub hashtags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub since: Option<u64>, // unix timestamp seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub until: Option<u64>, // unix timestamp seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u16>,
}

impl Filter {
pub fn new() -> Filter {
Filter {
ids: None,
authors: None,
kinds: None,
events: None,
pubkeys: None,
hashtags: None,
since: None,
until: None,
limit: None,
}
}

pub fn default_limit() -> u16 {
250
}

pub fn default_remote_limit() -> u16 {
150
}

pub fn ids(mut self, ids: Vec<NoteId>) -> Self {
self.ids = Some(ids);
self
}

pub fn authors(mut self, authors: Vec<Pubkey>) -> Self {
self.authors = Some(authors);
self
}

pub fn kinds(mut self, kinds: Vec<u64>) -> Self {
self.kinds = Some(kinds);
self
}

pub fn events(mut self, events: Vec<NoteId>) -> Self {
self.events = Some(events);
self
}

pub fn pubkeys(mut self, pubkeys: Vec<Pubkey>) -> Self {
self.pubkeys = Some(pubkeys);
self
}

pub fn since(mut self, since: u64) -> Self {
self.since = Some(since);
self
}

pub fn until(mut self, until: u64) -> Self {
self.until = Some(until);
self
}

pub fn limit(mut self, limit: u16) -> Self {
self.limit = Some(limit);
self
}
}
pub type Filter = nostrdb::Filter;
22 changes: 6 additions & 16 deletions enostr/src/keypair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl FullKeypair {
let secret_key = nostr::SecretKey::from(*secret_key);
FullKeypair {
pubkey: Pubkey::new(&xopk.serialize()),
secret_key: SecretKey::from(secret_key),
secret_key,
}
}

Expand Down Expand Up @@ -90,11 +90,7 @@ impl std::fmt::Display for Keypair {

impl std::fmt::Display for FullKeypair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Keypair:\n\tpublic: {}\n\tsecret: {}",
self.pubkey, "<hidden>"
)
write!(f, "Keypair:\n\tpublic: {}\n\tsecret: <hidden>", self.pubkey)
}
}

Expand All @@ -108,23 +104,17 @@ impl SerializableKeypair {
pub fn from_keypair(kp: &Keypair, pass: &str, log_n: u8) -> Self {
Self {
pubkey: kp.pubkey.clone(),
encrypted_secret_key: kp
.secret_key
.clone()
.map(|s| {
EncryptedSecretKey::new(&s, pass, log_n, nostr::nips::nip49::KeySecurity::Weak)
.ok()
})
.flatten(),
encrypted_secret_key: kp.secret_key.clone().and_then(|s| {
EncryptedSecretKey::new(&s, pass, log_n, nostr::nips::nip49::KeySecurity::Weak).ok()
}),
}
}

pub fn to_keypair(&self, pass: &str) -> Keypair {
Keypair::new(
self.pubkey.clone(),
self.encrypted_secret_key
.map(|e| e.to_secret_key(pass).ok())
.flatten(),
.and_then(|e| e.to_secret_key(pass).ok()),
)
}
}
2 changes: 1 addition & 1 deletion enostr/src/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl Note {
}

pub fn verify(&self) -> Result<Self, Error> {
return Err(Error::InvalidSignature);
Err(Error::InvalidSignature)
}

/// This is just for serde sanity checking
Expand Down
2 changes: 1 addition & 1 deletion enostr/src/pubkey.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::Error;
use log::debug;
use nostr::bech32::Hrp;
use std::fmt;
use tracing::debug;

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub struct Pubkey([u8; 32]);
Expand Down
12 changes: 6 additions & 6 deletions enostr/src/relay/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl<'a> From<&'a WsEvent> for RelayEvent<'a> {
impl<'a> From<&'a WsMessage> for RelayEvent<'a> {
fn from(wsmsg: &'a WsMessage) -> RelayEvent<'a> {
match wsmsg {
WsMessage::Text(ref s) => match RelayMessage::from_json(&s).map(RelayEvent::Message) {
WsMessage::Text(s) => match RelayMessage::from_json(s).map(RelayEvent::Message) {
Ok(msg) => msg,
Err(err) => RelayEvent::Error(err),
},
Expand All @@ -59,9 +59,9 @@ impl<'a> RelayMessage<'a> {

pub fn ok(event_id: &'a str, status: bool, message: &'a str) -> Self {
RelayMessage::OK(CommandResult {
event_id: event_id,
event_id,
status,
message: message,
message,
})
}

Expand All @@ -78,7 +78,7 @@ impl<'a> RelayMessage<'a> {
// Relay response format: ["NOTICE", <message>]
if &msg[0..=9] == "[\"NOTICE\"," {
// TODO: there could be more than one space, whatever
let start = if msg.bytes().nth(10) == Some(b' ') {
let start = if msg.as_bytes().get(10).copied() == Some(b' ') {
12
} else {
11
Expand All @@ -96,7 +96,7 @@ impl<'a> RelayMessage<'a> {
// EOSE (NIP-15)
// Relay response format: ["EOSE", <subscription_id>]
if &msg[0..=7] == "[\"EOSE\"," {
let start = if msg.bytes().nth(8) == Some(b' ') {
let start = if msg.as_bytes().get(8).copied() == Some(b' ') {
10
} else {
9
Expand Down Expand Up @@ -161,7 +161,7 @@ mod tests {

#[test]
fn test_handle_valid_event() -> Result<()> {
use log::debug;
use tracing::debug;

env_logger::init();
let valid_event_msg = r#"["EVENT", "random_string", {"id":"70b10f70c1318967eddf12527799411b1a9780ad9c43858f5e5fcd45486a13a5","pubkey":"379e863e8357163b5bce5d2688dc4f1dcc2d505222fb8d74db600f30535dfdfe","created_at":1612809991,"kind":1,"tags":[],"content":"test","sig":"273a9cd5d11455590f4359500bccb7a89428262b96b3ea87a756b770964472f8c3e87f5d5e64d8d2e859a71462a3f477b554565c4f2f326cb01dd7620db71502"}]"#;
Expand Down
Loading
Loading