diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a622ca6f..e98198b7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,7 @@ * nostr: require `fmt::Debug`, `Send` and `Sync` for `NostrSigner` ([Yuki Kishimoto]) * nostr: enable support for `Tags::indexes` in `no_std` ([Yuki Kishimoto]) * nostr: improve `RelayMessage` docs ([Yuki Kishimoto]) +* nostr: dedup tags in `EventBuilder::text_note_reply` and `EventBuilder::comment` ([Yuki Kishimoto]) * database: add manual trait implementations for `BTreeCappedSet` ([Yuki Kishimoto]) * database: replace LRU with custom memory cache for IDs tracking ([Yuki Kishimoto]) * lmdb: use `async-utility` to spawn blocking tasks ([Yuki Kishimoto]) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index a92b01da0..bf0436839 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -4,6 +4,7 @@ //! Event builder +use alloc::collections::BTreeSet; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt; @@ -15,6 +16,7 @@ use bitcoin::secp256k1::rand::{CryptoRng, Rng}; use bitcoin::secp256k1::{Secp256k1, Signing, Verification}; use serde_json::{json, Value}; +use super::tag::weak::WeakTag; #[cfg(all(feature = "std", feature = "nip04", feature = "nip46"))] use crate::nips::nip46::Message as NostrConnectMessage; use crate::prelude::*; @@ -468,8 +470,13 @@ impl EventBuilder { .cloned(), ); + // Dedup tags using `WeakTag` + // TODO: compose directly tags with `BTreeSet` instead of iterate and collect? + #[allow(clippy::mutable_key_type)] + let tags: BTreeSet = tags.into_iter().map(WeakTag::new).collect(); + // Compose event - Self::new(Kind::TextNote, content).tags(tags) + Self::new(Kind::TextNote, content).tags(tags.into_iter().map(|w| w.into_inner())) } /// Comment @@ -570,7 +577,6 @@ impl EventBuilder { })); // Add others `p` tags of comment_to event - // TODO: avoid `p` tag duplicates (are added also before from root event) tags.extend( comment_to .tags @@ -585,8 +591,13 @@ impl EventBuilder { .cloned(), ); + // Dedup tags using `WeakTag` + // TODO: compose directly tags with `BTreeSet` instead of iterate and collect? + #[allow(clippy::mutable_key_type)] + let tags: BTreeSet = tags.into_iter().map(WeakTag::new).collect(); + // Compose event - Self::new(Kind::Comment, content).tags(tags) + Self::new(Kind::Comment, content).tags(tags.into_iter().map(|w| w.into_inner())) } /// Long-form text note (generally referred to as "articles" or "blog posts"). @@ -1979,6 +1990,29 @@ mod tests { assert_eq!(profile_badges.kind, Kind::ProfileBadges); assert_eq!(profile_badges.tags, example_event.tags); } + + #[test] + #[cfg(feature = "std")] + fn test_text_note_reply() { + let keys = Keys::generate(); + let json: &str = r###"{"kind":1,"created_at":1732718325,"content":"## rust-nostr v0.37 is out! 🦀\n\n### Summary\n\nAdd support to NIP17 relay list in SDK (when `gossip` option is enabled), add NIP22 and NIP73 support, \nfix Swift Package, many performance improvements and bug fixes and more!\n\nFrom this release all the rust features are be disabled by default (except `std` feature in `nostr` crate).\n\nFull changelog: https://rust-nostr.org/changelog\n\n### Contributors\n\nThanks to all contributors!\n\n* nostr:npub1zuuajd7u3sx8xu92yav9jwxpr839cs0kc3q6t56vd5u9q033xmhsk6c2uc \n* nostr:npub1q0uulk2ga9dwkp8hsquzx38hc88uqggdntelgqrtkm29r3ass6fq8y9py9 \n* nostr:npub1zfss807aer0j26mwp2la0ume0jqde3823rmu97ra6sgyyg956e0s6xw445 \n* nostr:npub1zwnx29tj2lnem8wvjcx7avm8l4unswlz6zatk0vxzeu62uqagcash7fhrf \n* nostr:npub1acxjpdrlk2vw320dxcy3prl87g5kh4c73wp0knullrmp7c4mc7nq88gj3j \n\n### Links\n\nhttps://rust-nostr.org\nhttps://rust-nostr.org/donate\n\n#rustnostr #nostr #rustlang #programming #rust #python #javascript #kotlin #swift #flutter","tags":[["t","rustnostr"],["t","nostr"],["t","rustlang"],["t","programming"],["t","rust"],["t","python"],["t","javascript"],["t","kotlin"],["t","swift"],["t","flutter"],["p","1739d937dc8c0c7370aa27585938c119e25c41f6c441a5d34c6d38503e3136ef","","mention"],["p","03f9cfd948e95aeb04f780382344f7c1cfc0210d9af3f4006bb6d451c7b08692","","mention"],["p","126103bfddc8df256b6e0abfd7f3797c80dcc4ea88f7c2f87dd4104220b4d65f","","mention"],["p","13a665157257e79d9dcc960deeb367fd79383be2d0babb3d861679a5701d463b","","mention"],["p","ee0d20b47fb298e8a9ed3609108fe7f2296bd71e8b82fb4f9ff8f61f62bbc7a6","","mention"]],"pubkey":"68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272","id":"8262a50cf7832351ae3f21c429e111bb31be0cf754ec437e015534bf5cc2eee8","sig":"7e81ff3dfb78ba59b09b48d5218331a3259c56f702a6b8e118938a219879d60e7062e90fc1b070a4c472988d1801ec55714388efc6a4a3876a8a957c5c7808b6"}"###; + let root_event = Event::from_json(json).unwrap(); + + assert_eq!(root_event.tags.public_keys().count(), 5); + + // Build reply + let reply = EventBuilder::text_note_reply("Test reply", &root_event, None, None) + .sign_with_keys(&keys) + .unwrap(); + assert_eq!(reply.tags.public_keys().count(), 6); // Previous 5 + root author + + // Build reply of reply + let reply = + EventBuilder::text_note_reply("Test reply of reply", &reply, Some(&root_event), None) + .sign_with_keys(&keys) + .unwrap(); + assert_eq!(reply.tags.public_keys().count(), 6); // Previous 5 + root author + } } #[cfg(bench)] diff --git a/crates/nostr/src/event/tag/mod.rs b/crates/nostr/src/event/tag/mod.rs index ebe8e08e7..d853ad064 100644 --- a/crates/nostr/src/event/tag/mod.rs +++ b/crates/nostr/src/event/tag/mod.rs @@ -22,6 +22,7 @@ mod error; pub mod kind; pub mod list; pub mod standard; +pub(super) mod weak; pub use self::error::Error; pub use self::kind::TagKind; diff --git a/crates/nostr/src/event/tag/weak.rs b/crates/nostr/src/event/tag/weak.rs new file mode 100644 index 000000000..0390fef26 --- /dev/null +++ b/crates/nostr/src/event/tag/weak.rs @@ -0,0 +1,51 @@ +// Copyright (c) 2022-2023 Yuki Kishimoto +// Copyright (c) 2023-2024 Rust Nostr Developers +// Distributed under the MIT software license + +//! Weak tag + +use alloc::string::String; +use core::cmp::Ordering; + +use super::Tag; + +/// [`WeakTag`] wraps [`Tag`] to provide a comparison based on only the first two values of `buf`. +pub struct WeakTag(Tag); + +impl WeakTag { + #[inline] + pub fn new(tag: Tag) -> Self { + Self(tag) + } + + #[inline] + fn first_two(&self) -> &[String] { + &self.0.buf[..self.0.buf.len().min(2)] + } + + #[inline] + pub fn into_inner(self) -> Tag { + self.0 + } +} + +// Implement ordering and equality based on the first two elements of `buf` +impl PartialEq for WeakTag { + fn eq(&self, other: &Self) -> bool { + self.first_two() == other.first_two() + } +} + +impl Eq for WeakTag {} + +impl PartialOrd for WeakTag { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for WeakTag { + fn cmp(&self, other: &Self) -> Ordering { + self.first_two().cmp(other.first_two()) + } +}