1use crate::admin::StoreChange;
4use crate::error::{bound, exact_length, require, Error, Rule};
5use crate::sealed;
6use crate::sealed_key::{CopyBox, KeyCopyPrefix};
7use crate::sequence::{SlotFrame, MAX_BOUNDED_SLOT};
8use crate::wire::{Decoder, Encoder, Wire};
9use coven_crypto::{
10 CircleKey, Signature, StoreKey, KEY_BOX_HEAD_LEN, KEY_BOX_TAG_LEN,
11 SEALED_OBJECT_CHUNK_OVERHEAD, SIGNATURE_LEN,
12};
13use coven_foundation::id_source::KeyId;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum BoxPlace {
19 KeyCopy,
21 Admission(u32),
23 Own,
27}
28
29#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum SlotKind {
33 Admin,
35 Writes,
37 KeyCopy(CopyBox),
39 Announcement,
41 Admission {
46 copies: Vec<CopyBox>,
48 own: Option<CopyBox>,
51 },
52}
53impl SlotKind {
54 pub fn tag(&self) -> u8 {
56 match self {
57 Self::Admin => 0,
58 Self::Writes => 1,
59 Self::KeyCopy(_) => 2,
60 Self::Announcement => 3,
61 Self::Admission { .. } => 4,
62 }
63 }
64 pub fn boxes(&self) -> impl Iterator<Item = (BoxPlace, &CopyBox)> {
66 let (single, many) = match self {
67 Self::KeyCopy(copy) => (Some(copy), &[][..]),
68 Self::Admission { copies, .. } => (None, &copies[..]),
69 Self::Admin | Self::Writes | Self::Announcement => (None, &[][..]),
70 };
71 let own = match self {
72 Self::Admission { own: Some(own), .. } => Some((BoxPlace::Own, own)),
73 _ => None,
74 };
75 single
76 .map(|copy| (BoxPlace::KeyCopy, copy))
77 .into_iter()
78 .chain(
79 many.iter()
80 .enumerate()
81 .map(|(index, copy)| (BoxPlace::Admission(index as u32), copy)),
82 )
83 .chain(own)
84 }
85 pub fn check_frame(&self, frame: &SlotFrame) -> Result<(), Error> {
89 let admits = matches!(
90 frame,
91 SlotFrame::Admin(
92 StoreChange::AdmitMember { .. }
93 | StoreChange::RecoverMember { .. }
94 | StoreChange::CreateStore { .. }
95 )
96 );
97 require(
98 match (self, frame) {
99 (Self::Admin, SlotFrame::Admin(_)) => !admits,
100 (Self::Admission { .. }, SlotFrame::Admin(_)) => admits,
101 (Self::KeyCopy(_), SlotFrame::KeyCopy)
102 | (Self::Announcement, SlotFrame::Announcement(_)) => true,
103 _ => false,
104 },
105 "slot kind",
106 Rule::Kind,
107 )
108 }
109}
110
111fn check_copies(copies: &[CopyBox], own: Option<&CopyBox>) -> Result<(), Error> {
115 require(!copies.is_empty(), "admission copies", Rule::Required)?;
116 let first = &copies[0];
117 require(
118 copies.iter().chain(own).all(|copy| {
119 copy.routing.member == first.routing.member
120 && copy.routing.sealing == first.routing.sealing
121 }),
122 "admission copy recipient",
123 Rule::Recipient,
124 )?;
125 require(
126 own.is_none_or(|own| matches!(own.routing.audience, coven_merge::Audience::Circle(_))),
127 "admission own copy",
128 Rule::Audience,
129 )?;
130 require(
131 copies.windows(2).all(|pair| {
132 (&pair[0].routing.audience, pair[0].routing.key)
133 < (&pair[1].routing.audience, pair[1].routing.key)
134 }),
135 "admission copy order",
136 Rule::Order,
137 )
138}
139
140#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct SlotObjectPrefix {
143 pub format: crate::FormatVersion,
145 pub key: KeyId,
147 pub kind: SlotKind,
149}
150impl SlotObjectPrefix {
151 pub const MAX_LENGTH: usize = Self::FIXED_LEN
154 + KeyCopyPrefix::CIRCLE_LEN
155 + KEY_BOX_HEAD_LEN
156 + 4
157 + CircleKey::ENCODED_LEN
158 + KEY_BOX_TAG_LEN;
159 const FIXED_LEN: usize = 1 + 2 + 1 + 16 + 1;
161 pub fn encode(&self) -> Result<Vec<u8>, Error> {
163 let mut out = self.start()?;
164 match &self.kind {
165 SlotKind::KeyCopy(copy) => {
166 1u8.put(&mut out)?;
167 copy.put(&mut out)?;
168 }
169 SlotKind::Admission { copies, own } => {
170 check_copies(copies, own.as_ref())?;
171 copies.put(&mut out)?;
172 own.put(&mut out)?;
173 }
174 SlotKind::Admin | SlotKind::Writes | SlotKind::Announcement => 0u8.put(&mut out)?,
175 }
176 Ok(out.bytes)
177 }
178 fn start(&self) -> Result<Encoder, Error> {
179 let mut out = Encoder::new();
180 out.bytes(&self.format.prefix(crate::kinds::SEQUENCE_SLOT))?;
181 self.kind.tag().put(&mut out)?;
182 self.key.put(&mut out)?;
183 Ok(out)
184 }
185 pub fn copy_context(
189 format: crate::FormatVersion,
190 key: KeyId,
191 place: BoxPlace,
192 routing: &KeyCopyPrefix,
193 ) -> Result<Vec<u8>, Error> {
194 let mut out = Encoder::new();
195 out.bytes(&format.prefix(crate::kinds::SEQUENCE_SLOT))?;
196 match place {
197 BoxPlace::KeyCopy => {
198 2u8.put(&mut out)?;
199 key.put(&mut out)?;
200 1u8.put(&mut out)?;
201 }
202 BoxPlace::Admission(index) => {
203 4u8.put(&mut out)?;
204 key.put(&mut out)?;
205 index.put(&mut out)?;
206 }
207 BoxPlace::Own => return Err(Error::Invalid { field: "box place", rule: Rule::Kind }),
209 }
210 routing.put(&mut out)?;
211 Ok(out.bytes)
212 }
213 pub fn own_binding(
217 store: coven_foundation::id_source::StoreId,
218 routing: &KeyCopyPrefix,
219 ) -> Result<Vec<u8>, Error> {
220 let mut out = Encoder::new();
221 store.put(&mut out)?;
222 routing.put(&mut out)?;
223 Ok(out.bytes)
224 }
225 pub fn admission(bytes: &[u8]) -> Result<bool, Error> {
228 sealed::prefix(bytes, crate::kinds::SEQUENCE_SLOT)?;
229 Ok(*bytes.get(3).ok_or(Error::Truncated)? == 4)
230 }
231 pub fn length(bytes: &[u8]) -> Result<usize, Error> {
234 sealed::prefix(bytes, crate::kinds::SEQUENCE_SLOT)?;
235 let kind = *bytes.get(3).ok_or(Error::Truncated)?;
236 require(kind <= 4, "slot kind", Rule::Kind)?;
237 if kind == 4 {
238 let start = Self::FIXED_LEN - 1;
239 let count = bytes.get(start..start + 4).ok_or(Error::Truncated)?;
240 let count = u32::from_be_bytes(count.try_into().expect("four bytes")) as usize;
241 require(count > 0, "admission copies", Rule::Required)?;
242 bound(count, crate::wire::MAX_ITEMS, "admission copies")?;
243 let mut end = start + 4;
244 for _ in 0..count {
245 end = box_end(bytes, end)?;
246 }
247 return match *bytes.get(end).ok_or(Error::Truncated)? {
249 0 => Ok(end + 1),
250 1 => box_end(bytes, end + 1),
251 tag => Err(Error::UnknownTag { field: "own copy", tag }),
252 };
253 }
254 let copy = *bytes.get(Self::FIXED_LEN - 1).ok_or(Error::Truncated)?;
255 require(copy == u8::from(kind == 2), "slot copy routing", Rule::Kind)?;
256 if kind != 2 {
257 return Ok(Self::FIXED_LEN);
258 }
259 box_end(bytes, Self::FIXED_LEN)
260 }
261 pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
263 exact_length(bytes.len(), Self::length(bytes)?)?;
264 let mut input = Decoder::new(&bytes[4..])?;
265 let key = KeyId::get(&mut input)?;
266 let kind = match bytes[3] {
267 4 => {
268 let copies = Vec::<CopyBox>::get(&mut input)?;
269 let own = Option::<CopyBox>::get(&mut input)?;
270 check_copies(&copies, own.as_ref())?;
271 SlotKind::Admission { copies, own }
272 }
273 tag => {
274 let copy = Option::<CopyBox>::get(&mut input)?;
275 match tag {
276 0 => SlotKind::Admin,
277 1 => SlotKind::Writes,
278 2 => SlotKind::KeyCopy(copy.expect("copy tag checked")),
279 3 => SlotKind::Announcement,
280 _ => unreachable!("kind checked"),
281 }
282 }
283 };
284 input.finish()?;
285 Ok(Self { format: crate::FormatVersion::decode(bytes)?, key, kind })
286 }
287 pub fn fits(&self, plaintext: usize) -> Result<bool, Error> {
291 Ok(bound(
292 Self::bounded_size(self.encode()?.len(), plaintext + SEALED_OBJECT_CHUNK_OVERHEAD),
293 MAX_BOUNDED_SLOT,
294 "slot object",
295 )
296 .is_ok())
297 }
298 fn bounded_size(prefix: usize, chunk: usize) -> usize {
301 prefix + 4 + chunk + SIGNATURE_LEN
302 }
303 pub fn encode_chunk(&self, chunk: &[u8]) -> Result<Vec<u8>, Error> {
307 require(!matches!(self.kind, SlotKind::Writes), "bounded slot kind", Rule::Kind)?;
308 let mut bytes = self.encode()?;
309 let length =
310 chunk.len().checked_sub(SEALED_OBJECT_CHUNK_OVERHEAD).ok_or(Error::Truncated)?;
311 require(length >= 2 * crate::FRAME_PREFIX_LEN, "slot frames", Rule::Chunk)?;
312 bound(Self::bounded_size(bytes.len(), chunk.len()), MAX_BOUNDED_SLOT, "slot object")?;
313 bytes.extend_from_slice(&sealed::encode_chunk(chunk)?);
314 Ok(bytes)
315 }
316}
317
318fn box_end(bytes: &[u8], start: usize) -> Result<usize, Error> {
322 let (routing, ciphertext) = match *bytes.get(start).ok_or(Error::Truncated)? {
323 0 => (KeyCopyPrefix::STORE_LEN, StoreKey::ENCODED_LEN),
324 1 => (KeyCopyPrefix::CIRCLE_LEN, CircleKey::ENCODED_LEN),
325 tag => return Err(Error::UnknownTag { field: "audience", tag }),
326 };
327 let offset = start + routing + KEY_BOX_HEAD_LEN;
328 let declared = bytes.get(offset..offset + 4).ok_or(Error::Truncated)?;
329 require(
330 u32::from_be_bytes(declared.try_into().expect("four bytes")) as usize == ciphertext,
331 "key box ciphertext",
332 Rule::StreamLength,
333 )?;
334 Ok(offset + 4 + ciphertext + KEY_BOX_TAG_LEN)
335}
336
337#[derive(Debug)]
339pub struct BoundedSlot<'a> {
340 pub prefix: SlotObjectPrefix,
342 pub chunk: &'a [u8],
344 pub signature: Signature,
346}
347impl<'a> BoundedSlot<'a> {
348 pub fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
350 bound(bytes.len(), MAX_BOUNDED_SLOT, "slot object")?;
351 let prefix_length = SlotObjectPrefix::length(bytes)?;
352 let prefix = SlotObjectPrefix::decode(bytes.get(..prefix_length).ok_or(Error::Truncated)?)?;
353 require(!matches!(prefix.kind, SlotKind::Writes), "bounded slot kind", Rule::Kind)?;
354 let body = &bytes[prefix_length..];
355 let length = sealed::chunk_length(body, MAX_BOUNDED_SLOT)?;
356 let chunk = body.get(4..length).ok_or(Error::Truncated)?;
357 require(
358 chunk.len() >= SEALED_OBJECT_CHUNK_OVERHEAD + 2 * crate::FRAME_PREFIX_LEN,
359 "slot frames",
360 Rule::Chunk,
361 )?;
362 let signature = sealed::signature(body.get(length..).ok_or(Error::Truncated)?)?;
363 Ok(Self { prefix, chunk, signature })
364 }
365 pub fn encode(&self) -> Result<Vec<u8>, Error> {
367 let mut bytes = self.prefix.encode_chunk(self.chunk)?;
368 bytes.extend_from_slice(self.signature.as_bytes());
369 Ok(bytes)
370 }
371}
372
373#[cfg(test)]
374#[path = "sealed_slot_tests.rs"]
375mod tests;