use std::fmt;
use serde::de::value::MapAccessDeserializer;
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use crate::did::DidNostr;
use crate::encoding;
use crate::id::{EventId, UnixTime};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsignedEvent {
kind: u16,
created_at: UnixTime,
tags: Vec<Vec<String>>,
content: String,
}
impl UnsignedEvent {
pub fn new(kind: u16, created_at: UnixTime) -> Self {
Self {
kind,
created_at,
tags: Vec::new(),
content: String::new(),
}
}
#[must_use]
pub fn with_tag<I, S>(mut self, tag: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tags.push(tag.into_iter().map(Into::into).collect());
self
}
#[must_use]
pub fn with_content(mut self, content: impl Into<String>) -> Self {
self.content = content.into();
self
}
pub fn kind(&self) -> u16 {
self.kind
}
pub fn created_at(&self) -> UnixTime {
self.created_at
}
pub fn tags(&self) -> &[Vec<String>] {
&self.tags
}
pub fn content(&self) -> &str {
&self.content
}
pub(crate) fn is_supported_text(&self) -> bool {
is_supported_text(&self.tags, &self.content)
}
pub(crate) fn has_empty_tag(&self) -> bool {
has_empty_tag(&self.tags)
}
pub(crate) fn id_for(&self, author: &DidNostr) -> EventId {
compute_id(
author,
self.created_at,
self.kind,
&self.tags,
&self.content,
)
}
pub(crate) fn into_signed(self, id: EventId, author: DidNostr, sig: [u8; 64]) -> SignedEvent {
SignedEvent {
id,
author,
created_at: self.created_at,
kind: self.kind,
tags: self.tags,
content: self.content,
sig,
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct SignedEvent {
id: EventId,
author: DidNostr,
created_at: UnixTime,
kind: u16,
tags: Vec<Vec<String>>,
content: String,
sig: [u8; 64],
}
impl SignedEvent {
pub fn from_json(json: &[u8]) -> Result<Self, ParseEventError> {
let mut deserializer = serde_json::Deserializer::from_slice(json);
let raw = deserialize_object(&mut deserializer)
.and_then(|raw| deserializer.end().map(|()| raw))
.map_err(|_| ParseEventError::MalformedJson)?;
Self::from_raw(raw)
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self.to_raw())
.expect("serde_json cannot fail on strings, integers and string arrays")
}
pub fn id(&self) -> EventId {
self.id
}
pub fn author(&self) -> DidNostr {
self.author
}
pub fn created_at(&self) -> UnixTime {
self.created_at
}
pub fn kind(&self) -> u16 {
self.kind
}
pub fn tags(&self) -> &[Vec<String>] {
&self.tags
}
pub fn content(&self) -> &str {
&self.content
}
pub fn signature(&self) -> &[u8; 64] {
&self.sig
}
fn from_raw(raw: RawEvent) -> Result<Self, ParseEventError> {
let claimed_id =
encoding::decode_lower_hex::<32>(&raw.id).ok_or(ParseEventError::InvalidId)?;
let author = DidNostr::from_hex(&raw.pubkey).map_err(|_| ParseEventError::InvalidPubkey)?;
let sig =
encoding::decode_lower_hex::<64>(&raw.sig).ok_or(ParseEventError::InvalidSignature)?;
if has_empty_tag(&raw.tags) {
return Err(ParseEventError::EmptyTag);
}
if !is_supported_text(&raw.tags, &raw.content) {
return Err(ParseEventError::UnsupportedCharacter);
}
let created_at = UnixTime::from_secs(raw.created_at);
let id = compute_id(&author, created_at, raw.kind, &raw.tags, &raw.content);
if id.as_bytes() != &claimed_id {
return Err(ParseEventError::IdMismatch);
}
if !crate::schnorr::verify(author.as_bytes(), id.as_bytes(), &sig) {
return Err(ParseEventError::BadSignature);
}
Ok(Self {
id,
author,
created_at,
kind: raw.kind,
tags: raw.tags,
content: raw.content,
sig,
})
}
fn to_raw(&self) -> RawEvent {
RawEvent {
id: self.id.to_hex(),
pubkey: self.author.to_hex(),
created_at: self.created_at.as_secs(),
kind: self.kind,
tags: self.tags.clone(),
content: self.content.clone(),
sig: hex::encode(self.sig),
}
}
}
impl fmt::Debug for SignedEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SignedEvent")
.field("id", &self.id)
.field("author", &self.author)
.field("created_at", &self.created_at)
.field("kind", &self.kind)
.field("tags", &self.tags)
.field("content", &self.content)
.field("sig", &hex::encode(self.sig))
.finish()
}
}
impl Serialize for SignedEvent {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.to_raw().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SignedEvent {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = deserialize_object(deserializer)?;
Self::from_raw(raw).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseEventError {
#[error("malformed event json")]
MalformedJson,
#[error("event id is not 64 lowercase hex digits")]
InvalidId,
#[error("event pubkey is not a valid lowercase x-only public key")]
InvalidPubkey,
#[error("event signature is not 128 lowercase hex digits")]
InvalidSignature,
#[error("event has an empty tag")]
EmptyTag,
#[error("event text contains an unsupported control character")]
UnsupportedCharacter,
#[error("event id does not match the event")]
IdMismatch,
#[error("event signature does not verify")]
BadSignature,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawEvent {
id: String,
pubkey: String,
created_at: u64,
kind: u16,
tags: Vec<Vec<String>>,
content: String,
sig: String,
}
fn deserialize_object<'de, D: Deserializer<'de>>(deserializer: D) -> Result<RawEvent, D::Error> {
deserializer.deserialize_map(ObjectOnly)
}
struct ObjectOnly;
impl<'de> Visitor<'de> for ObjectOnly {
type Value = RawEvent;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a nip-01 event object")
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<RawEvent, A::Error> {
RawEvent::deserialize(MapAccessDeserializer::new(map))
}
}
fn has_empty_tag(tags: &[Vec<String>]) -> bool {
tags.iter().any(Vec::is_empty)
}
fn is_supported_text(tags: &[Vec<String>], content: &str) -> bool {
std::iter::once(content)
.chain(tags.iter().flatten().map(String::as_str))
.all(|text| !text.chars().any(is_unsupported_char))
}
fn is_unsupported_char(c: char) -> bool {
c < '\u{20}' && !matches!(c, '\u{08}' | '\t' | '\n' | '\u{0c}' | '\r')
}
fn compute_id(
author: &DidNostr,
created_at: UnixTime,
kind: u16,
tags: &[Vec<String>],
content: &str,
) -> EventId {
let preimage = (
0u8,
author.to_hex(),
created_at.as_secs(),
kind,
tags,
content,
);
let bytes = serde_json::to_vec(&preimage)
.expect("serde_json cannot fail on strings, integers and string arrays");
EventId::from_bytes(Sha256::digest(&bytes).into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn named_escapes_match_nip01() {
let encoded = serde_json::to_string("\"\\\n\r\t\u{08}\u{0c}").expect("serialises");
assert_eq!(encoded, r#""\"\\\n\r\t\b\f""#, "serde_json named escapes");
}
#[test]
fn other_text_is_written_verbatim() {
let text = "é \u{7f} \u{2028} / <>";
let encoded = serde_json::to_string(text).expect("serialises");
assert_eq!(encoded, format!("\"{text}\""), "no escaping beyond NIP-01");
}
#[test]
fn unsupported_characters_are_exactly_the_unnamed_controls() {
let unsupported: Vec<u32> = (0u32..0x80)
.filter_map(char::from_u32)
.filter(|c| is_unsupported_char(*c))
.map(u32::from)
.collect();
let want: Vec<u32> = (0u32..0x20)
.filter(|c| ![0x08, 0x09, 0x0a, 0x0c, 0x0d].contains(c))
.collect();
assert_eq!(unsupported, want, "unsupported set");
}
}