Skip to main content

nibkeep_log/
change.rs

1//! Changes: the operations that one replica made at one time, signed by the replica, with
2//! their payload sealed under a key of the change's own.
3
4use std::collections::{BTreeMap, BTreeSet};
5
6pub use nibkeep_base::ChangeId;
7use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value as Cbor};
8use nibkeep_base::small::SmallSet;
9use nibkeep_base::{Hash, SpaceId, StatementId};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_crypto::{Envelope, Key, Signature, SigningKey, VerifyingKey, key_hash};
12use nibkeep_time::Timestamp;
13
14use crate::keys::{associated_data, change_keys_key};
15use crate::{LogError, Payload, SpaceKeys};
16
17/// The suite of the change format in version 1 of the specification.
18const SUITE: u8 = 1;
19
20/// The context of the signatures of changes.
21const SIGNATURE_CONTEXT: &str = "nibkeep change";
22
23/// What a change is for, which its header says, so that every replica can tell from
24/// headers alone which changes may be purged.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub enum Kind {
27	/// Any change that does not govern the space.
28	#[default]
29	Ordinary,
30	/// A change that sets who may write to the space: the keys of replicas, and later
31	/// members and roles. It holds nothing else, and is never purged.
32	Governing,
33}
34
35impl ToCbor for Kind {
36	fn to_cbor(&self) -> Cbor {
37		match self {
38			Self::Ordinary => 0u8.to_cbor(),
39			Self::Governing => 1u8.to_cbor(),
40		}
41	}
42}
43
44impl FromCbor for Kind {
45	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
46		match u8::from_cbor(value) {
47			Ok(0) => Ok(Self::Ordinary),
48			Ok(1) => Ok(Self::Governing),
49			_ => Err(cbor::Error::Expected("a kind of change: 0 or 1")),
50		}
51	}
52}
53
54/// What a change purges: changes, whose keys and payloads every replica destroys; secret
55/// statements, whose record keys it destroys; and blobs, by the sealed hashes of the blobs
56/// whose keys it destroys.
57///
58/// In CBOR, purges are the array `[changes, statements, blobs]`, each sorted by its bytes
59/// without duplicates.
60#[derive(Clone, Debug, Default, PartialEq, Eq)]
61pub struct Purges {
62	/// The changes whose keys and payloads the change destroys.
63	pub changes: BTreeSet<ChangeId>,
64	/// The secret statements whose record keys the change destroys.
65	pub statements: BTreeSet<StatementId>,
66	/// The sealed hashes of the blobs whose keys the change destroys.
67	pub blobs: BTreeSet<Hash>,
68}
69
70impl Purges {
71	/// Whether the change purges nothing.
72	#[must_use]
73	pub fn is_empty(&self) -> bool {
74		self.changes.is_empty() && self.statements.is_empty() && self.blobs.is_empty()
75	}
76}
77
78impl ToCbor for Purges {
79	fn to_cbor(&self) -> Cbor {
80		// Hashes of one algorithm, and so change IDs, sort by their digests, as their
81		// bytes do.
82		Cbor::Array(vec![
83			Cbor::Array(self.changes.iter().map(ToCbor::to_cbor).collect()),
84			Cbor::Array(self.statements.iter().map(ToCbor::to_cbor).collect()),
85			Cbor::Array(self.blobs.iter().map(ToCbor::to_cbor).collect()),
86		])
87	}
88}
89
90impl FromCbor for Purges {
91	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
92		const EXPECTED: &str =
93			"purges: [changes, statements, blobs], each in ascending order without duplicates";
94		let Cbor::Array(items) = value else {
95			return Err(cbor::Error::Expected(EXPECTED));
96		};
97		let [changes, statements, blobs] = items.as_slice() else {
98			return Err(cbor::Error::Expected(EXPECTED));
99		};
100		Ok(Self {
101			changes: ascending(changes, EXPECTED)?,
102			statements: ascending(statements, EXPECTED)?,
103			blobs: ascending(blobs, EXPECTED)?,
104		})
105	}
106}
107
108/// What a change restores, after purges destroyed it: the same three lists as [`Purges`],
109/// of changes whose payloads and keys come back, secret statements whose record keys come
110/// back, and blobs whose keys come back, from replicas that kept them
111/// ([technical design](../../../docs/Technical-design.md#911-copies-that-wait)).
112pub type Restores = Purges;
113
114/// Reads an array whose items are in ascending order, without duplicates.
115pub(crate) fn ascending<T: FromCbor + Ord>(
116	value: &Cbor,
117	expected: &'static str,
118) -> Result<BTreeSet<T>, cbor::Error> {
119	let items: Vec<T> = Vec::from_cbor(value)?;
120	if items.windows(2).any(|pair| pair[0] >= pair[1]) {
121		return Err(cbor::Error::Expected(expected));
122	}
123	Ok(items.into_iter().collect())
124}
125
126/// A change's payload, sealed with the change's key: what [`Payload`] holds, encrypted.
127/// The change's header holds its hash, so a sealed payload that does not belong to a
128/// change is known at once. It is stored and travels beside its change, so that purging
129/// can delete it while the change stays.
130///
131/// In CBOR, a sealed payload is an envelope.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct SealedPayload(Envelope);
134
135impl SealedPayload {
136	/// The hash of its encoding, which the header of its change holds.
137	#[must_use]
138	pub fn hash(&self) -> Hash {
139		Hash::of(&cbor::to_vec(self))
140	}
141
142	/// How many bytes it holds, about what it takes on disk.
143	#[must_use]
144	pub fn byte_len(&self) -> usize {
145		self.0.byte_len()
146	}
147}
148
149impl ToCbor for SealedPayload {
150	fn to_cbor(&self) -> Cbor {
151		self.0.to_cbor()
152	}
153}
154
155impl FromCbor for SealedPayload {
156	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
157		Envelope::from_cbor(value).map(Self)
158	}
159}
160
161/// A change's key, wrapped with a key derived from the space key of the change's epoch,
162/// and tied to the change's ID. It is stored and travels beside its change, so that
163/// purging can delete it while the change stays.
164///
165/// In CBOR, a wrapped change key is an envelope.
166#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct WrappedChangeKey(Envelope);
168
169impl WrappedChangeKey {
170	/// Wraps the key of a change with the space key of its epoch.
171	fn wrap(
172		space: SpaceId,
173		change: ChangeId,
174		change_key: &Key,
175		space_key: &Key,
176		rng: &mut impl CryptoRng,
177	) -> Self {
178		Self(Envelope::seal_key(
179			&change_keys_key(space_key),
180			change_key,
181			&associated_data(space, &change),
182			rng,
183		))
184	}
185
186	/// Unwraps the key of `change`, if `keys` hold the space key of its epoch and the key
187	/// is the one whose hash the change's header holds.
188	pub(crate) fn unwrap(&self, change: &Change, keys: &SpaceKeys) -> Option<Key> {
189		let space_key = keys.get(change.epoch())?;
190		let key = self
191			.0
192			.open_key(
193				&change_keys_key(space_key),
194				&associated_data(change.space(), &change.id()),
195			)
196			.ok()?;
197		(key_hash(&key) == change.header.key_hash).then_some(key)
198	}
199}
200
201impl ToCbor for WrappedChangeKey {
202	fn to_cbor(&self) -> Cbor {
203		self.0.to_cbor()
204	}
205}
206
207impl FromCbor for WrappedChangeKey {
208	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
209		Envelope::from_cbor(value).map(Self)
210	}
211}
212
213/// A change with its sealed payload and wrapped key, as far as a replica has them: the
214/// three travel together, but may arrive apart, and the payload and key are deleted when
215/// the change is purged.
216#[derive(Clone, Debug, PartialEq, Eq)]
217pub struct Parcel {
218	/// The change.
219	pub change: Change,
220	/// Its sealed payload.
221	pub payload: Option<SealedPayload>,
222	/// Its wrapped key: one, or a few on a replica that cannot tell yet which is good.
223	pub keys: Vec<WrappedChangeKey>,
224}
225
226impl Parcel {
227	/// The change's ID.
228	#[must_use]
229	pub const fn id(&self) -> ChangeId {
230		self.change.id()
231	}
232}
233
234/// What a new change is to hold, besides who makes it and with which key.
235#[derive(Clone, Debug)]
236pub struct Draft {
237	/// The heads of the author's log.
238	pub parents: BTreeSet<ChangeId>,
239	/// The change's system time.
240	pub timestamp: Timestamp,
241	/// What the change is for.
242	pub kind: Kind,
243	/// What the change purges.
244	pub purges: Purges,
245	/// What the change restores, of what purges destroyed.
246	pub restores: Restores,
247	/// The hashes of the record keys of the statements sealed in the payload, by ID.
248	pub record_keys: BTreeMap<StatementId, Hash>,
249	/// The payload.
250	pub payload: Payload,
251}
252
253impl Draft {
254	/// An ordinary change that holds `payload` and purges nothing.
255	#[must_use]
256	pub fn new(
257		parents: impl IntoIterator<Item = ChangeId>,
258		timestamp: Timestamp,
259		payload: Payload,
260	) -> Self {
261		Self {
262			parents: parents.into_iter().collect(),
263			timestamp,
264			kind: Kind::Ordinary,
265			purges: Purges::default(),
266			restores: Restores::default(),
267			record_keys: BTreeMap::new(),
268			payload,
269		}
270	}
271}
272
273/// The operations that one replica made at one time, signed by the replica. The payload
274/// that holds them is sealed with a key of the change's own, and kept beside the change,
275/// whose header holds the hashes of both.
276///
277/// In CBOR, a change is the array `[1, header, signature]`. `docs/spec/log.md` describes
278/// the format.
279#[derive(Clone, Debug, PartialEq, Eq)]
280pub struct Change {
281	header: Header,
282	signature: Signature,
283	id: ChangeId,
284}
285
286#[derive(Clone, Debug, PartialEq, Eq)]
287struct Header {
288	space: SpaceId,
289	epoch: u64,
290	author: VerifyingKey,
291	/// Nearly always one or two: a small set.
292	parents: SmallSet<ChangeId>,
293	timestamp: Timestamp,
294	kind: Kind,
295	payload_hash: Hash,
296	key_hash: Hash,
297	/// The hashes of the record keys of the statements sealed in the payload, by ID.
298	sealed: BTreeMap<StatementId, Hash>,
299	purges: Purges,
300	/// What it restores: in CBOR, an item after `purges` only if it restores anything.
301	restores: Restores,
302}
303
304impl Change {
305	/// Makes a change: seals the draft's payload with a new change key, wraps that key
306	/// with the space's newest key, and signs the change as `author`.
307	#[must_use]
308	pub fn create(
309		space: SpaceId,
310		keys: &SpaceKeys,
311		author: &SigningKey,
312		draft: &Draft,
313		rng: &mut impl CryptoRng,
314	) -> Parcel {
315		let (epoch, space_key) = keys.newest();
316		let change_key = Key::generate(rng);
317		let key_hash = key_hash(&change_key);
318		let payload = SealedPayload(Envelope::seal(
319			&change_key,
320			&cbor::to_vec(&draft.payload),
321			&associated_data(space, &key_hash),
322			rng,
323		));
324		let header = Header {
325			space,
326			epoch,
327			author: author.verifying_key(),
328			parents: draft.parents.iter().copied().collect(),
329			timestamp: draft.timestamp,
330			kind: draft.kind,
331			payload_hash: payload.hash(),
332			key_hash,
333			sealed: draft.record_keys.clone(),
334			purges: draft.purges.clone(),
335			restores: draft.restores.clone(),
336		};
337		let signature = author.sign(SIGNATURE_CONTEXT, &cbor::to_vec(&header));
338		let change = Self::from_parts(header, signature);
339		let key = WrappedChangeKey::wrap(space, change.id(), &change_key, space_key, rng);
340		Parcel {
341			change,
342			payload: Some(payload),
343			keys: vec![key],
344		}
345	}
346
347	/// Puts a change together, with its ID: the hash of its encoding.
348	fn from_parts(header: Header, signature: Signature) -> Self {
349		let mut change = Self {
350			header,
351			signature,
352			id: ChangeId::from_hash(Hash::of(&[])),
353		};
354		change.id = ChangeId::from_hash(Hash::of(&cbor::to_vec(&change)));
355		change
356	}
357
358	/// The change's ID.
359	#[must_use]
360	pub const fn id(&self) -> ChangeId {
361		self.id
362	}
363
364	/// The space the change belongs to.
365	#[must_use]
366	pub const fn space(&self) -> SpaceId {
367		self.header.space
368	}
369
370	/// The number of the space key that wraps the change's key.
371	#[must_use]
372	pub const fn epoch(&self) -> u64 {
373		self.header.epoch
374	}
375
376	/// The replica that made the change.
377	#[must_use]
378	pub const fn author(&self) -> &VerifyingKey {
379		&self.header.author
380	}
381
382	/// The changes that the author's log ended with when the author made this one.
383	#[must_use]
384	pub const fn parents(&self) -> &SmallSet<ChangeId> {
385		&self.header.parents
386	}
387
388	/// The change's system time.
389	#[must_use]
390	pub const fn timestamp(&self) -> Timestamp {
391		self.header.timestamp
392	}
393
394	/// What the change is for.
395	#[must_use]
396	pub const fn kind(&self) -> Kind {
397		self.header.kind
398	}
399
400	/// The hash of the change's sealed payload.
401	#[must_use]
402	pub const fn payload_hash(&self) -> &Hash {
403		&self.header.payload_hash
404	}
405
406	/// The secret statements sealed in the change's payload, with the hashes of their record
407	/// keys, by ID.
408	#[must_use]
409	pub const fn sealed(&self) -> &BTreeMap<StatementId, Hash> {
410		&self.header.sealed
411	}
412
413	/// What the change purges.
414	#[must_use]
415	pub const fn purges(&self) -> &Purges {
416		&self.header.purges
417	}
418
419	/// What the change restores, of what purges destroyed.
420	#[must_use]
421	pub const fn restores(&self) -> &Restores {
422		&self.header.restores
423	}
424
425	/// Whether the change purges or restores anything, which the same roles may do.
426	#[must_use]
427	pub fn purges_or_restores(&self) -> bool {
428		!self.header.purges.is_empty() || !self.header.restores.is_empty()
429	}
430
431	/// Checks the change's signature.
432	///
433	/// # Errors
434	///
435	/// Returns [`LogError::InvalidSignature`] if the signature is not valid for the author.
436	pub fn verify(&self) -> Result<(), LogError> {
437		self.header
438			.author
439			.verify(
440				SIGNATURE_CONTEXT,
441				&cbor::to_vec(&self.header),
442				&self.signature,
443			)
444			.map_err(|_| LogError::InvalidSignature)
445	}
446
447	/// Decrypts the change's payload with the change's key, which `key` holds wrapped. Sealed
448	/// statements stay sealed.
449	///
450	/// # Errors
451	///
452	/// Returns an error if the payload is not this change's, if `keys` lack the space key of
453	/// the change's epoch, if the wrapped key is not this change's, or if the payload does
454	/// not have the form of a payload, or seals other statements than the header says.
455	pub fn open(
456		&self,
457		payload: &SealedPayload,
458		key: &WrappedChangeKey,
459		keys: &SpaceKeys,
460	) -> Result<Payload, LogError> {
461		if payload.hash() != self.header.payload_hash {
462			return Err(LogError::OtherPayload);
463		}
464		self.open_checked(payload, key, keys)
465	}
466
467	/// Decrypts the change's payload, as [`Change::open`] does, for a payload already known
468	/// to be the change's.
469	pub(crate) fn open_checked(
470		&self,
471		payload: &SealedPayload,
472		key: &WrappedChangeKey,
473		keys: &SpaceKeys,
474	) -> Result<Payload, LogError> {
475		if keys.get(self.header.epoch).is_none() {
476			return Err(LogError::UnknownEpoch(self.header.epoch));
477		}
478		let change_key = key.unwrap(self, keys).ok_or(LogError::OtherKey)?;
479		let plaintext = payload
480			.0
481			.open(
482				&change_key,
483				&associated_data(self.header.space, &self.header.key_hash),
484			)
485			.map_err(|_| LogError::Decryption)?;
486		let opened: Payload = cbor::from_slice(&plaintext).map_err(LogError::Operations)?;
487		let mut sealed: Vec<StatementId> = opened.all_sealed().map(|(&id, _)| id).collect();
488		sealed.sort_unstable();
489		if !sealed.iter().eq(self.header.sealed.keys()) {
490			return Err(LogError::Operations(cbor::Error::Expected(
491				"the statements that the change's header says are sealed",
492			)));
493		}
494		Ok(opened)
495	}
496}
497
498/// The parents in their CBOR form: sorted by their bytes.
499fn parents_cbor(parents: &SmallSet<ChangeId>) -> Cbor {
500	let mut parents: Vec<Vec<u8>> = parents
501		.iter()
502		.map(|parent| parent.hash().to_multihash())
503		.collect();
504	parents.sort();
505	Cbor::Array(parents.into_iter().map(Cbor::Bytes).collect())
506}
507
508impl ToCbor for Header {
509	fn to_cbor(&self) -> Cbor {
510		let mut items = vec![
511			self.space.to_cbor(),
512			self.epoch.to_cbor(),
513			self.author.to_cbor(),
514			parents_cbor(&self.parents),
515			self.timestamp.to_cbor(),
516			self.kind.to_cbor(),
517			self.payload_hash.to_cbor(),
518			self.key_hash.to_cbor(),
519			write_by_statement(&self.sealed),
520			self.purges.to_cbor(),
521		];
522		if !self.restores.is_empty() {
523			items.push(self.restores.to_cbor());
524		}
525		Cbor::Array(items)
526	}
527}
528
529impl FromCbor for Header {
530	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
531		const EXPECTED: &str = "a change header: [space, epoch, author, parents, timestamp, kind, payload hash, key hash, sealed, purges], and restores if it restores anything";
532		let Cbor::Array(items) = value else {
533			return Err(cbor::Error::Expected(EXPECTED));
534		};
535		// What it restores comes last, and only if it restores anything, so that a change
536		// that does not has the form changes had before.
537		let (items, restores) = match items.as_slice() {
538			[header @ .., restores] if header.len() == 10 => {
539				let restores = Restores::from_cbor(restores)?;
540				if restores.is_empty() {
541					return Err(cbor::Error::Expected(EXPECTED));
542				}
543				(header, restores)
544			}
545			items => (items, Restores::default()),
546		};
547		let [
548			space,
549			epoch,
550			author,
551			parents,
552			timestamp,
553			kind,
554			payload_hash,
555			key_hash,
556			sealed,
557			purges,
558		] = items
559		else {
560			return Err(cbor::Error::Expected(EXPECTED));
561		};
562		Ok(Self {
563			space: SpaceId::from_cbor(space)?,
564			epoch: u64::from_cbor(epoch)?,
565			author: VerifyingKey::from_cbor(author)?,
566			parents: read_parents(parents)?,
567			timestamp: Timestamp::from_cbor(timestamp)?,
568			kind: Kind::from_cbor(kind)?,
569			payload_hash: Hash::from_cbor(payload_hash)?,
570			key_hash: Hash::from_cbor(key_hash)?,
571			sealed: read_by_statement(
572				sealed,
573				"sealed statements: [id, record key hash] in ascending order of their IDs",
574			)?,
575			purges: Purges::from_cbor(purges)?,
576			restores,
577		})
578	}
579}
580
581/// Reads `[id, value]` pairs of statements, in ascending order of their IDs, without
582/// duplicates: the sealed statements of a header or of a payload.
583pub(crate) fn read_by_statement<T: FromCbor>(
584	value: &Cbor,
585	expected: &'static str,
586) -> Result<BTreeMap<StatementId, T>, cbor::Error> {
587	let Cbor::Array(items) = value else {
588		return Err(cbor::Error::Expected(expected));
589	};
590	let mut read = BTreeMap::new();
591	for item in items {
592		let Cbor::Array(pair) = item else {
593			return Err(cbor::Error::Expected(expected));
594		};
595		let [statement, value] = pair.as_slice() else {
596			return Err(cbor::Error::Expected(expected));
597		};
598		let statement = StatementId::from_cbor(statement)?;
599		if read
600			.last_key_value()
601			.is_some_and(|(&last, _)| last >= statement)
602		{
603			return Err(cbor::Error::Expected(expected));
604		}
605		read.insert(statement, T::from_cbor(value)?);
606	}
607	Ok(read)
608}
609
610/// Writes `[id, value]` pairs of statements, in ascending order of their IDs.
611pub(crate) fn write_by_statement<T: ToCbor>(pairs: &BTreeMap<StatementId, T>) -> Cbor {
612	Cbor::Array(
613		pairs
614			.iter()
615			.map(|(statement, value)| Cbor::Array(vec![statement.to_cbor(), value.to_cbor()]))
616			.collect(),
617	)
618}
619
620/// Reads parents, which must be sorted by their bytes, without duplicates.
621fn read_parents(value: &Cbor) -> Result<SmallSet<ChangeId>, cbor::Error> {
622	const EXPECTED: &str = "parents: change IDs sorted by their bytes, without duplicates";
623	let Cbor::Array(items) = value else {
624		return Err(cbor::Error::Expected(EXPECTED));
625	};
626	let mut previous: Option<&[u8]> = None;
627	let mut parents = SmallSet::new();
628	for item in items {
629		let Cbor::Bytes(bytes) = item else {
630			return Err(cbor::Error::Expected(EXPECTED));
631		};
632		if previous.is_some_and(|previous| previous >= bytes.as_slice()) {
633			return Err(cbor::Error::Expected(EXPECTED));
634		}
635		previous = Some(bytes);
636		parents.insert(ChangeId::from_cbor(item)?);
637	}
638	Ok(parents)
639}
640
641impl ToCbor for Change {
642	fn to_cbor(&self) -> Cbor {
643		Cbor::Array(vec![
644			SUITE.to_cbor(),
645			self.header.to_cbor(),
646			self.signature.to_cbor(),
647		])
648	}
649}
650
651impl FromCbor for Change {
652	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
653		const EXPECTED: &str = "a change: [1, header, signature]";
654		let Cbor::Array(items) = value else {
655			return Err(cbor::Error::Expected(EXPECTED));
656		};
657		let [suite, header, signature] = items.as_slice() else {
658			return Err(cbor::Error::Expected(EXPECTED));
659		};
660		if u8::from_cbor(suite) != Ok(SUITE) {
661			return Err(cbor::Error::Expected(EXPECTED));
662		}
663		Ok(Self::from_parts(
664			Header::from_cbor(header)?,
665			Signature::from_cbor(signature)?,
666		))
667	}
668}