p2panda_rs/entry/
encoded_entry.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3use std::fmt::Display;
4use std::hash::Hash as StdHash;
5
6use bamboo_rs_core_ed25519_yasmf::ED25519_SIGNATURE_SIZE;
7use serde::{Deserialize, Serialize};
8
9use crate::entry::traits::AsEncodedEntry;
10use crate::hash::Hash;
11use crate::serde::{deserialize_hex, serialize_hex};
12
13/// Size of p2panda entries' signatures.
14pub const SIGNATURE_SIZE: usize = ED25519_SIGNATURE_SIZE;
15
16/// Wrapper type for Bamboo entry bytes.
17///
18/// This struct can be used to deserialize an hex-encoded string into bytes when using a
19/// human-readable encoding format. No validation is applied whatsoever, except of checking if it
20/// is a valid hex-string (#E1).
21///
22/// To validate these bytes use the `decode_entry` method to apply all checks and to get an `Entry`
23/// instance. Read the module-level documentation for more information.
24#[derive(Clone, Debug, PartialEq, Eq, StdHash, Serialize, Deserialize)]
25pub struct EncodedEntry(
26    #[serde(serialize_with = "serialize_hex", deserialize_with = "deserialize_hex")] Vec<u8>,
27);
28
29impl EncodedEntry {
30    /// Returns new `EncodedEntry` instance from given bytes.
31    ///
32    /// This does not apply any validation and should only be used in methods where all checks have
33    /// taken place before.
34    pub fn from_bytes(bytes: &[u8]) -> Self {
35        Self(bytes.to_owned())
36    }
37}
38
39impl AsEncodedEntry for EncodedEntry {
40    /// Generates and returns hash of encoded entry.
41    fn hash(&self) -> Hash {
42        Hash::new_from_bytes(&self.0)
43    }
44
45    /// Returns entry as bytes.
46    fn into_bytes(&self) -> Vec<u8> {
47        self.0.clone()
48    }
49
50    /// Returns payload size (number of bytes) of total encoded entry.
51    fn size(&self) -> u64 {
52        self.0.len() as u64
53    }
54}
55
56impl Display for EncodedEntry {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "{}", hex::encode(&self.0))
59    }
60}
61
62#[cfg(any(feature = "test-utils", test))]
63impl EncodedEntry {
64    /// Returns a new instance of `EncodedEntry` for testing.
65    pub fn new(bytes: &[u8]) -> EncodedEntry {
66        Self(bytes.to_owned())
67    }
68
69    /// Converts hexadecimal string into bytes and returns as a new instance of `EncodedEntry`.
70    pub fn from_hex(value: &str) -> EncodedEntry {
71        let bytes = hex::decode(value).expect("invalid hexadecimal value");
72        Self(bytes)
73    }
74}