use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use super::id::EventId;
use super::kind::Kind;
use super::tag::{Coordinate, Tag};
use super::{Error, Event, Result, UnsignedEvent, canonical};
use crate::key::PublicKey;
use crate::time::Timestamp;
use crate::url::RelayUrl;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Metadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub about: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub picture: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub banner: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub website: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub nip05: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lud06: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lud16: Option<String>,
}
impl Metadata {
fn to_json(&self) -> String {
let mut out = String::from("{");
let mut first = true;
for (key, value) in [
("name", &self.name),
("display_name", &self.display_name),
("about", &self.about),
("picture", &self.picture),
("banner", &self.banner),
("website", &self.website),
("nip05", &self.nip05),
("lud06", &self.lud06),
("lud16", &self.lud16),
] {
let Some(value) = value else {
continue;
};
if !first {
out.push(',');
}
first = false;
canonical::push_json_string(key, &mut out);
out.push(':');
canonical::push_json_string(value, &mut out);
}
out.push('}');
out
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeletionTarget {
Event {
id: EventId,
kind: Option<Kind>,
},
Address(Coordinate),
}
#[cfg_attr(not(feature = "clock"), doc = "```compile_fail")]
#[cfg_attr(
not(feature = "clock"),
doc = "let _ = nk_core::EventBuilder::text_note(\"x\")"
)]
#[cfg_attr(
not(feature = "clock"),
doc = " .build(nk_core::PublicKey::from_bytes([0; 32]));"
)]
#[cfg_attr(not(feature = "clock"), doc = "```")]
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
pub struct EventBuilder {
kind: Kind,
content: String,
tags: Vec<Tag>,
}
impl EventBuilder {
pub fn new<S: Into<String>>(kind: Kind, content: S) -> Self {
Self {
kind,
content: content.into(),
tags: Vec::new(),
}
}
pub fn text_note<S: Into<String>>(content: S) -> Self {
Self::new(Kind::TEXT_NOTE, content)
}
pub fn metadata(metadata: &Metadata) -> Self {
Self::new(Kind::METADATA, metadata.to_json())
}
pub fn contacts<I>(pubkeys: I) -> Self
where
I: IntoIterator<Item = PublicKey>,
{
let mut builder = Self::new(Kind::CONTACTS, "");
builder.tags.extend(
pubkeys
.into_iter()
.map(|pk| Tag::public_key(pk, None, None)),
);
builder
}
pub fn deletion<I, S>(targets: I, reason: S) -> Self
where
I: IntoIterator<Item = DeletionTarget>,
S: Into<String>,
{
let mut builder = Self::new(Kind::EVENT_DELETION, reason);
let mut kinds: Vec<Kind> = Vec::new();
for target in targets {
let kind = match &target {
DeletionTarget::Event { id, kind } => {
builder.tags.push(Tag::event(*id, None, None, None));
*kind
}
DeletionTarget::Address(address) => {
builder.tags.push(Tag::address(address, None));
Some(address.kind())
}
};
if let Some(kind) = kind
&& !kinds.contains(&kind)
{
kinds.push(kind);
}
}
builder.tags.extend(kinds.into_iter().map(Tag::kind));
builder
}
pub fn reaction<S>(target: &Event, content: S, relay_hint: Option<&RelayUrl>) -> Result<Self>
where
S: Into<String>,
{
let coord = if target.kind().is_addressable() {
let d = target.tags().identifier().ok_or(Error::MissingIdentifier)?;
Some(Coordinate::new(target.kind(), target.pubkey(), d))
} else {
None
};
let mut builder = Self::new(Kind::REACTION, content);
builder.tags.push(Tag::custom(
"e",
[
target.id().to_hex(),
relay_hint.map_or_else(String::new, |url| String::from(url.as_str())),
target.pubkey().to_hex(),
],
));
builder
.tags
.push(Tag::public_key(target.pubkey(), relay_hint, None));
builder.tags.push(Tag::kind(target.kind()));
if let Some(coord) = coord {
builder.tags.push(Tag::address(&coord, relay_hint));
}
Ok(builder)
}
pub fn repost(target: &Event, relay_hint: &RelayUrl) -> Result<Self> {
if target.kind() != Kind::TEXT_NOTE {
return Err(Error::InvalidTargetKind {
found: target.kind(),
});
}
let content = if protected(target) {
String::new()
} else {
target.to_json()
};
let mut builder = Self::new(Kind::REPOST, content);
builder
.tags
.push(Tag::event(target.id(), Some(relay_hint), None, None));
builder
.tags
.push(Tag::public_key(target.pubkey(), None, None));
Ok(builder)
}
pub fn generic_repost(
target: &Event,
relay_hint: &RelayUrl,
p_pubkey: Option<PublicKey>,
) -> Result<Self> {
if target.kind() == Kind::TEXT_NOTE {
return Err(Error::InvalidTargetKind {
found: target.kind(),
});
}
let replaceable = target.kind().is_replaceable();
let addressable = target.kind().is_addressable();
let d = target.tags().identifier();
if addressable && d.is_none() {
return Err(Error::MissingIdentifier);
}
let content = if protected(target) || replaceable || addressable {
String::new()
} else {
target.to_json()
};
let mut builder = Self::new(Kind::GENERIC_REPOST, content);
builder
.tags
.push(Tag::event(target.id(), Some(relay_hint), None, None));
builder.tags.push(Tag::public_key(
p_pubkey.unwrap_or_else(|| target.pubkey()),
None,
None,
));
builder.tags.push(Tag::kind(target.kind()));
if replaceable || addressable {
let address = Coordinate::new(target.kind(), target.pubkey(), d.unwrap_or_default());
builder.tags.push(Tag::address(&address, None));
}
Ok(builder)
}
pub fn tag(mut self, tag: Tag) -> Self {
self.tags.push(tag);
self
}
pub fn tags<I>(mut self, tags: I) -> Self
where
I: IntoIterator<Item = Tag>,
{
self.tags.extend(tags);
self
}
#[must_use]
pub fn build_at(self, pubkey: PublicKey, created_at: Timestamp) -> UnsignedEvent {
UnsignedEvent::new(
pubkey,
created_at,
self.kind,
self.tags.into_iter().collect(),
self.content,
)
}
#[cfg(feature = "clock")]
#[must_use]
pub fn build(self, pubkey: PublicKey) -> UnsignedEvent {
self.build_at(pubkey, Timestamp::now())
}
}
fn protected(event: &Event) -> bool {
event.tags().iter().any(|tag| tag.name() == "-")
}
#[cfg(test)]
mod tests {
use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
use super::*;
use crate::key::{Keys, SecretKey};
const SK_HEX: &str = "d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf";
const RELAY: &str = "wss://r.example/nostr";
fn keys() -> Keys {
Keys::new(SecretKey::from_hex(SK_HEX).unwrap())
}
fn sign(builder: EventBuilder) -> Event {
let unsigned = builder.build_at(keys().public_key(), Timestamp::from_secs(1));
crate::testutil::sign_with_aux(&keys(), unsigned, [0; 32])
}
fn relay() -> RelayUrl {
RelayUrl::parse(RELAY).unwrap()
}
fn tag_slices(event: &UnsignedEvent) -> Vec<Vec<String>> {
event
.tags()
.iter()
.map(|tag| tag.as_slice().to_vec())
.collect()
}
#[test]
fn text_note() {
let unsigned = EventBuilder::text_note("hello")
.tag(Tag::hashtag("nostr"))
.build_at(keys().public_key(), Timestamp::from_secs(1_700_000_000));
assert_eq!(unsigned.kind(), Kind::TEXT_NOTE);
assert_eq!(unsigned.content(), "hello");
assert_eq!(tag_slices(&unsigned), vec![vec!["t", "nostr"]]);
}
#[test]
fn metadata_declared_key_order() {
let meta = Metadata {
lud16: Some("a@b".to_owned()),
name: Some("alice".to_owned()),
nip05: Some("n@x".to_owned()),
..Metadata::default()
};
let unsigned =
EventBuilder::metadata(&meta).build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(unsigned.kind(), Kind::METADATA);
assert_eq!(
unsigned.content(),
r#"{"name":"alice","nip05":"n@x","lud16":"a@b"}"#
);
}
#[test]
fn metadata_json_matches_serde() {
let meta = Metadata {
name: Some("a\u{2028}b\n".to_owned()),
display_name: Some("d".to_owned()),
about: Some("\u{1F600}".to_owned()),
..Metadata::default()
};
assert_eq!(meta.to_json(), serde_json::to_string(&meta).unwrap());
}
#[test]
fn contacts() {
let pk = keys().public_key();
let unsigned = EventBuilder::contacts(vec![pk, pk]).build_at(pk, Timestamp::from_secs(1));
assert_eq!(
tag_slices(&unsigned),
vec![
vec!["p".to_owned(), pk.to_hex()],
vec!["p".to_owned(), pk.to_hex()]
]
);
}
#[test]
fn deletion_mixed_targets() {
let id = EventId::from_bytes([7; 32]);
let address = Coordinate::new(Kind::new(30023), keys().public_key(), "d1");
let unsigned = EventBuilder::deletion(
vec![
DeletionTarget::Event {
id,
kind: Some(Kind::TEXT_NOTE),
},
DeletionTarget::Event { id, kind: None },
DeletionTarget::Address(address.clone()),
DeletionTarget::Event {
id,
kind: Some(Kind::TEXT_NOTE),
},
],
"spam",
)
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(unsigned.content(), "spam");
assert_eq!(
tag_slices(&unsigned),
vec![
vec!["e".to_owned(), id.to_hex()],
vec!["e".to_owned(), id.to_hex()],
vec!["a".to_owned(), address.to_string()],
vec!["e".to_owned(), id.to_hex()],
vec!["k".to_owned(), "1".to_owned()],
vec!["k".to_owned(), "30023".to_owned()],
]
);
}
#[test]
fn reaction_tags() {
let target = sign(EventBuilder::text_note("n"));
let unsigned = EventBuilder::reaction(&target, "+", Some(&relay()))
.unwrap()
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(unsigned.kind(), Kind::REACTION);
assert_eq!(
tag_slices(&unsigned),
vec![
vec![
"e".to_owned(),
target.id().to_hex(),
RELAY.to_owned(),
target.pubkey().to_hex()
],
vec!["p".to_owned(), target.pubkey().to_hex(), RELAY.to_owned()],
vec!["k".to_owned(), "1".to_owned()],
]
);
}
#[test]
fn reaction_no_hint_empty_relay_slot() {
let target = sign(EventBuilder::text_note("n"));
let unsigned = EventBuilder::reaction(&target, "+", None)
.unwrap()
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(
tag_slices(&unsigned),
vec![
vec![
"e".to_owned(),
target.id().to_hex(),
String::new(),
target.pubkey().to_hex()
],
vec!["p".to_owned(), target.pubkey().to_hex()],
vec!["k".to_owned(), "1".to_owned()],
]
);
}
#[test]
fn reaction_addressable() {
let target = sign(EventBuilder::new(Kind::new(30023), "v").tag(Tag::identifier("ep1")));
let unsigned = EventBuilder::reaction(&target, "🔥", None)
.unwrap()
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(
tag_slices(&unsigned),
vec![
vec![
"e".to_owned(),
target.id().to_hex(),
String::new(),
target.pubkey().to_hex()
],
vec!["p".to_owned(), target.pubkey().to_hex()],
vec!["k".to_owned(), "30023".to_owned()],
vec![
"a".to_owned(),
format!("30023:{}:ep1", target.pubkey().to_hex())
],
]
);
}
#[test]
fn reaction_addressable_without_d_errors() {
let target = sign(EventBuilder::new(Kind::new(30023), "v"));
let err = EventBuilder::reaction(&target, "+", None).unwrap_err();
assert!(matches!(err, Error::MissingIdentifier));
}
#[test]
fn repost_embeds_event_json() {
let target = sign(EventBuilder::text_note("esc \" \\ \n 😀").tag(Tag::identifier("d")));
let unsigned = EventBuilder::repost(&target, &relay())
.unwrap()
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(unsigned.content(), serde_json::to_string(&target).unwrap());
assert_eq!(
tag_slices(&unsigned),
vec![
vec!["e".to_owned(), target.id().to_hex(), RELAY.to_owned()],
vec!["p".to_owned(), target.pubkey().to_hex()],
]
);
}
#[test]
fn repost_protected_empty_content() {
let target = sign(EventBuilder::text_note("p").tag(Tag::new(vec!["-"]).unwrap()));
let unsigned = EventBuilder::repost(&target, &relay())
.unwrap()
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(unsigned.content(), "");
}
#[test]
fn repost_rejects_non_text_note() {
let target = sign(EventBuilder::new(Kind::new(6), "x"));
assert!(matches!(
EventBuilder::repost(&target, &relay()).unwrap_err(),
Error::InvalidTargetKind { found } if found == Kind::new(6)
));
}
#[test]
fn generic_repost_regular_target() {
let target = sign(EventBuilder::new(Kind::new(30023), "v").tag(Tag::identifier("d1")));
let unsigned = EventBuilder::generic_repost(&target, &relay(), None)
.unwrap()
.build_at(keys().public_key(), Timestamp::from_secs(1));
assert_eq!(unsigned.kind(), Kind::GENERIC_REPOST);
assert_eq!(unsigned.content(), "");
assert_eq!(
tag_slices(&unsigned),
vec![
vec!["e".to_owned(), target.id().to_hex(), RELAY.to_owned()],
vec!["p".to_owned(), target.pubkey().to_hex()],
vec!["k".to_owned(), "30023".to_owned()],
vec![
"a".to_owned(),
format!("30023:{}:d1", target.pubkey().to_hex())
],
]
);
}
}