Skip to main content

nibkeep_log/
payload.rs

1//! What a change holds: ordinary operations, sealed secret statements, and what it states
2//! again of the changes it purges.
3
4use std::collections::BTreeMap;
5
6use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value as Cbor};
7use nibkeep_base::{SpaceId, StatementId};
8use nibkeep_crypto::rand_core::CryptoRng;
9use nibkeep_crypto::{Envelope, Key};
10use nibkeep_model::{Operation, Statement};
11
12use crate::ChangeId;
13use crate::change::{read_by_statement, write_by_statement};
14use crate::keys::associated_data;
15
16/// The content of a change, which the change's header does not hold.
17///
18/// In CBOR, a payload is the array `[operations, sealed, restated]`, where `restated` is
19/// an array of `[change, operations, sealed]`, in ascending order of the changes' IDs.
20/// `docs/spec/log.md` describes the format.
21#[derive(Clone, Debug, Default, PartialEq, Eq)]
22pub struct Payload {
23	/// The operations that everyone with the space key can read.
24	pub operations: Vec<Operation>,
25	/// Secret statements, by ID, each encrypted with its record key. What they supersede
26	/// is retracted in `operations`, so that every replica applies it.
27	pub sealed: BTreeMap<StatementId, Envelope>,
28	/// What the change states again of earlier changes, by the change each came from: the
29	/// rest of the changes it purges.
30	pub restated: BTreeMap<ChangeId, Restated>,
31}
32
33/// What a purge states again of one earlier change: its operations and sealed statements
34/// but those purged, with their statement IDs. They count from the time of the change they
35/// came from, and show from the purge on.
36#[derive(Clone, Debug, Default, PartialEq, Eq)]
37pub struct Restated {
38	/// The operations.
39	pub operations: Vec<Operation>,
40	/// The secret statements, sealed as they were.
41	pub sealed: BTreeMap<StatementId, Envelope>,
42}
43
44impl Restated {
45	/// Whether it states nothing again.
46	#[must_use]
47	pub fn is_empty(&self) -> bool {
48		self.operations.is_empty() && self.sealed.is_empty()
49	}
50}
51
52impl Payload {
53	/// Every operation of the payload, its own and those it states again.
54	pub fn all_operations(&self) -> impl Iterator<Item = &Operation> {
55		self.operations.iter().chain(
56			self.restated
57				.values()
58				.flat_map(|restated| restated.operations.iter()),
59		)
60	}
61
62	/// Every statement the payload seals, its own and those it states again.
63	pub fn all_sealed(&self) -> impl Iterator<Item = (&StatementId, &Envelope)> {
64		self.sealed.iter().chain(
65			self.restated
66				.values()
67				.flat_map(|restated| restated.sealed.iter()),
68		)
69	}
70}
71
72impl From<Vec<Operation>> for Payload {
73	fn from(operations: Vec<Operation>) -> Self {
74		Self {
75			operations,
76			..Self::default()
77		}
78	}
79}
80
81/// Encrypts a secret statement with its record key.
82pub(crate) fn seal(
83	space: SpaceId,
84	statement: &Statement,
85	record_key: &Key,
86	rng: &mut impl CryptoRng,
87) -> Envelope {
88	Envelope::seal(
89		record_key,
90		&cbor::to_vec(statement),
91		&associated_data(space, &statement.id),
92		rng,
93	)
94}
95
96/// Decrypts a sealed statement with its record key. Returns `None` if it does not open,
97/// or is not the statement with this ID.
98pub(crate) fn open_sealed(
99	space: SpaceId,
100	id: StatementId,
101	envelope: &Envelope,
102	record_key: &Key,
103) -> Option<Statement> {
104	let plaintext = envelope
105		.open(record_key, &associated_data(space, &id))
106		.ok()?;
107	let statement: Statement = cbor::from_slice(&plaintext).ok()?;
108	(statement.id == id).then_some(statement)
109}
110
111impl ToCbor for Payload {
112	fn to_cbor(&self) -> Cbor {
113		Cbor::Array(vec![
114			Cbor::Array(self.operations.iter().map(ToCbor::to_cbor).collect()),
115			write_by_statement(&self.sealed),
116			Cbor::Array(
117				self.restated
118					.iter()
119					.map(|(change, restated)| {
120						Cbor::Array(vec![
121							change.to_cbor(),
122							Cbor::Array(restated.operations.iter().map(ToCbor::to_cbor).collect()),
123							write_by_statement(&restated.sealed),
124						])
125					})
126					.collect(),
127			),
128		])
129	}
130}
131
132impl FromCbor for Payload {
133	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
134		const EXPECTED: &str = "a payload: [operations, sealed, restated], with sealed statements and restated changes in ascending order of their IDs";
135		let error = || cbor::Error::Expected(EXPECTED);
136		let Cbor::Array(items) = value else {
137			return Err(error());
138		};
139		let [operations, sealed, restated] = items.as_slice() else {
140			return Err(error());
141		};
142		let Cbor::Array(restated) = restated else {
143			return Err(error());
144		};
145		let mut restated_by_change: BTreeMap<ChangeId, Restated> = BTreeMap::new();
146		for entry in restated {
147			let Cbor::Array(entry) = entry else {
148				return Err(error());
149			};
150			let [change, operations, sealed] = entry.as_slice() else {
151				return Err(error());
152			};
153			let change = ChangeId::from_cbor(change)?;
154			// Change IDs of one algorithm sort by their digests, as their bytes do.
155			if restated_by_change
156				.last_key_value()
157				.is_some_and(|(&last, _)| last >= change)
158			{
159				return Err(error());
160			}
161			restated_by_change.insert(
162				change,
163				Restated {
164					operations: Vec::from_cbor(operations)?,
165					sealed: read_by_statement(sealed, EXPECTED)?,
166				},
167			);
168		}
169		Ok(Self {
170			operations: Vec::from_cbor(operations)?,
171			sealed: read_by_statement(sealed, EXPECTED)?,
172			restated: restated_by_change,
173		})
174	}
175}