Skip to main content

coven_format/
floor.rs

1//! The floor's encrypted header and original announcement frames (D8).
2
3use crate::error::{require, Error, Rule};
4use crate::path::ObjectPath;
5use crate::sequence::MAX_BOUNDED_SLOT;
6use crate::value::Slot;
7use crate::wire::{
8    decode_frame, decode_frame_value, get_blob, put_blob, wire_struct, Decoder, Encoder, Wire,
9};
10use coven_foundation::id_source::{DeviceId, StoreId};
11use std::collections::BTreeSet;
12
13/// Exact original slot evidence, verified at its original slot path.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct OriginalSlot {
16    /// The original slot, even if retention has since deleted its path.
17    pub slot: Slot,
18    /// Complete original sealed bytes and signature.
19    pub object: Vec<u8>,
20}
21impl OriginalSlot {
22    /// Where the slot's object lived in `store`.
23    pub fn path(&self, store: StoreId) -> ObjectPath {
24        ObjectPath::slot(store, self.slot.into())
25    }
26}
27impl Wire for OriginalSlot {
28    fn put(&self, out: &mut Encoder) -> Result<(), Error> {
29        self.slot.put(out)?;
30        put_blob(&self.object, out)
31    }
32    fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
33        Ok(Self { slot: Wire::get(input)?, object: get_blob(input)? })
34    }
35}
36impl OriginalSlot {
37    /// Check that the clear slot kind is one of `kinds` and the bounded
38    /// envelope. Authentication and the encrypted header's path binding are
39    /// checked when opening it.
40    pub fn validate_kind(&self, kinds: &[u8]) -> Result<(), Error> {
41        crate::error::bound(self.object.len(), MAX_BOUNDED_SLOT, "retained slot")?;
42        let object = crate::sealed_slot::BoundedSlot::decode(&self.object)?;
43        require(kinds.contains(&object.prefix.kind.tag()), "retained slot kind", Rule::Kind)
44    }
45}
46
47/// Header of the signed floor stream. Announcements follow in this order.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct FloorHeader {
50    /// Device signing the floor in the state at `at`.
51    pub author: DeviceId,
52    /// Signer's applied slot, covering every named announcement.
53    pub at: u64,
54    /// First slot the sequence retains.
55    pub first: Slot,
56    /// One announcement per audience that holds a part or has a snapshot, in
57    /// audience order, store first.
58    pub snapshots: Vec<Slot>,
59}
60wire_struct!(FloorHeader, author, at, first, snapshots);
61impl FloorHeader {
62    fn validate(&self) -> Result<(), Error> {
63        require(!self.snapshots.is_empty(), "floor snapshots", Rule::Required)?;
64        require(
65            self.first.get() - 1 <= self.at
66                && self.snapshots.iter().all(|slot| slot.get() <= self.at),
67            "floor coverage",
68            Rule::Coverage,
69        )?;
70        let unique: BTreeSet<_> = self.snapshots.iter().collect();
71        require(unique.len() == self.snapshots.len(), "floor announcements", Rule::Order)
72    }
73    /// Encode the kind-12 header frame.
74    pub fn encode(&self) -> Result<Vec<u8>, Error> {
75        self.validate()?;
76        crate::encode_frame(crate::kinds::FLOOR_HEADER, self)
77    }
78    /// Decode exactly the kind-12 header frame.
79    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
80        let header: Self = decode_frame_value(bytes, crate::kinds::FLOOR_HEADER, "floor header")?;
81        header.validate()?;
82        Ok(header)
83    }
84}
85
86/// Incremental floor frame codec; no bound is imposed on the complete stream.
87pub struct FloorFrames {
88    header: FloorHeader,
89    next: usize,
90    ended: bool,
91}
92impl FloorFrames {
93    /// Begin encoding with the validated floor header.
94    pub fn start(header: FloorHeader) -> Result<(Self, Vec<u8>), Error> {
95        let frame = header.encode()?;
96        Ok((Self { header, next: 0, ended: false }, frame))
97    }
98    /// Start decoding from its initial header frame, checking the clear prefix.
99    pub fn decode_header(bytes: &[u8], first: Slot) -> Result<Self, Error> {
100        let header = FloorHeader::decode(bytes)?;
101        require(header.first == first, "floor first", Rule::Coverage)?;
102        Ok(Self { header, next: 0, ended: false })
103    }
104    /// Unauthenticated header; verify the floor before granting authority.
105    pub fn header(&self) -> &FloorHeader {
106        &self.header
107    }
108    fn accept(&mut self, slot: &OriginalSlot) -> Result<(), Error> {
109        slot.validate_kind(&[3])?;
110        require(
111            !self.ended && self.header.snapshots.get(self.next) == Some(&slot.slot),
112            "floor announcement order",
113            Rule::Order,
114        )?;
115        self.next += 1;
116        Ok(())
117    }
118    /// Encode the next original announcement, checking header order.
119    pub fn announcement(&mut self, slot: &OriginalSlot) -> Result<Vec<u8>, Error> {
120        let bytes = crate::encode_frame(crate::kinds::SNAPSHOT_RECORD, slot)?;
121        self.accept(slot)?;
122        Ok(bytes)
123    }
124    /// Encode the required end frame after all announcements.
125    pub fn end(&mut self) -> Result<Vec<u8>, Error> {
126        require(
127            !self.ended && self.next == self.header.snapshots.len(),
128            "floor end",
129            Rule::SnapshotSequence,
130        )?;
131        self.ended = true;
132        crate::encode_frame_with(crate::kinds::SNAPSHOT_END, |_| Ok(()))
133    }
134    /// Decode one announcement or the end marker, preserving exact evidence.
135    pub fn frame(&mut self, bytes: &[u8]) -> Result<Option<OriginalSlot>, Error> {
136        let (kind, mut input) = decode_frame(bytes)?;
137        if kind == crate::kinds::SNAPSHOT_END {
138            input.finish()?;
139            require(
140                !self.ended && self.next == self.header.snapshots.len(),
141                "floor end",
142                Rule::SnapshotSequence,
143            )?;
144            self.ended = true;
145            return Ok(None);
146        }
147        require(kind == crate::kinds::SNAPSHOT_RECORD, "floor announcement", Rule::Kind)?;
148        let slot = OriginalSlot::get(&mut input)?;
149        input.finish()?;
150        self.accept(&slot)?;
151        Ok(Some(slot))
152    }
153    /// Require the end marker before accepting the stream.
154    pub fn finish(&self) -> Result<(), Error> {
155        if self.ended {
156            Ok(())
157        } else {
158            Err(Error::Truncated)
159        }
160    }
161}
162
163#[cfg(test)]
164#[path = "floor_tests.rs"]
165mod tests;