zaun_community_protocol/signed/rotation/
link.rs1use serde::{Deserialize, Serialize};
4
5use super::RootRotation;
6use crate::crypto::{self, Context, SecretKey, SignError};
7use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
8use crate::keys::{KeyEncodingError, SIGNATURE_LEN, Signature};
9use crate::limits::MAX_CANONICAL_FIELD;
10use crate::signed::error::SignedError;
11use crate::signed::object::SignedObject;
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct SignedRootRotation {
19 #[serde(with = "crate::b64::bytes")]
21 pub bytes: Vec<u8>,
22 pub sig_old: Signature,
24 pub sig_new: Signature,
26}
27
28fn read_signature(r: &mut Reader<'_>, field: &'static str) -> Result<Signature, DecodeError> {
29 let bytes = r.bytes(SIGNATURE_LEN)?;
32 Signature::from_bytes(bytes).map_err(|e| match e {
33 KeyEncodingError::UnknownSuite(s) => DecodeError::UnknownSuite(s),
34 KeyEncodingError::Length(_) => DecodeError::Invalid(field),
35 })
36}
37
38impl Encode for SignedRootRotation {
39 fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
40 w.bytes(&self.bytes, MAX_CANONICAL_FIELD)?;
41 w.bytes(self.sig_old.as_bytes(), SIGNATURE_LEN)?;
42 w.bytes(self.sig_new.as_bytes(), SIGNATURE_LEN)
43 }
44}
45
46impl Decode for SignedRootRotation {
47 fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
48 Ok(Self {
49 bytes: r.bytes(MAX_CANONICAL_FIELD)?.to_vec(),
50 sig_old: read_signature(r, "sig_old")?,
51 sig_new: read_signature(r, "sig_new")?,
52 })
53 }
54}
55
56type SignFn = fn(&SecretKey, Context, &[u8]) -> Result<Signature, SignError>;
57
58impl SignedRootRotation {
59 pub fn sign(
65 rotation: &RootRotation,
66 old: &SecretKey,
67 new: &SecretKey,
68 ) -> Result<Self, SignedError> {
69 Self::sign_with(rotation, old, new, crypto::sign)
70 }
71
72 pub fn sign_deterministic(
77 rotation: &RootRotation,
78 old: &SecretKey,
79 new: &SecretKey,
80 ) -> Result<Self, SignedError> {
81 Self::sign_with(rotation, old, new, crypto::sign_deterministic)
82 }
83
84 fn sign_with(
85 rotation: &RootRotation,
86 old: &SecretKey,
87 new: &SecretKey,
88 sign: SignFn,
89 ) -> Result<Self, SignedError> {
90 let bytes = rotation.to_bytes()?;
91 let ctx = RootRotation::CONTEXT;
92 Ok(Self {
93 sig_old: sign(old, ctx, &bytes)?,
94 sig_new: sign(new, ctx, &bytes)?,
95 bytes,
96 })
97 }
98}