weirdnet_update/
envelope.rs1use crate::keys::{PublicKey, Signature, SigningKey};
9use crate::{Error, Hash32, Result, cbor};
10use serde::{Deserialize, Serialize, de::DeserializeOwned};
11use std::collections::BTreeSet;
12use std::fmt;
13
14pub const MAX_ENVELOPE_BYTES: usize = 1024 * 1024;
16pub const MAX_SIGNATURES: usize = 64;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
21#[serde(rename_all = "kebab-case")]
22pub enum Domain {
23 Root,
25 Manifest,
27 Freshness,
29 Announcement,
31}
32
33impl Domain {
34 pub fn context(self) -> &'static str {
36 match self {
37 Self::Root => "weirdnet-update/v1/root",
38 Self::Manifest => "weirdnet-update/v1/manifest",
39 Self::Freshness => "weirdnet-update/v1/freshness",
40 Self::Announcement => "weirdnet-update/v1/announcement",
41 }
42 }
43}
44
45impl fmt::Display for Domain {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.write_str(match self {
48 Self::Root => "root",
49 Self::Manifest => "manifest",
50 Self::Freshness => "freshness",
51 Self::Announcement => "announcement",
52 })
53 }
54}
55
56#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
58pub struct SignatureEntry {
59 pub key: PublicKey,
61 pub sig: Signature,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Signed {
68 pub domain: Domain,
70 #[serde(with = "serde_bytes")]
72 pub payload: Vec<u8>,
73 pub signatures: Vec<SignatureEntry>,
75}
76
77fn message(domain: Domain, payload: &[u8]) -> Vec<u8> {
78 let ctx = domain.context().as_bytes();
79 let mut msg = Vec::with_capacity(ctx.len() + 1 + payload.len());
80 msg.extend_from_slice(ctx);
81 msg.push(0);
82 msg.extend_from_slice(payload);
83 msg
84}
85
86impl Signed {
87 pub fn sign<T: Serialize>(domain: Domain, value: &T, keys: &[&SigningKey]) -> Result<Self> {
90 let mut env = Self { domain, payload: cbor::to_vec(value)?, signatures: Vec::new() };
91 for key in keys {
92 env.add_signature(key);
93 }
94 Ok(env)
95 }
96
97 pub fn add_signature(&mut self, key: &SigningKey) {
99 let public = key.public();
100 let sig = key.sign_raw(&message(self.domain, &self.payload));
101 self.signatures.retain(|e| e.key != public);
102 self.signatures.push(SignatureEntry { key: public, sig });
103 }
104
105 pub fn verify_threshold(&self, domain: Domain, trusted: &[PublicKey], threshold: usize) -> Result<()> {
108 if self.domain != domain {
109 return Err(Error::WrongDomain { expected: domain, found: self.domain });
110 }
111 if threshold == 0 {
112 return Err(Error::invalid("threshold", "must be at least 1"));
113 }
114 if self.signatures.len() > MAX_SIGNATURES {
115 return Err(Error::invalid("envelope", format!("more than {MAX_SIGNATURES} signatures")));
116 }
117 let msg = message(domain, &self.payload);
118 let mut good = BTreeSet::new();
119 for entry in &self.signatures {
120 if trusted.contains(&entry.key) && !good.contains(&entry.key) && entry.key.verify(&msg, &entry.sig) {
121 good.insert(entry.key);
122 }
123 }
124 if good.len() < threshold {
125 return Err(Error::Threshold { domain, found: good.len(), needed: threshold });
126 }
127 Ok(())
128 }
129
130 pub fn decode<T: DeserializeOwned>(&self) -> Result<T> {
133 cbor::from_slice(&self.payload)
134 }
135
136 pub fn payload_hash(&self) -> Hash32 {
138 Hash32::of(&self.payload)
139 }
140
141 pub fn to_bytes(&self) -> Result<Vec<u8>> {
143 cbor::to_vec(self)
144 }
145
146 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
148 if bytes.len() > MAX_ENVELOPE_BYTES {
149 return Err(Error::Decode(format!("envelope larger than {MAX_ENVELOPE_BYTES} bytes")));
150 }
151 let env: Self = cbor::from_slice(bytes)?;
152 if env.signatures.len() > MAX_SIGNATURES {
153 return Err(Error::Decode(format!("more than {MAX_SIGNATURES} signatures")));
154 }
155 Ok(env)
156 }
157}