Skip to content

Commit

Permalink
nostr: add pow field to Filter
Browse files Browse the repository at this point in the history
* nostr: check `pow` in `Filter::match_event`
* lmdb: check `pow` in `DatabaseFilter::match_event`

Signed-off-by: Yuki Kishimoto <[email protected]>
  • Loading branch information
yukibtc committed Sep 24, 2024
1 parent b1fdeae commit d9b25c0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions crates/nostr-lmdb/src/store/types/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::str::FromStr;

use nostr::nips::nip13;
use nostr::{Filter, SingleLetterTag, Timestamp};
use nostr_database::flatbuffers::event_fbs::Fixed32Bytes;

Expand All @@ -18,6 +19,7 @@ pub struct DatabaseFilter {
pub search: Option<String>,
pub since: Option<Timestamp>,
pub until: Option<Timestamp>,
pub pow: Option<u8>,
pub generic_tags: BTreeMap<SingleLetterTag, BTreeSet<String>>,
}

Expand Down Expand Up @@ -78,6 +80,14 @@ impl DatabaseFilter {
}
}

#[inline]
fn pow_match(&self, event: &DatabaseEvent) -> bool {
match self.pow {
Some(difficulty) => nip13::get_leading_zero_bits(event.id.0) >= difficulty,
None => true,
}
}

#[inline]
pub fn match_event(&self, event: &DatabaseEvent) -> bool {
self.ids_match(event)
Expand All @@ -86,6 +96,7 @@ impl DatabaseFilter {
&& self.since.map_or(true, |t| event.created_at >= t)
&& self.until.map_or(true, |t| event.created_at <= t)
&& self.tag_match(event)
&& self.pow_match(event)
&& self.search_match(event)
}
}
Expand Down Expand Up @@ -121,6 +132,7 @@ impl From<Filter> for DatabaseFilter {
}),
since: filter.since,
until: filter.until,
pow: filter.pow,
generic_tags: filter.generic_tags,
}
}
Expand Down
15 changes: 15 additions & 0 deletions crates/nostr/src/types/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,12 @@ pub struct Filter {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub limit: Option<usize>,
/// Minimum POW difficulty
///
/// <https://github.com/nostr-protocol/nips/blob/master/13.md>
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub pow: Option<u8>,
/// Generic tag queries
#[serde(
flatten,
Expand Down Expand Up @@ -768,6 +774,14 @@ impl Filter {
}
}

#[inline]
fn pow_match(&self, event: &Event) -> bool {
match self.pow {
Some(difficulty) => event.id.check_pow(difficulty),
None => true,
}
}

/// Determine if [Filter] match given [Event].
#[inline]
pub fn match_event(&self, event: &Event) -> bool {
Expand All @@ -777,6 +791,7 @@ impl Filter {
&& self.since.map_or(true, |t| event.created_at >= t)
&& self.until.map_or(true, |t| event.created_at <= t)
&& self.tag_match(event)
&& self.pow_match(event)
&& self.search_match(event)
}
}
Expand Down

0 comments on commit d9b25c0

Please sign in to comment.