pub mod content;
pub mod content_kind;
use std::collections::BTreeSet;
use std::{fmt, str};
pub use content::*;
pub use content_kind::*;
#[cfg(feature = "ed25519-dalek")]
mod ed25519;
#[cfg(feature = "serde")]
mod serde;
#[cfg(feature = "bincode")]
mod bincode;
#[cfg(all(feature = "ed25519-dalek", feature = "bincode"))]
mod verified_event;
#[cfg(all(feature = "ed25519-dalek", feature = "bincode"))]
pub use verified_event::*;
use crate::id::RostraId;
use crate::{
ContentHash, MsgLen, NullableShortEventId, ShortEventId, Timestamp, TimestampFixed,
array_type_define, array_type_impl_base64_str, array_type_impl_serde,
array_type_impl_zero_default,
};
const PERSONA_TAG_MAX_LEN: usize = 32;
pub trait EventExt {
fn event(&self) -> &Event;
fn author(&self) -> RostraId {
self.event().author
}
fn flags(&self) -> u8 {
self.event().flags
}
fn aux_key(&self) -> EventAuxKey {
self.event().key_aux
}
fn kind(&self) -> EventKind {
self.event().kind
}
fn timestamp(&self) -> Timestamp {
self.event().timestamp.into()
}
fn content_hash(&self) -> ContentHash {
self.event().content_hash
}
fn parent_prev(&self) -> Option<ShortEventId> {
self.event().parent_prev.into()
}
fn parent_aux(&self) -> Option<ShortEventId> {
self.event().parent_aux.into()
}
fn all_parents(&self) -> BTreeSet<ShortEventId> {
[self.parent_prev(), self.parent_aux()]
.into_iter()
.flatten()
.collect()
}
fn content_len(&self) -> u32 {
self.event().content_len.into()
}
fn is_delete_parent_aux_content_set(&self) -> bool {
self.event().is_delete_parent_aux_content_set()
}
fn is_singleton(&self) -> bool {
self.event().is_singleton()
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Event {
pub version: u8,
pub flags: u8,
pub kind: EventKind,
pub content_len: MsgLen,
pub timestamp: TimestampFixed,
pub key_aux: EventAuxKey,
pub author: RostraId,
pub parent_prev: NullableShortEventId,
pub parent_aux: NullableShortEventId,
pub content_hash: ContentHash,
}
impl Event {
pub const DELETE_PARENT_AUX_CONTENT_FLAG: u8 = 1;
pub const SINGLETON_FLAG: u8 = 2;
pub fn is_delete_parent_aux_content_set(&self) -> bool {
self.flags & Self::DELETE_PARENT_AUX_CONTENT_FLAG != 0
}
pub fn is_singleton(&self) -> bool {
self.flags & Self::SINGLETON_FLAG != 0
}
}
impl EventExt for Event {
fn event(&self) -> &Event {
self
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
pub struct PersonaId(pub u8);
impl PersonaId {
pub const MIN: Self = Self(0);
pub const MAX: Self = Self(u8::MAX);
}
impl fmt::Display for PersonaId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl str::FromStr for PersonaId {
type Err = <u8 as str::FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(PersonaId(u8::from_str(s)?))
}
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PersonaTag(String);
impl PersonaTag {
pub fn defaults() -> BTreeSet<Self> {
BTreeSet::from([Self::personal(), Self::professional(), Self::civic()])
}
pub fn personal() -> Self {
Self("personal".into())
}
pub fn professional() -> Self {
Self("professional".into())
}
pub fn civic() -> Self {
Self("civic".into())
}
pub fn from_persona_id(id: PersonaId) -> Option<Self> {
match id.0 {
0 => Some(Self::personal()),
1 => Some(Self::professional()),
2 => Some(Self::civic()),
_ => None,
}
}
pub fn new(s: impl Into<String>) -> Result<Self, PersonaTagError> {
let s = s.into().to_lowercase();
if s.is_empty() {
return Err(PersonaTagError::Empty);
}
if PERSONA_TAG_MAX_LEN < s.len() {
return Err(PersonaTagError::TooLong);
}
Ok(Self(s))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone)]
pub enum PersonaTagError {
Empty,
TooLong,
}
impl fmt::Display for PersonaTagError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PersonaTagError::Empty => write!(f, "Persona tag cannot be empty"),
PersonaTagError::TooLong => write!(
f,
"Persona tag too long (max {PERSONA_TAG_MAX_LEN} characters)"
),
}
}
}
impl std::error::Error for PersonaTagError {}
impl fmt::Display for PersonaTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl str::FromStr for PersonaTag {
type Err = PersonaTagError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
pub trait SignedEventExt: EventExt {
fn sig(&self) -> EventSignature;
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SignedEvent {
pub event: Event,
pub sig: EventSignature,
}
impl SignedEvent {
pub fn unverified(event: Event, sig: EventSignature) -> Self {
Self { event, sig }
}
pub fn sig(&self) -> EventSignature {
self.sig
}
}
impl EventExt for SignedEvent {
fn event(&self) -> &Event {
&self.event
}
}
impl SignedEventExt for SignedEvent {
fn sig(&self) -> EventSignature {
self.sig
}
}
#[cfg(all(feature = "ed25519-dalek", feature = "bincode"))]
impl From<VerifiedEvent> for SignedEvent {
fn from(event: VerifiedEvent) -> Self {
Self {
event: event.event,
sig: event.sig,
}
}
}
array_type_define!(
#[derive(PartialEq, Eq)]
struct EventSignature,
64
);
impl fmt::Display for EventSignature {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
data_encoding::BASE64URL_NOPAD.encode_write(&self.0, f)
}
}
array_type_define!(
#[derive(PartialEq, Eq)]
struct EventAuxKey,
16
);
array_type_impl_serde!(struct EventAuxKey, 16);
array_type_impl_base64_str!(EventAuxKey);
array_type_impl_zero_default!(EventAuxKey, 16);
#[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct EventKind([u8; 2]);
impl EventKind {
pub const NULL: Self = EventKind::from_u16(0);
pub const RAW: Self = EventKind::from_u16(1);
pub const FOLLOW: Self = EventKind::from_u16(0x10);
pub const UNFOLLOW: Self = EventKind::from_u16(0x11);
pub const NODE_ANNOUNCEMENT: Self = EventKind::from_u16(0x13);
pub const SOCIAL_POST: Self = EventKind::from_u16(0x20);
pub const SOCIAL_VOTE: Self = EventKind::from_u16(0x21);
pub const SOCIAL_PROFILE_UPDATE: Self = EventKind::from_u16(0x24);
pub const SOCIAL_MEDIA: Self = EventKind::from_u16(0x25);
pub const SHOUTBOX: Self = EventKind::from_u16(0x30);
pub const fn from_u16(value: u16) -> Self {
Self(value.to_be_bytes())
}
pub const fn as_u16(self) -> u16 {
u16::from_be_bytes(self.0)
}
}
impl fmt::Display for EventKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match *self {
Self::NULL => "null",
Self::RAW => "raw",
Self::FOLLOW => "follow",
Self::UNFOLLOW => "unfollow",
Self::NODE_ANNOUNCEMENT => "node-announcement",
Self::SOCIAL_POST => "social-post",
Self::SOCIAL_VOTE => "social-vote",
Self::SOCIAL_PROFILE_UPDATE => "social-profile-update",
Self::SOCIAL_MEDIA => "social-media",
Self::SHOUTBOX => "shoutbox",
v => {
f.write_fmt(format_args!("{}", v.as_u16()))?;
return Ok(());
}
};
f.write_str(s)
}
}
impl From<u16> for EventKind {
fn from(value: u16) -> Self {
Self(value.to_be_bytes())
}
}
impl From<EventKind> for u16 {
fn from(value: EventKind) -> Self {
u16::from_be_bytes(value.0)
}
}