Skip to main content

nibkeep_sync/
pack.rs

1//! Packs: files of a space's items, as the messages of a sync carry them, which backups hold
2//! without keys ([Storage](../../../docs/spec/storage.md#6-backups)).
3//!
4//! A pack is a CBOR sequence: `[1, space, update]`, then items of that space, each the
5//! message `[4, space, …]` that a sync sends of it, and a blob's bytes after its item as
6//! one message `[7, bytes]`.
7
8use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
9use nibkeep_base::{Hash, SpaceId, StatementId};
10use nibkeep_log::{Parcel, WrappedBlobKey, WrappedKey};
11
12use crate::SyncError;
13use crate::message::{Item, SyncMessage, bytes_message};
14
15/// The version of the format of packs.
16const VERSION: u64 = 1;
17
18/// The largest sealed blob that a pack holds, 1 MiB: a larger one has a file of its own.
19pub const MOST_PACK_BLOB: u64 = 1024 * 1024;
20
21/// How many bytes a pack takes at most, 64 MiB, but for a single item that is larger: a
22/// writer with more to write writes another.
23pub const PACK_SIZE: usize = 64 * 1024 * 1024;
24
25/// An item of a pack.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub enum PackItem {
28	/// A change, with its sealed payload and keys as far as the writer held them.
29	Change(Box<Parcel>),
30	/// A wrapped record key of a secret statement.
31	RecordKey(StatementId, WrappedKey),
32	/// A wrapped blob key.
33	BlobKey(Hash, WrappedBlobKey),
34	/// A sealed blob of at most [`MOST_PACK_BLOB`] bytes, by its sealed hash.
35	Blob(Hash, Vec<u8>),
36}
37
38/// The encoding of a pack's first value: its space, and the number of the update that wrote
39/// it.
40#[must_use]
41pub fn pack_header(space: SpaceId, update: u64) -> Vec<u8> {
42	cbor::encode(&Value::Array(vec![
43		VERSION.to_cbor(),
44		space.to_cbor(),
45		update.to_cbor(),
46	]))
47}
48
49/// The encoding of an item in a pack of `space`: the message that a sync sends of it, and of
50/// a blob, its bytes after it.
51#[must_use]
52pub fn pack_item(space: SpaceId, item: &PackItem) -> Vec<u8> {
53	match item {
54		PackItem::Change(parcel) => SyncMessage::Item(space, Item::Change(parcel.clone())).encode(),
55		PackItem::RecordKey(statement, key) => {
56			SyncMessage::Item(space, Item::RecordKey(*statement, key.clone())).encode()
57		}
58		PackItem::BlobKey(sealed, key) => {
59			SyncMessage::Item(space, Item::BlobKey(*sealed, key.clone())).encode()
60		}
61		PackItem::Blob(sealed, bytes) => {
62			let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
63			let mut encoded = SyncMessage::Item(space, Item::Blob(*sealed, size)).encode();
64			encoded.extend(bytes_message(bytes));
65			encoded
66		}
67	}
68}
69
70/// A pack as it reads: its space, the update that wrote it, and its items, one after the
71/// other, each checked as it is read.
72pub struct PackReader<'a> {
73	bytes: &'a [u8],
74	position: usize,
75	space: SpaceId,
76	update: u64,
77}
78
79impl<'a> PackReader<'a> {
80	/// Starts reading a pack from its bytes.
81	///
82	/// # Errors
83	///
84	/// Returns [`SyncError::Protocol`] if the bytes do not start with a pack's first value.
85	pub fn new(bytes: &'a [u8]) -> Result<Self, SyncError> {
86		let (header, length) = first(bytes)?;
87		let Value::Array(fields) = header else {
88			return Err(SyncError::protocol("a pack starts with [1, space, update]"));
89		};
90		let [version, space, update] = fields.as_slice() else {
91			return Err(SyncError::protocol("a pack starts with [1, space, update]"));
92		};
93		if u64::from_cbor(version).ok() != Some(VERSION) {
94			return Err(SyncError::protocol("a pack of another version"));
95		}
96		let wrong = |error: cbor::Error| SyncError::protocol(error.to_string());
97		Ok(Self {
98			bytes,
99			position: length,
100			space: SpaceId::from_cbor(space).map_err(wrong)?,
101			update: u64::from_cbor(update).map_err(wrong)?,
102		})
103	}
104
105	/// The item whose encoding `bytes` holds whole, as [`PackReader::next_item`] found it
106	/// in a pack of `space`.
107	///
108	/// # Errors
109	///
110	/// Returns [`SyncError::Protocol`] if `bytes` is not exactly one such item.
111	pub fn item_at(space: SpaceId, bytes: &[u8]) -> Result<PackItem, SyncError> {
112		let mut reader = PackReader {
113			bytes,
114			position: 0,
115			space,
116			update: 0,
117		};
118		match reader.next_item()? {
119			Some((item, _, length)) if length == bytes.len() => Ok(item),
120			_ => Err(SyncError::protocol("not one item of a pack")),
121		}
122	}
123
124	/// The space whose items the pack holds.
125	#[must_use]
126	pub const fn space(&self) -> SpaceId {
127		self.space
128	}
129
130	/// The number of the update that wrote the pack.
131	#[must_use]
132	pub const fn update(&self) -> u64 {
133		self.update
134	}
135
136	/// The next item, with where its encoding starts in the pack and how long it is, or
137	/// `None` at the pack's end.
138	///
139	/// # Errors
140	///
141	/// Returns [`SyncError::Protocol`] if what follows is no item of the pack's space, or a
142	/// blob whose bytes do not have its sealed hash, or is larger than [`MOST_PACK_BLOB`].
143	pub fn next_item(&mut self) -> Result<Option<(PackItem, usize, usize)>, SyncError> {
144		if self.position == self.bytes.len() {
145			return Ok(None);
146		}
147		let start = self.position;
148		let message = self.message()?;
149		let SyncMessage::Item(space, item) = message else {
150			return Err(SyncError::protocol("a pack holds items only"));
151		};
152		if space != self.space {
153			return Err(SyncError::protocol("an item of another space in a pack"));
154		}
155		let item = match item {
156			Item::Change(parcel) => PackItem::Change(parcel),
157			Item::RecordKey(statement, key) => PackItem::RecordKey(statement, key),
158			Item::BlobKey(sealed, key) => PackItem::BlobKey(sealed, key),
159			Item::Blob(sealed, size) => {
160				if size > MOST_PACK_BLOB {
161					return Err(SyncError::protocol("a blob too large for a pack"));
162				}
163				let SyncMessage::Bytes(bytes) = self.message()? else {
164					return Err(SyncError::protocol("a blob's item without its bytes"));
165				};
166				if u64::try_from(bytes.len()).ok() != Some(size) || Hash::of(&bytes) != sealed {
167					return Err(SyncError::protocol("a blob whose bytes are not its own"));
168				}
169				PackItem::Blob(sealed, bytes)
170			}
171			Item::Account(_) => return Err(SyncError::protocol("a page of an account in a pack")),
172		};
173		Ok(Some((item, start, self.position - start)))
174	}
175
176	/// The next message, read whole.
177	fn message(&mut self) -> Result<SyncMessage, SyncError> {
178		let rest = self.bytes.get(self.position..).unwrap_or_default();
179		let (value, length) = first(rest)?;
180		let message = SyncMessage::from_value(value)?;
181		self.position += length;
182		Ok(message)
183	}
184}
185
186/// The first value of `bytes`, and how long its encoding is.
187fn first(bytes: &[u8]) -> Result<(Value, usize), SyncError> {
188	cbor::decode_first(bytes).map_err(|error| SyncError::protocol(error.to_string()))
189}
190
191#[cfg(test)]
192mod tests {
193	use super::*;
194
195	#[test]
196	fn a_pack_reads_back_its_blobs_and_refuses_one_that_is_not_its_own() {
197		let space = SpaceId::from_bytes([7; 16]);
198		let blob = b"sealed bytes".to_vec();
199		let sealed = Hash::of(&blob);
200		let mut pack = pack_header(space, 3);
201		pack.extend(pack_item(space, &PackItem::Blob(sealed, blob.clone())));
202		let mut reader = PackReader::new(&pack).expect("a pack");
203		assert_eq!((reader.space(), reader.update()), (space, 3));
204		let (item, start, length) = reader.next_item().expect("reads").expect("an item");
205		assert_eq!(item, PackItem::Blob(sealed, blob));
206		assert_eq!(start + length, pack.len());
207		assert!(reader.next_item().expect("reads").is_none());
208		// Another blob's bytes under that sealed hash.
209		let mut forged = pack_header(space, 3);
210		forged.extend(pack_item(space, &PackItem::Blob(sealed, b"other".to_vec())));
211		let mut reader = PackReader::new(&forged).expect("a pack");
212		assert!(reader.next_item().is_err());
213		// An item of another space.
214		let mut mixed = pack_header(space, 3);
215		mixed.extend(pack_item(
216			SpaceId::from_bytes([8; 16]),
217			&PackItem::Blob(sealed, b"sealed bytes".to_vec()),
218		));
219		let mut reader = PackReader::new(&mixed).expect("a pack");
220		assert!(reader.next_item().is_err());
221	}
222}