Skip to main content

zaun_community_protocol/signed/
object.rs

1//! The signed-object contract and verified wrapper (specification §3.3, §3.6).
2
3use super::error::SignedError;
4use crate::crypto::{self, Context, SecretKey};
5use crate::encoding::{self, Decode, DecodeError, Encode, EncodeError};
6use crate::json::SignedJson;
7use crate::keys::{PublicKey, Signature};
8
9/// The `format` byte of every v1 signed object.
10pub const FORMAT_V1: u8 = 0x01;
11
12/// A signed object type: its canonical encoding (format byte first) and its context.
13pub trait SignedObject: Encode + Decode {
14    /// The context the verifier supplies for this type (§3.5).
15    const CONTEXT: Context;
16
17    /// The canonical bytes `B`.
18    ///
19    /// # Errors
20    /// [`EncodeError`] when a field breaks its rule.
21    fn to_bytes(&self) -> Result<Vec<u8>, EncodeError> {
22        encoding::to_bytes(self)
23    }
24
25    /// Decodes canonical bytes **without verifying** them. Receivers use
26    /// [`Signed::verify_and_decode`].
27    ///
28    /// # Errors
29    /// [`DecodeError`] for non-canonical input or a broken field rule.
30    fn decode_unverified(bytes: &[u8]) -> Result<Self, DecodeError> {
31        encoding::from_bytes(bytes)
32    }
33
34    /// Encodes and signs (hedged).
35    ///
36    /// # Errors
37    /// [`SignedError`] when the object does not encode or signing fails.
38    fn sign(self, sk: &SecretKey) -> Result<Signed<Self>, SignedError> {
39        let bytes = self.to_bytes()?;
40        let sig = crypto::sign(sk, Self::CONTEXT, &bytes)?;
41        Ok(Signed {
42            object: self,
43            bytes,
44            sig,
45        })
46    }
47
48    /// Encodes and signs deterministically. **Golden test vectors only.**
49    ///
50    /// # Errors
51    /// [`SignedError`] when the object does not encode or signing fails.
52    fn sign_deterministic(self, sk: &SecretKey) -> Result<Signed<Self>, SignedError> {
53        let bytes = self.to_bytes()?;
54        let sig = crypto::sign_deterministic(sk, Self::CONTEXT, &bytes)?;
55        Ok(Signed {
56            object: self,
57            bytes,
58            sig,
59        })
60    }
61}
62
63/// Reads the `format` byte.
64pub(super) fn read_format(r: &mut encoding::Reader<'_>) -> Result<(), DecodeError> {
65    match r.u8()? {
66        FORMAT_V1 => Ok(()),
67        other => Err(DecodeError::UnknownFormat(other)),
68    }
69}
70
71/// A signed object whose signature has been made or verified, with its exact bytes.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Signed<T> {
74    object: T,
75    bytes: Vec<u8>,
76    sig: Signature,
77}
78
79impl<T: SignedObject> Signed<T> {
80    /// Verifies `sig` over `bytes` under `key` with `T`'s context, **then** decodes (§3.6).
81    ///
82    /// # Errors
83    /// [`SignedError::Signature`] before any decoding, or [`SignedError::Decode`].
84    pub fn verify_and_decode(
85        bytes: &[u8],
86        sig: &Signature,
87        key: &PublicKey,
88        min_suite: u8,
89    ) -> Result<Self, SignedError> {
90        crypto::verify(key, sig, T::CONTEXT, bytes, min_suite)?;
91        let object = T::decode_unverified(bytes)?;
92        Ok(Self {
93            object,
94            bytes: bytes.to_vec(),
95            sig: sig.clone(),
96        })
97    }
98
99    /// [`Self::verify_and_decode`] for the JSON form `{bytes, sig}`.
100    ///
101    /// # Errors
102    /// [`SignedError::SignatureEncoding`] for a malformed `sig`, else as `verify_and_decode`.
103    pub fn from_json(
104        json: &SignedJson,
105        key: &PublicKey,
106        min_suite: u8,
107    ) -> Result<Self, SignedError> {
108        let sig = Signature::from_bytes(&json.sig)?;
109        Self::verify_and_decode(&json.bytes, &sig, key, min_suite)
110    }
111}
112
113impl<T> Signed<T> {
114    /// The decoded object.
115    pub const fn object(&self) -> &T {
116        &self.object
117    }
118
119    /// The decoded object, consuming the wrapper.
120    pub fn into_object(self) -> T {
121        self.object
122    }
123
124    /// The canonical bytes `B`.
125    pub fn bytes(&self) -> &[u8] {
126        &self.bytes
127    }
128
129    /// The signature.
130    pub const fn signature(&self) -> &Signature {
131        &self.sig
132    }
133
134    /// `SHA3-256(B)`: the object's identity (never the signature, §3.2).
135    #[must_use]
136    pub fn hash(&self) -> [u8; 32] {
137        crypto::content_hash(&self.bytes)
138    }
139
140    /// The JSON form `{bytes, sig}` (§3.6).
141    #[must_use]
142    pub fn to_json(&self) -> SignedJson {
143        SignedJson {
144            bytes: self.bytes.clone(),
145            sig: self.sig.as_bytes().to_vec(),
146        }
147    }
148}
149
150impl<T> From<Signed<T>> for SignedJson {
151    fn from(signed: Signed<T>) -> Self {
152        Self {
153            bytes: signed.bytes,
154            sig: signed.sig.as_bytes().to_vec(),
155        }
156    }
157}