rostra-core 0.1.3

Signed event graph types for the Rostra protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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,
};

/// Max length for a persona tag string
const PERSONA_TAG_MAX_LEN: usize = 32;

/// Convenience extension trait to unify getting event data from all versions
/// of [`Event`].
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()
    }

    /// Return all unique parent event IDs (prev and aux, deduplicated).
    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()
    }
}

/// An event (header), as encoded on the wire
///
/// The smallest building block of Rostra's data model.
///
/// Events chain up to two previous events, forming
/// a DAG that can be traversed from the present to the past.
///
/// Intentionally crafted to be a small and fixed:
///
/// * version + flags + kind = 1 + 1 + 2 = 4
/// * content_len = 4
/// * timestamp = 8
/// * padding = 16
/// * author = 32
/// * parent * 2 = 16 * 2 = 32
/// * content_hash = 32
///
/// * signature = 64
#[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 {
    /// Simple version counter to allow upgrades of [`Event`] format in the
    /// future.
    ///
    /// For now should always be `0`. Any newer version should be rejected.
    pub version: u8,

    /// Bit flags
    ///
    /// Bit `0` - delete previous event - All well-behaved nodes
    /// should consider the **content** of the author's event from `parent_aux`
    /// deleted, and delete it from their storage, recording the id of
    /// this event (one that deleted it) instead. The p2p and other
    /// protocols should accommodate such missing events as a core
    /// feature of the protocol and no longer store or return content data.
    /// Deleting the content of an event does not disable that event's header or
    /// its own graph-level effects.
    ///
    /// Bit `1` - singleton - only the event with the maximum
    /// `(event.timestamp, ShortEventId)` for a given `(kind, key)` matters, and
    /// previous ones can be considered deleted.
    ///
    /// All other bits MUST be 0 when producing headers, but might
    /// gain meaning in the future, so should still be accepted and
    /// ignored by client that don't understand them.
    pub flags: u8,

    /// The meaning and interpretation of the content from `content_hash`.
    ///
    /// This allows clients to filter events without inspecting their content.
    pub kind: EventKind,

    /// Content length
    ///
    /// Committing to it here, allows clients with storage requirements
    /// to skip data simply too large to bother with.
    ///
    /// Must be valid. Clients will simply reject content that doesn't
    /// match **both** `content_hash` and `content_len`.
    pub content_len: MsgLen,

    /// Timestamp of the message, in a fixed-sized encoding.
    pub timestamp: TimestampFixed,

    /// Key for the `singleton` flag
    ///
    /// Arbitrary bytes that can be used to index the event automatically,
    /// event without inspecting the content.
    pub key_aux: EventAuxKey,

    /// Public id of the creator of the message
    pub author: RostraId,

    /// Previous [`crate::EventId`], to form a kind-of-a-chain (actually DAG).
    ///
    /// It is supposed to be the *latest* `EventID` known to the client
    /// to allow traversing events (almost) in order.
    ///
    /// The ID is relative to this event's `author` and can only identify
    /// another event by that author.
    ///
    /// `EventID::ZERO` means "None" which means that there is
    /// no parent (first event ever), or the node that produced the event
    /// was not capable of knowing it. In such a case it is a job
    /// of the "active" node to connect it to the chain/DAG.
    pub parent_prev: NullableShortEventId,

    /// Auxiliary parent
    ///
    /// With some `flags` and `kind`s it can point at a past [`Event`]
    /// with special meaning or function, as
    /// opposed to the `parent_event` which is always about exact ordering.
    ///
    /// The ID is relative to this event's `author` and can only identify
    /// another event by that author.
    ///
    /// In all cases used to potentially merge divergent chains
    /// into one DAG. Also, by pointing at some much older `EventId`
    /// it allows fetching older events without traversing
    /// the DAG/chain one by one, potentially suffering latency
    /// of getting the data serially.
    ///
    /// Well behaved clients should try to make it point somewhat
    /// older event, to help it act as a skiplist. A random event
    /// should be easy to implement and recommended.
    ///
    /// `EventID::ZERO` means "None", and is valid, e.g. in
    /// cases where the client does not maintain any history and
    /// relies on forwarding signed events to "active" node.
    ///
    /// It is also OK if `parent_aux == parent_prev`.
    pub parent_aux: NullableShortEventId,

    /// Blake3 hash of the content
    ///
    /// [`EventContentRaw`] stores the actual content bytes. The bytes are
    /// interpreted according to [`EventKind`] and are stored and transmitted
    /// outside of the [`Event`] itself to decouple them.
    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)?))
    }
}

/// A persona tag — a short lowercase string used to categorize posts.
///
/// Tags replace the old numeric `PersonaId` system. Posts can have multiple
/// tags, and followers can filter by tags.
#[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 {
    /// The three default persona tags, corresponding to the legacy
    /// `PersonaId(0)`, `PersonaId(1)`, `PersonaId(2)`.
    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())
    }

    /// Convert a legacy `PersonaId` to a `PersonaTag`.
    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,
        }
    }

    /// Create a new persona tag, validating and lowercasing the input.
    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;
}

/// An [`Event`] along with a [`EventSignature`]
///
/// Notably: not verified yet be any means.
#[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 {
    /// No real content
    pub const NULL: Self = EventKind::from_u16(0);
    /// Unspecified binary data
    pub const RAW: Self = EventKind::from_u16(1);

    /// Control: Start following identity
    pub const FOLLOW: Self = EventKind::from_u16(0x10);
    /// Control: Stop following identity
    pub const UNFOLLOW: Self = EventKind::from_u16(0x11);
    // PERSONA_UPDATE (0x12) - not implemented yet
    /// Control: Node Announcement
    pub const NODE_ANNOUNCEMENT: Self = EventKind::from_u16(0x13);

    /// Social Post, backbone of the social network
    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);
    /// Shoutbox post - simple broadcast message
    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)
    }
}