From db6c87a86bab84ebbe7b3fdcef41a81f915d45c8 Mon Sep 17 00:00:00 2001 From: Yuki Kishimoto Date: Mon, 29 Jan 2024 15:59:45 +0100 Subject: [PATCH] sdk: add `max_num_tags` limit --- crates/nostr-sdk/src/relay/limits.rs | 9 ++++++--- crates/nostr-sdk/src/relay/mod.rs | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/nostr-sdk/src/relay/limits.rs b/crates/nostr-sdk/src/relay/limits.rs index 13503010e..4a686e734 100644 --- a/crates/nostr-sdk/src/relay/limits.rs +++ b/crates/nostr-sdk/src/relay/limits.rs @@ -19,7 +19,10 @@ impl Default for Limits { messages: MessagesLimits { max_size: 5_250_000, }, - events: EventsLimits { max_size: 70_000 }, + events: EventsLimits { + max_size: 70_000, + max_num_tags: 2_000, + }, } } } @@ -36,8 +39,8 @@ pub struct MessagesLimits { pub struct EventsLimits { /// Maximum size of normalised JSON, in bytes pub max_size: u32, - // /// Maximum number of tags allowed - // pub max_num_tags: u16, + /// Maximum number of tags allowed + pub max_num_tags: u16, // Maximum size for tag values, in bytes // pub max_tag_val_size: u16, } diff --git a/crates/nostr-sdk/src/relay/mod.rs b/crates/nostr-sdk/src/relay/mod.rs index b49c6dba6..4e947c4d8 100644 --- a/crates/nostr-sdk/src/relay/mod.rs +++ b/crates/nostr-sdk/src/relay/mod.rs @@ -144,6 +144,14 @@ pub enum Error { /// Max event size max_size: usize, }, + /// Too many tags + #[error("Received event with too many tags: tags={size}, max_tags={max_size}")] + TooManyTags { + /// Tags num + size: usize, + /// Max tags num + max_size: usize, + }, } /// Relay connection status @@ -795,11 +803,27 @@ impl Relay { tracing::trace!("Received message from {}: {:?}", relay.url, msg); if let RawRelayMessage::Event { event, .. } = &msg { + // Check event size let size: usize = event.to_string().as_bytes().len(); let max_size: usize = relay.limits.events.max_size as usize; if size > max_size { return Err(Error::EventTooLarge { size, max_size }); } + + // Check tags limit + if let Some(tags) = event.get("tags") { + if let Some(tags) = tags.as_array() { + let size: usize = tags.len(); + let max_num_tags: usize = + relay.limits.events.max_num_tags as usize; + if size > max_num_tags { + return Err(Error::TooManyTags { + size, + max_size: max_num_tags, + }); + } + } + } } if let Err(err) = relay