zaun_community_protocol/signed/
object.rs1use 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
9pub const FORMAT_V1: u8 = 0x01;
11
12pub trait SignedObject: Encode + Decode {
14 const CONTEXT: Context;
16
17 fn to_bytes(&self) -> Result<Vec<u8>, EncodeError> {
22 encoding::to_bytes(self)
23 }
24
25 fn decode_unverified(bytes: &[u8]) -> Result<Self, DecodeError> {
31 encoding::from_bytes(bytes)
32 }
33
34 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 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
63pub(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#[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 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 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 pub const fn object(&self) -> &T {
116 &self.object
117 }
118
119 pub fn into_object(self) -> T {
121 self.object
122 }
123
124 pub fn bytes(&self) -> &[u8] {
126 &self.bytes
127 }
128
129 pub const fn signature(&self) -> &Signature {
131 &self.sig
132 }
133
134 #[must_use]
136 pub fn hash(&self) -> [u8; 32] {
137 crypto::content_hash(&self.bytes)
138 }
139
140 #[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}