p2panda_core/traits.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0tra
2
3//! Traits expressing core features of peer-to-peer data types.
4use std::fmt::Debug;
5use std::hash::Hash as StdHash;
6
7use serde::{Deserialize, Serialize};
8
9use crate::logs::SeqNum;
10use crate::operation::{Body, PayloadSize};
11
12/// Identifier of an operation author.
13pub trait Author:
14 Copy + Clone + Debug + PartialEq + Eq + Ord + StdHash + Serialize + for<'de> Deserialize<'de>
15{
16}
17
18/// Identifier of a single operation.
19pub trait OperationId: Copy + Clone + Debug + PartialEq + Eq + Ord + StdHash {}
20
21#[cfg(any(test, feature = "test_utils"))]
22impl OperationId for u32 {}
23#[cfg(any(test, feature = "test_utils"))]
24impl OperationId for &str {}
25
26/// Returns (unique) hash digest, which can be used as identifier of this published data type.
27pub trait Digest<ID>
28where
29 ID: OperationId,
30{
31 /// Hash digest of peer-to-peer data-type which can be used as the identifier.
32 fn hash(&self) -> ID;
33}
34
35/// Returns the author of this published data type and a method to verify the authenticity of it.
36pub trait Provenance<A>
37where
38 A: Author,
39{
40 /// Identity of the author of data-type.
41 fn author(&self) -> A;
42
43 /// Checks if data-type and given author is authentic.
44 fn verify(&self) -> bool;
45}
46
47/// Hash-chain structure with integrity guarantees and sequence numbers as a performance
48/// optimization.
49pub trait Chain<ID> {
50 /// Pointer at previous entry in log which gives us the integrity guarantee of the "hash chain".
51 /// The first entry in a log returns `None`.
52 fn backlink(&self) -> Option<ID>;
53
54 /// Sequence numbers are helpful to fastly detect forks and use the much faster and optimized
55 /// diffing strategy when the local log is not forked.
56 fn seq_num(&self) -> SeqNum;
57}
58
59/// Additional data which can be removed from the on-chain data-type.
60pub trait Offchain<ID> {
61 /// Authenticated payload.
62 ///
63 /// Can be requested or removed independently from the peer-to-peer data-type (off-chain). Don't
64 /// expect this to always be available.
65 fn payload(&self) -> Option<&Body>;
66
67 /// Hash digest of the payload.
68 fn payload_hash(&self) -> Option<ID>;
69
70 /// Size in bytes of the payload.
71 fn payload_size(&self) -> PayloadSize;
72}
73
74/// Custom header extensions type.
75///
76/// User-defined extensions can be added to an operation's [`Header`](crate::Header) in order to
77/// extend the basic functionality of the core p2panda data types or to encode application-specific
78/// fields which should not be contained in the [`Body`].
79///
80/// This might be system-specific information relating to capabilities or key-agreement schemes
81/// which is required to enforce access-control restrictions during sync. Alternatively, extensions
82/// might be used to set expiration timestamps and deletion flags in order to facilitate garbage
83/// collection of stale data from the network. The core p2panda data types intentionally don't
84/// enforce a single approach to such areas where there are rightly many different approaches, with
85/// the most suitable being dependent on specific use-case requirements.
86///
87/// Interfaces which use p2panda core data types can require certain extensions to be present on any
88/// headers that their APIs accept using trait bounds. `p2panda-stream`, for example, uses the
89/// [`PruneFlag`](crate::PruneFlag) in order to implement automatic network-wide garbage collection.
90///
91/// Extensions are encoded on a header and sent over the wire. We need to satisfy all trait
92/// requirements that `Header` requires, including `Serialize` and `Deserialize`.
93///
94/// ## Example
95///
96/// ```
97/// use p2panda_core::{Hash, Header, SigningKey};
98/// use serde::{Serialize, Deserialize};
99///
100/// #[derive(Clone, Debug, Serialize, Deserialize)]
101/// struct LogId(Hash);
102///
103/// #[derive(Clone, Debug, Serialize, Deserialize)]
104/// struct CustomExtensions {
105/// log_id: Option<LogId>,
106/// expires: u64,
107/// }
108///
109/// let extensions = CustomExtensions {
110/// log_id: None,
111/// expires: 1787246796,
112/// };
113///
114/// let signing_key = SigningKey::generate();
115///
116/// let header = Header::builder()
117/// .body("Hello, Sloth".as_bytes())
118/// .build(&signing_key, extensions.clone());
119///
120/// assert_eq!(header.extensions.expires, 1787246796);
121/// ```
122pub trait Extensions: Clone + Debug + for<'de> Deserialize<'de> + Serialize {}
123
124impl<T> Extensions for T where T: Clone + Debug + for<'de> Deserialize<'de> + Serialize {}