Skip to main content

nibkeep_log/
log.rs

1//! The log of a space: the changes a replica has, and the state they build.
2
3use std::borrow::Cow;
4use std::cell::{Cell, RefCell};
5use std::collections::{BTreeMap, BTreeSet, btree_map};
6
7use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
8use nibkeep_crypto::rand_core::CryptoRng;
9use nibkeep_crypto::{Key, SigningKey, VerifyingKey, key_hash};
10use nibkeep_governance::rules::{Fact, Governance};
11use nibkeep_governance::{Followed, Role};
12use nibkeep_model::storage::{AsOf, Layers, Memory, Origin, Statements};
13use nibkeep_model::{FieldName, Operation, State, Statement, fields};
14use nibkeep_time::{Clock, Timestamp};
15
16use crate::history::{Accepted, History, MemoryHistory, Status, Summary};
17use crate::keys::Unwrapped;
18use crate::payload::{open_sealed, seal};
19use crate::{
20	Change, ChangeId, Draft, Kind, LogError, Parcel, Payload, Purges, Restores, SealedPayload,
21	SpaceKeys, WrappedBlobKey, WrappedChangeKey, WrappedKey,
22};
23pub use governance::Review;
24
25mod governance;
26
27/// How many changes may wait for their parents unless [`Log::limit_waiting`] says
28/// otherwise.
29const DEFAULT_WAITING_LIMIT: usize = 100_000;
30
31/// How many different wrapped keys a replica keeps for one statement, while it cannot tell
32/// which of them are good.
33const WRAPPED_KEYS_PER_STATEMENT: usize = 4;
34
35/// How many different wrapped keys a replica keeps for one sealed blob, while it cannot
36/// tell which of them are good.
37const WRAPPED_KEYS_PER_BLOB: usize = 4;
38
39/// How many different wrapped keys a replica keeps for one change, while it cannot tell
40/// which of them are good.
41const WRAPPED_KEYS_PER_CHANGE: usize = 4;
42
43/// The state a log builds: its ordinary statements, kept in `S`, with the secret statements
44/// this replica has opened, which never reach the storage of the ordinary ones.
45pub type SpaceState<S = Memory> = State<Layers<S>>;
46
47/// A replica's copy of a space's log: the changes it has accepted, with their sealed
48/// payloads and wrapped keys as far as it has them, the changes waiting for their parents,
49/// the changes it rejected for good, the wrapped record keys of secret statements, the
50/// wrapped keys of blobs, and the state that the accepted changes build.
51///
52/// A change is accepted on its header alone, and its operations are applied once its
53/// payload and key are there too, in whatever order they arrive.
54///
55/// The log keeps the space's hybrid logical clock, so the caller passes the wall clock
56/// time to every call that makes or receives a change.
57///
58/// The ordinary statements of the state are kept in a storage `S`, and the accepted
59/// changes in a history `H`: in memory, or on disk, where reading and writing may fail. The
60/// log then keeps the error, and refuses to make or take changes until it is built again,
61/// as it no longer matches its storage.
62#[derive(Debug)]
63pub struct Log<S: Statements = Memory, H: History = MemoryHistory<<S as Statements>::Error>> {
64	space: SpaceId,
65	clock: Clock,
66	/// The accepted changes.
67	history: H,
68	/// Changes waiting for some of their parents.
69	waiting: BTreeMap<ChangeId, Held>,
70	/// The decrypted payloads of the changes whose operations the last call applied, which
71	/// the caller may take, so that it need not decrypt them again.
72	applied: Vec<(ChangeId, Payload)>,
73	/// For each change that waiting changes need and that is not accepted, the changes
74	/// that need it.
75	waiting_on: BTreeMap<ChangeId, BTreeSet<ChangeId>>,
76	waiting_limit: usize,
77	/// Changes that can never be accepted, with the reason.
78	rejected: BTreeMap<ChangeId, LogError>,
79	state: SpaceState<S>,
80	/// Changes taken back whose operations the storage holds already.
81	covered: BTreeSet<ChangeId>,
82	/// Whether reading or writing the storage or the history failed, and the error, until
83	/// it is taken.
84	failed: Cell<bool>,
85	storage_error: RefCell<Option<S::Error>>,
86	/// The fields whose values are secret.
87	secret_fields: BTreeSet<FieldName>,
88	/// The wrapped record keys of secret statements: a few candidates for each, until one
89	/// of them is known to be good.
90	wrapped: BTreeMap<StatementId, Vec<WrappedKey>>,
91	/// The wrapped keys of sealed blobs, by sealed hash: a few candidates for each, until
92	/// one of them is known to be good.
93	wrapped_blob_keys: BTreeMap<Hash, Vec<WrappedBlobKey>>,
94	/// The blob keys this replica has opened: by sealed hash, the content hash and the key.
95	blob_keys: BTreeMap<Hash, (Hash, Key)>,
96	/// For each content hash, the sealed hashes of the blob keys opened for it.
97	sealed_blobs: BTreeMap<Hash, BTreeSet<Hash>>,
98	/// The sealed hashes of the opened blob keys that are secret blob keys, which the
99	/// replica forgets when it locks its secrets.
100	secret_blobs: BTreeSet<Hash>,
101	/// The sealed hashes with a wrapped key in the form of a secret blob key, whose outer
102	/// layer opened: those that unlocking the secrets may open, or open anew.
103	secret_candidates: BTreeSet<Hash>,
104	/// Whether a purge took away operations that the state holds, or a change that counted
105	/// was set aside, so that the state is to be built again: in a fresh storage at once,
106	/// where one costs nothing, or else by the caller, which [`Log::take_stale`] tells.
107	stale: bool,
108	/// What the governing changes that count say, once read: which keys are listed and
109	/// which revoked. It is read from the governing changes and their statuses, and decided
110	/// anew when a governing change can be read.
111	governance: RefCell<Option<Governance>>,
112	/// Whether the space's first change must govern it, as in every space of NibKeep, so that
113	/// a change without parents that does not is rejected whenever it comes.
114	expects_governed: bool,
115	/// The changes that may be the space's first, if the replica was told which: only these
116	/// are taken as its first change, and any other is refused, without being rejected;
117	/// `None` while it was told nothing, when it takes any.
118	expected_roots: Option<BTreeSet<ChangeId>>,
119	/// What each governing change that the log has read says, or `None` if it does not have
120	/// the form a governing change must: read once, as it never changes.
121	facts: RefCell<BTreeMap<ChangeId, Option<governance::ReadGoverning>>>,
122	/// In a space with members, the latest governing changes that each change builds on,
123	/// found once for each, with the governing changes they were found among: kept while
124	/// those are the same.
125	frontiers: RefCell<governance::Frontiers>,
126	/// What the purges that the last call acted on destroyed, for the caller to delete from
127	/// its storage too.
128	destroyed: Destroyed,
129	/// Whether what purges destroy is kept, as it was, in [`Destroyed::kept`], for a
130	/// replica that waits before purging.
131	keeping: bool,
132	/// The accepted changes that restore anything, once looked for: rare, and looked for
133	/// only when a purge must know whether something it names was restored.
134	restoring: RefCell<Option<BTreeSet<ChangeId>>>,
135	/// The groups in the space that it follows, as the replica's copies of their logs say:
136	/// their changes take effect at the space's anchors that name them.
137	following: BTreeMap<SpaceId, Followed>,
138}
139
140/// What purges destroyed: the record keys of secret statements, the keys of sealed blobs,
141/// and whether changes lost their keys and payloads; with what a replica that waits keeps of
142/// it, and what changes that restore brought back.
143#[derive(Clone, Debug, Default, PartialEq, Eq)]
144pub struct Destroyed {
145	/// The secret statements whose record keys were destroyed.
146	pub statements: Vec<StatementId>,
147	/// The sealed hashes of the blobs whose keys were destroyed.
148	pub blobs: Vec<Hash>,
149	/// Whether changes lost their keys and payloads.
150	pub changes: bool,
151	/// What the purges destroyed, as it was, by the purge that destroyed each part, if the
152	/// log keeps it ([`Log::keep_destroyed`]).
153	pub kept: Vec<(ChangeId, Kept)>,
154	/// What is no longer purged, as a change that restores it came to count: the changes
155	/// that wait for their payloads and keys again, and the statements and blobs that wait
156	/// for their wrapped keys.
157	pub restored: Restores,
158}
159
160impl Destroyed {
161	/// Whether nothing was destroyed.
162	#[must_use]
163	pub fn is_empty(&self) -> bool {
164		self.statements.is_empty() && self.blobs.is_empty() && !self.changes
165	}
166}
167
168/// Which purge keeps each purged item purged ([`Log::purged_by`]).
169#[derive(Clone, Debug, Default, PartialEq, Eq)]
170pub struct PurgedBy {
171	/// The purged changes, each by its purge.
172	pub changes: BTreeMap<ChangeId, ChangeId>,
173	/// The secret statements whose record keys were destroyed, each by its purge.
174	pub statements: BTreeMap<StatementId, ChangeId>,
175	/// The sealed blobs whose keys were destroyed, each by its purge.
176	pub blobs: BTreeMap<Hash, ChangeId>,
177}
178
179/// A part of what a purge destroyed, as it was, which a replica that waits keeps apart, to
180/// give back if a change restores it ([technical design: copies that wait]).
181///
182/// [technical design: copies that wait]: ../../../docs/Technical-design.md#911-copies-that-wait
183#[derive(Clone, Debug, PartialEq, Eq)]
184pub enum Kept {
185	/// A change, with the sealed payload and wrapped keys it had.
186	Change(Box<Parcel>),
187	/// The wrapped record keys of a secret statement.
188	RecordKeys(StatementId, Vec<WrappedKey>),
189	/// The wrapped keys of a sealed blob.
190	BlobKeys(Hash, Vec<WrappedBlobKey>),
191}
192
193/// A change waiting for its parents, with the parts that came with it.
194#[derive(Clone, Debug)]
195struct Held {
196	change: Change,
197	payload: Option<SealedPayload>,
198	/// A few candidates for the change's wrapped key, until one of them is known to be
199	/// good, and then that one alone.
200	keys: Vec<WrappedChangeKey>,
201}
202
203impl Held {
204	fn parcel(&self) -> Parcel {
205		Parcel {
206			change: self.change.clone(),
207			payload: self.payload.clone(),
208			keys: self.keys.clone(),
209		}
210	}
211}
212
213/// Whether governing operations revoke a replica or set a role: what a replica would undo so,
214/// by revoking back or taking a role away, may revoke it or take its role away itself, sent
215/// without its payload, so such a change builds on no governing change it has not read.
216fn defends(operations: &[Operation]) -> bool {
217	operations.iter().any(|operation| {
218		matches!(operation, Operation::Assert { statement, .. }
219			if statement.field == fields::REVOKED || statement.field == fields::ROLE)
220	})
221}
222
223/// Whether a change's payload fits its kind: an ordinary change holds no statement that
224/// governs the space, and one that restores holds nothing at all; a governing change holds
225/// only such statements, and states nothing again.
226fn fits_its_kind(change: &Change, payload: &Payload) -> bool {
227	match change.kind() {
228		// A change that restores holds nothing else.
229		Kind::Ordinary if !change.restores().is_empty() => *payload == Payload::default(),
230		Kind::Ordinary => {
231			!holds_governing(&payload.operations)
232				&& payload
233					.restated
234					.values()
235					.all(|restated| !holds_governing(&restated.operations))
236		}
237		Kind::Governing => holds_only_governing(&payload.operations) && payload.restated.is_empty(),
238	}
239}
240
241/// The parts of an accepted change, as they travel.
242fn parcel_of(accepted: &Accepted) -> Parcel {
243	Parcel {
244		change: accepted.change.clone(),
245		payload: accepted.payload.clone(),
246		keys: accepted.keys.clone(),
247	}
248}
249
250/// Opens an accepted change's payload, if it is there with a good key, and keeps that key
251/// alone. Candidate keys that are not the change's are dropped.
252fn open_payload(accepted: &mut Accepted, keys: &SpaceKeys) -> Opened {
253	let Some(payload) = &accepted.payload else {
254		return Opened::NotYet;
255	};
256	if keys.get(accepted.change.epoch()).is_none() {
257		return Opened::NotYet;
258	}
259	let change = &accepted.change;
260	let mut opened = Opened::NotYet;
261	accepted.keys.retain(|key| {
262		if !matches!(opened, Opened::NotYet) {
263			return false;
264		}
265		match change.open_checked(payload, key, keys) {
266			Ok(payload) => {
267				opened = Opened::Payload(payload);
268				true
269			}
270			// Not the change's key.
271			Err(LogError::OtherKey) => false,
272			// The change's key, but a payload that adds nothing.
273			Err(_) => {
274				opened = Opened::Nothing;
275				true
276			}
277		}
278	});
279	opened
280}
281
282/// Opens an accepted change's payload with the first of its candidate keys that opens it.
283fn read_payload(accepted: &Accepted, keys: &SpaceKeys) -> Result<Option<Payload>, LogError> {
284	let Some(payload) = &accepted.payload else {
285		return Ok(None);
286	};
287	let mut last = None;
288	for key in &accepted.keys {
289		match accepted.change.open_checked(payload, key, keys) {
290			Ok(opened) => return Ok(Some(opened)),
291			Err(error) => last = Some(error),
292		}
293	}
294	last.map_or(Ok(None), Err)
295}
296
297/// What opening a change's payload gives.
298enum Opened {
299	/// The payload, or a good key for it, is not there yet.
300	NotYet,
301	/// The payload opens with the change's key, but adds nothing: it does not have the
302	/// form of a payload.
303	Nothing,
304	/// The payload.
305	Payload(Payload),
306}
307
308/// A change whose signature is not valid, or, with why, that the history cannot read.
309pub type Forged<E> = (ChangeId, Option<E>);
310
311/// What became of a received change.
312#[derive(Clone, Debug, PartialEq, Eq)]
313pub enum Received {
314	/// The change was accepted, followed by the waiting changes it completed, in the order
315	/// they were accepted. Their operations are applied once their payloads and keys are
316	/// there.
317	Accepted(Vec<ChangeId>),
318	/// The change waits for some of its parents.
319	Waiting,
320	/// The log already has the change, accepted or waiting, and all that came with it.
321	Duplicate,
322	/// The log already has the change, accepted or waiting, and keeps the payload or a key
323	/// that came with it, which it lacked.
324	Completed,
325}
326
327/// Whether a change's signature is checked as the log takes it.
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329enum Signature {
330	/// Checked: the change comes from elsewhere.
331	Check,
332	/// Trusted: the change comes from the replica's own storage, and was checked when it
333	/// arrived.
334	Trusted,
335}
336
337impl Log {
338	/// Returns an empty log of a space, with the space's clock, and its state and history in
339	/// memory.
340	#[must_use]
341	pub fn new(space: SpaceId, clock: Clock) -> Self {
342		Self::with_storage(space, clock, Memory::default())
343	}
344}
345
346impl<S: Statements> Log<S, MemoryHistory<S::Error>> {
347	/// Returns an empty log of a space, with the space's clock, whose state is kept in
348	/// `storage`, and its history in memory. The storage may hold the operations of changes
349	/// already: those that [`Log::restore`] says it covers.
350	#[must_use]
351	pub fn with_storage(space: SpaceId, clock: Clock, storage: S) -> Self {
352		Self::with_history(space, clock, storage, MemoryHistory::default())
353	}
354}
355
356impl<S: Statements, H: History<Error = S::Error>> Log<S, H> {
357	/// Returns a log of a space, with the space's clock, whose state is kept in `storage`
358	/// and whose accepted changes are kept in `history`.
359	#[must_use]
360	pub fn with_history(space: SpaceId, clock: Clock, storage: S, history: H) -> Self {
361		Self {
362			space,
363			clock,
364			history,
365			waiting: BTreeMap::new(),
366			applied: Vec::new(),
367			waiting_on: BTreeMap::new(),
368			waiting_limit: DEFAULT_WAITING_LIMIT,
369			rejected: BTreeMap::new(),
370			state: State::in_storage(Layers::new(storage)),
371			covered: BTreeSet::new(),
372			failed: Cell::new(false),
373			storage_error: RefCell::new(None),
374			secret_fields: BTreeSet::new(),
375			wrapped: BTreeMap::new(),
376			wrapped_blob_keys: BTreeMap::new(),
377			blob_keys: BTreeMap::new(),
378			sealed_blobs: BTreeMap::new(),
379			secret_blobs: BTreeSet::new(),
380			secret_candidates: BTreeSet::new(),
381			stale: false,
382			governance: RefCell::new(None),
383			expects_governed: false,
384			expected_roots: None,
385			facts: RefCell::new(BTreeMap::new()),
386			frontiers: RefCell::default(),
387			destroyed: Destroyed::default(),
388			keeping: false,
389			restoring: RefCell::new(None),
390			following: BTreeMap::new(),
391		}
392	}
393
394	/// Empties the log, as [`Log::with_history`] makes it, but keeps its storage, the
395	/// fields that are secret and the limit on waiting changes, with the space's clock
396	/// `clock`: to take back its changes again, after the storage was made again or a
397	/// failure left the log out of step with it. Its history is emptied, and opened secrets
398	/// are forgotten.
399	pub fn reset(&mut self, clock: Clock) {
400		// Every field is named, so that a field added later is decided on here.
401		let Self {
402			space: _,
403			clock: own_clock,
404			history,
405			waiting,
406			applied,
407			waiting_on,
408			waiting_limit: _,
409			rejected,
410			state,
411			covered,
412			failed,
413			storage_error,
414			secret_fields: _,
415			wrapped,
416			wrapped_blob_keys,
417			blob_keys,
418			sealed_blobs,
419			secret_blobs,
420			secret_candidates,
421			stale,
422			governance,
423			expects_governed: _,
424			expected_roots: _,
425			facts,
426			frontiers,
427			destroyed,
428			keeping: _,
429			restoring,
430			following: _,
431		} = self;
432		*own_clock = clock;
433		waiting.clear();
434		applied.clear();
435		waiting_on.clear();
436		rejected.clear();
437		state.storage_mut().forget_all();
438		covered.clear();
439		failed.set(false);
440		*storage_error.get_mut() = None;
441		wrapped.clear();
442		wrapped_blob_keys.clear();
443		blob_keys.clear();
444		sealed_blobs.clear();
445		secret_blobs.clear();
446		secret_candidates.clear();
447		*stale = false;
448		*governance.get_mut() = None;
449		facts.get_mut().clear();
450		*frontiers.get_mut() = governance::Frontiers::default();
451		*destroyed = Destroyed::default();
452		*restoring.get_mut() = None;
453		if let Err(error) = history.clear() {
454			self.fault(error);
455		}
456	}
457
458	/// Why reading or writing the storage or the history failed, if it did and this was not
459	/// asked before. The log keeps refusing changes, as it no longer matches its storage.
460	pub fn storage_error(&mut self) -> Option<S::Error> {
461		self.storage_error.get_mut().take()
462	}
463
464	/// The storage of the state, to begin and end transactions, for example.
465	pub fn storage_mut(&mut self) -> &mut S {
466		self.state.storage_mut().ordinary_mut()
467	}
468
469	/// The history, to begin and end transactions, for example.
470	pub fn history_mut(&mut self) -> &mut H {
471		&mut self.history
472	}
473
474	/// The history.
475	#[must_use]
476	pub const fn history(&self) -> &H {
477		&self.history
478	}
479
480	/// Notes that the storage or the history failed: the log refuses changes from now on.
481	fn fault(&self, error: S::Error) -> LogError {
482		self.failed.set(true);
483		*self.storage_error.borrow_mut() = Some(error);
484		LogError::Storage
485	}
486
487	/// What the storage or the history answered, or [`LogError::Storage`] if it failed.
488	fn read<T>(&self, result: Result<T, S::Error>) -> Result<T, LogError> {
489		result.map_err(|error| self.fault(error))
490	}
491
492	/// Returns [`LogError::Storage`] if reading or writing the storage has failed.
493	fn check_storage(&self) -> Result<(), LogError> {
494		if self.failed.get() {
495			Err(LogError::Storage)
496		} else {
497			Ok(())
498		}
499	}
500
501	/// Has the space's first change govern it, as it does in every space of NibKeep: a
502	/// change without parents that does not govern the space is rejected from now on,
503	/// whatever came before it, so that every replica decides the same of it.
504	pub fn expect_governed(&mut self) {
505		self.expects_governed = true;
506	}
507
508	/// Takes as the space's first change only one of `roots`, as a replica told by another
509	/// that it trusts which change founded the space does: any other change without parents
510	/// is refused, without being rejected, so that the real one is taken when it comes. With
511	/// no roots, it takes none until it is told one.
512	pub fn expect_roots(&mut self, roots: impl IntoIterator<Item = ChangeId>) {
513		self.expected_roots = Some(roots.into_iter().collect());
514	}
515
516	/// Takes as the space's first change one of `roots` too, besides those it was told of
517	/// before, as [`Log::expect_roots`] says: when several sources that it trusts each name
518	/// the change that founded the space. If it was told of none, it takes only one of
519	/// `roots`; with no roots, it then takes none until it is told one, as when a source it
520	/// trusts cannot be read.
521	pub fn expect_roots_too(&mut self, roots: impl IntoIterator<Item = ChangeId>) {
522		self.expected_roots.get_or_insert_default().extend(roots);
523	}
524
525	/// Limits how many changes may wait for their parents, which is 100,000 unless set.
526	pub fn limit_waiting(&mut self, limit: usize) {
527		self.waiting_limit = limit;
528	}
529
530	/// Keeps what purges destroy, as it was, in [`Destroyed::kept`], for a replica that waits
531	/// before purging, which keeps it apart for a while: or no longer.
532	pub fn keep_destroyed(&mut self, keeping: bool) {
533		self.keeping = keeping;
534	}
535
536	/// Sets the fields whose values are secret, as the space's types mark them. New
537	/// statements of these fields are sealed with record keys of their own.
538	pub fn set_secret_fields(&mut self, fields: impl IntoIterator<Item = FieldName>) {
539		self.secret_fields = fields.into_iter().collect();
540	}
541
542	/// The space.
543	#[must_use]
544	pub const fn space(&self) -> SpaceId {
545		self.space
546	}
547
548	/// The space's clock, to save across restarts.
549	#[must_use]
550	pub const fn clock(&self) -> &Clock {
551		&self.clock
552	}
553
554	/// Makes a change of `operations`, signed by `author`, its key wrapped with the newest
555	/// of `keys`, and applies it. Statements of secret fields are sealed, their record keys
556	/// wrapped with the newest secrets key, and what they supersede retracted in the
557	/// ordinary layer. Statements of the fields that govern the space make a change of
558	/// their own ([`Kind::Governing`]), wrapped with the space's first key, which every
559	/// replica holds; one that revokes a replica or sets a role builds on no governing
560	/// change whose payload this replica has not read. Returns the change with its payload
561	/// and key, for other replicas.
562	///
563	/// # Errors
564	///
565	/// Returns an error, and leaves the log unchanged, if a secret value is to be written
566	/// without a secrets key, if statements that govern the space come with others, if
567	/// `keys` lack the space's first key for a governing change, or if the clock has run
568	/// out of timestamps.
569	pub fn commit(
570		&mut self,
571		author: &SigningKey,
572		keys: &SpaceKeys,
573		operations: Vec<Operation>,
574		wall_millis: u64,
575		rng: &mut impl CryptoRng,
576	) -> Result<Parcel, LogError> {
577		self.check_storage()?;
578		self.applied.clear();
579		self.destroyed = Destroyed::default();
580		let mut governing = 0;
581		for operation in &operations {
582			if self.read(self.governs(operation))? {
583				governing += 1;
584			}
585		}
586		let kind = match governing {
587			0 => Kind::Ordinary,
588			all if all == operations.len() => Kind::Governing,
589			_ => return Err(LogError::MixedGoverning),
590		};
591		let defends = kind == Kind::Governing && defends(&operations);
592		let first_key;
593		let keys = if kind == Kind::Governing {
594			first_key = keys.get(0).map(|_| keys.writing_with(0));
595			first_key.as_ref().ok_or(LogError::UnknownEpoch(0))?
596		} else {
597			keys
598		};
599		let mut payload = Payload::default();
600		let mut secret = Vec::new();
601		let is_secret = |statement: &Statement| {
602			kind == Kind::Ordinary && self.secret_fields.contains(&statement.field)
603		};
604		// What takes away secret statements names no entity, as theirs are sealed with them:
605		// one retraction of secret statements, which takes away no ordinary statement, for
606		// those this replica knows to be of the entity named: opened, or sealed in this
607		// change.
608		let mut taking = TakingSecrets {
609			sealing: operations
610				.iter()
611				.filter_map(|operation| match operation {
612					Operation::Assert { statement, .. } if is_secret(statement) => {
613						Some((statement.id, statement.entity))
614					}
615					_ => None,
616				})
617				.collect(),
618			taken: BTreeSet::new(),
619		};
620		for operation in operations {
621			match operation {
622				Operation::Assert {
623					statement,
624					supersedes,
625					..
626				} if is_secret(&statement) => {
627					let retraction =
628						self.read(self.take_secret(statement.entity, supersedes, &mut taking))?;
629					payload.operations.extend(retraction);
630					secret.push(statement);
631				}
632				Operation::Retract {
633					entity: Some(entity),
634					statements,
635				} if kind == Kind::Ordinary => {
636					let retraction =
637						self.read(self.take_secret(entity, statements, &mut taking))?;
638					payload.operations.extend(retraction);
639				}
640				other => payload.operations.push(other),
641			}
642		}
643		if !taking.taken.is_empty() {
644			payload
645				.operations
646				.push(Operation::retract_secret(taking.taken));
647		}
648		let mut record_keys = BTreeMap::new();
649		let mut wrapped = Vec::new();
650		if !secret.is_empty() {
651			let secrets_key = keys.newest_secrets().ok_or(LogError::SecretsLocked)?;
652			for statement in secret {
653				let record_key = Key::generate(rng);
654				let id = statement.id;
655				payload
656					.sealed
657					.insert(id, seal(self.space, &statement, &record_key, rng));
658				record_keys.insert(id, key_hash(&record_key));
659				let key = WrappedKey::wrap(self.space, id, &record_key, secrets_key, rng);
660				wrapped.push((id, key));
661			}
662		}
663		let heads = if defends {
664			self.defending_parents()?
665		} else {
666			self.read(self.history.heads())?
667		};
668		let timestamp = self.clock.now(wall_millis)?;
669		let mut draft = Draft::new(heads, timestamp, payload);
670		draft.kind = kind;
671		draft.record_keys = record_keys;
672		let parcel = Change::create(self.space, keys, author, &draft, rng);
673		for (id, key) in wrapped {
674			self.wrapped.insert(id, vec![key]);
675		}
676		// The change is read as every other replica reads it.
677		self.accept(held(parcel.clone()), keys)?;
678		self.check_storage()?;
679		Ok(parcel)
680	}
681
682	/// Of statements that an operation about `entity` takes away, moves the secret ones of
683	/// that entity that this replica knows, opened or sealed in the same change, to those
684	/// that the change's retraction of secret statements takes away, and returns the
685	/// retraction of the others, which names the entity, if any are left: a statement of
686	/// another entity stays there, where it is not superseded, as the operation said.
687	fn take_secret(
688		&self,
689		entity: EntityId,
690		statements: BTreeSet<StatementId>,
691		taking: &mut TakingSecrets,
692	) -> Result<Option<Operation>, S::Error> {
693		let storage = self.state.storage();
694		let mut others = BTreeSet::new();
695		for id in statements {
696			let secret = match taking.sealing.get(&id) {
697				Some(&of) => of == entity,
698				None => {
699					storage.is_secret(id)?
700						&& storage
701							.get(id)?
702							.is_some_and(|recorded| recorded.statement.entity == entity)
703				}
704			};
705			if secret {
706				taking.taken.insert(id);
707			} else {
708				others.insert(id);
709			}
710		}
711		Ok((!others.is_empty()).then(|| Operation::retract(entity, others)))
712	}
713
714	/// Whether an operation governs the space ([`Kind::Governing`]): sets a field that
715	/// governs it, or retracts or replaces a statement of such a field that the state holds.
716	/// A change that governs the space holds nothing else: no retraction of secret
717	/// statements, as no statement that governs is secret.
718	///
719	/// # Errors
720	///
721	/// Returns an error if the storage of the state cannot be read.
722	pub fn governs(&self, operation: &Operation) -> Result<bool, S::Error> {
723		let asserted = match operation {
724			Operation::Assert { statement, .. } => Some(&statement.field),
725			Operation::RetractSecret { .. } => return Ok(false),
726			_ => None,
727		};
728		if asserted.is_some_and(fields::is_governing) {
729			return Ok(true);
730		}
731		for &id in operation.superseded().into_iter().flatten() {
732			if self
733				.state
734				.statement(id)?
735				.is_some_and(|statement| fields::is_governing(&statement.field))
736			{
737				return Ok(true);
738			}
739		}
740		Ok(false)
741	}
742
743	/// Receives a change from another replica, with its payload and key if they came with
744	/// it. Accepts it if its parents are all accepted, together with the waiting changes it
745	/// completes; otherwise the change waits for its parents. An accepted change's operations
746	/// are applied once its payload and key are there. A payload or key that is not the
747	/// change's is dropped, and the change waits for the right one. The clock takes a
748	/// change's timestamp into account only once the change is accepted.
749	///
750	/// # Errors
751	///
752	/// Returns an error, and leaves the log unchanged, if the change belongs to another
753	/// space, its signature is not valid, it would govern the space and do something else
754	/// too, its timestamp is too far ahead of the wall clock, or too many changes wait
755	/// already. Returns an error, and remembers the change as rejected for good, if the
756	/// change is not later than its parents, purges what it does not build on or what
757	/// governs the space, or one of its parents was rejected.
758	pub fn receive(
759		&mut self,
760		parcel: Parcel,
761		keys: &SpaceKeys,
762		wall_millis: u64,
763	) -> Result<Received, LogError> {
764		self.take(parcel, keys, wall_millis, Signature::Check, false)
765	}
766
767	/// Receives a change that this replica accepted or kept waiting before, from its own
768	/// storage: like [`Log::receive`], without the checks that were made when the change
769	/// first arrived and need not be made again: its signature, which is slow to check,
770	/// and its timestamp against the wall clock. [`Log::forged`] checks the signatures.
771	/// `covered` says whether the storage holds the change's operations already: if so,
772	/// applying them leaves the storage as it is, and they are not among those that
773	/// [`Log::take_applied`] gives.
774	///
775	/// # Errors
776	///
777	/// Returns the errors of [`Log::receive`], other than the signature's and the
778	/// clock's.
779	pub fn restore(
780		&mut self,
781		parcel: Parcel,
782		keys: &SpaceKeys,
783		covered: bool,
784	) -> Result<Received, LogError> {
785		self.take(parcel, keys, u64::MAX, Signature::Trusted, covered)
786	}
787
788	/// Receives the sealed payload of a change that the log holds, and applies the change's
789	/// operations if it is accepted and its key is there too. Returns whether the log kept
790	/// the payload, which it does unless it had it already.
791	///
792	/// # Errors
793	///
794	/// Returns an error if the log does not hold the change, or the payload is not the
795	/// change's.
796	pub fn receive_payload(
797		&mut self,
798		id: ChangeId,
799		payload: SealedPayload,
800		keys: &SpaceKeys,
801	) -> Result<bool, LogError> {
802		self.check_storage()?;
803		self.applied.clear();
804		self.destroyed = Destroyed::default();
805		let kept = self.add_payload(id, payload, keys)?;
806		self.check_storage()?;
807		Ok(kept)
808	}
809
810	/// Keeps the sealed payload of a change, as [`Log::receive_payload`] says, adding what
811	/// it applies to what the last call applied.
812	fn add_payload(
813		&mut self,
814		id: ChangeId,
815		payload: SealedPayload,
816		keys: &SpaceKeys,
817	) -> Result<bool, LogError> {
818		if let Some(error) = self.rejected.get(&id) {
819			return Err(error.clone());
820		}
821		if let Some(held) = self.waiting.get_mut(&id) {
822			if held.payload.is_some() {
823				return Ok(false);
824			}
825			if payload.hash() != *held.change.payload_hash() {
826				return Err(LogError::OtherPayload);
827			}
828			held.payload = Some(payload);
829			return Ok(true);
830		}
831		if self.read(self.history.is_change_purged(id))? {
832			return Ok(false);
833		}
834		let Some(mut accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
835			return Err(LogError::UnknownChange);
836		};
837		if accepted.payload.is_some() {
838			return Ok(false);
839		}
840		if payload.hash() != *accepted.change.payload_hash() {
841			return Err(LogError::OtherPayload);
842		}
843		accepted.payload = Some(payload);
844		self.store(&accepted)?;
845		self.complete(id, keys)?;
846		Ok(true)
847	}
848
849	/// Receives a wrapped key of a change that the log holds, and applies the change's
850	/// operations if it is accepted and its payload is there too. A replica that cannot open
851	/// the key yet keeps a few. Returns whether the log kept the key.
852	///
853	/// # Errors
854	///
855	/// Returns an error if the log does not hold the change, or `keys` hold the space key
856	/// the key needs and it is not the change's.
857	pub fn receive_change_key(
858		&mut self,
859		id: ChangeId,
860		key: WrappedChangeKey,
861		keys: &SpaceKeys,
862	) -> Result<bool, LogError> {
863		self.check_storage()?;
864		self.applied.clear();
865		self.destroyed = Destroyed::default();
866		let kept = self.add_change_key(id, key, keys)?;
867		self.check_storage()?;
868		Ok(kept)
869	}
870
871	/// Keeps a wrapped key of a change, as [`Log::receive_change_key`] says, adding what it
872	/// applies to what the last call applied.
873	fn add_change_key(
874		&mut self,
875		id: ChangeId,
876		key: WrappedChangeKey,
877		keys: &SpaceKeys,
878	) -> Result<bool, LogError> {
879		if let Some(error) = self.rejected.get(&id) {
880			return Err(error.clone());
881		}
882		if let Some(held) = self.waiting.get_mut(&id) {
883			return keep_key(&held.change, &mut held.keys, key, keys);
884		}
885		if self.read(self.history.is_change_purged(id))? {
886			return Ok(false);
887		}
888		let Some(mut accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
889			return Err(LogError::UnknownChange);
890		};
891		if !keep_key(&accepted.change, &mut accepted.keys, key, keys)? {
892			return Ok(false);
893		}
894		self.store(&accepted)?;
895		self.complete(id, keys)?;
896		Ok(true)
897	}
898
899	/// Keeps what the log has of an accepted change in its history.
900	fn store(&mut self, accepted: &Accepted) -> Result<(), LogError> {
901		let updated = self.history.update(
902			accepted.change.id(),
903			accepted.payload.as_ref(),
904			&accepted.keys,
905			accepted.status,
906		);
907		self.read(updated)
908	}
909
910	/// Applies the operations of every accepted change that `keys` let the log read now,
911	/// for example after the replica received an older space key.
912	///
913	/// # Errors
914	///
915	/// Returns [`LogError::Storage`] if reading or writing the storage failed.
916	pub fn open_changes(&mut self, keys: &SpaceKeys) -> Result<(), LogError> {
917		let pending = self.read(self.history.pending())?;
918		self.open_changes_of(pending, keys)
919	}
920
921	/// Applies the operations of these accepted changes, if they are pending and `keys` let
922	/// the log read them now.
923	///
924	/// # Errors
925	///
926	/// Returns [`LogError::Storage`] if reading or writing the storage failed.
927	pub fn open_changes_of(
928		&mut self,
929		changes: impl IntoIterator<Item = ChangeId>,
930		keys: &SpaceKeys,
931	) -> Result<(), LogError> {
932		self.check_storage()?;
933		self.applied.clear();
934		self.destroyed = Destroyed::default();
935		for id in changes {
936			self.complete(id, keys)?;
937		}
938		self.check_storage()
939	}
940
941	/// The changes, accepted or waiting, whose signatures are not valid, or that the
942	/// history cannot read, with why, ordered by ID: none, unless the storage that the log
943	/// read them from was damaged or tampered with. One that cannot be read does not keep
944	/// the others from being checked.
945	///
946	/// # Errors
947	///
948	/// Returns an error if the history cannot list its changes.
949	pub fn forged(&self) -> Result<Vec<Forged<S::Error>>, S::Error> {
950		let mut forged: Vec<Forged<S::Error>> = self
951			.waiting
952			.values()
953			.map(|held| &held.change)
954			.filter(|change| change.verify().is_err())
955			.map(|change| (change.id(), None))
956			.collect();
957		for id in self.history.ids()? {
958			match self.history.change(id) {
959				Ok(Some(change)) if change.verify().is_err() => forged.push((id, None)),
960				Ok(_) => {}
961				Err(error) => forged.push((id, Some(error))),
962			}
963		}
964		forged.sort_unstable_by_key(|(id, _)| *id);
965		Ok(forged)
966	}
967
968	/// Receives a change, checking its signature or trusting it.
969	fn take(
970		&mut self,
971		parcel: Parcel,
972		keys: &SpaceKeys,
973		wall_millis: u64,
974		signature: Signature,
975		covered: bool,
976	) -> Result<Received, LogError> {
977		self.check_storage()?;
978		self.applied.clear();
979		self.destroyed = Destroyed::default();
980		let id = parcel.id();
981		if let Some(error) = self.rejected.get(&id) {
982			return Err(error.clone());
983		}
984		if self.waiting.contains_key(&id) || self.read(self.history.contains(id))? {
985			return self.take_parts(parcel, keys);
986		}
987		let change = &parcel.change;
988		if change.space() != self.space {
989			return Err(LogError::OtherSpace);
990		}
991		if signature == Signature::Check {
992			change.verify()?;
993		}
994		if change.kind() == Kind::Governing
995			&& (!change.sealed().is_empty() || change.purges_or_restores())
996		{
997			return Err(LogError::MixedGoverning);
998		}
999		// Every replica reads every governing change, wrapped with the space's first key,
1000		// which it holds: one wrapped with another key could be read by some replicas and not
1001		// by others, and decide otherwise on each. The header decides, so it is rejected for
1002		// good, with what builds on it; one that this replica kept before, from a draft of
1003		// the formats, stays.
1004		if signature == Signature::Check && change.kind() == Kind::Governing && change.epoch() != 0
1005		{
1006			self.rejected.insert(id, LogError::GoverningEpoch);
1007			return Err(LogError::GoverningEpoch);
1008		}
1009		self.clock.check(change.timestamp(), wall_millis)?;
1010		if change
1011			.parents()
1012			.iter()
1013			.any(|parent| self.rejected.contains_key(parent))
1014		{
1015			self.rejected.insert(id, LogError::RejectedParent);
1016			return Err(LogError::RejectedParent);
1017		}
1018		self.check_governed(id, &parcel, keys, signature)?;
1019		let mut held = held(parcel);
1020		// A payload or key that is not the change's is dropped.
1021		if held
1022			.payload
1023			.as_ref()
1024			.is_some_and(|payload| payload.hash() != *held.change.payload_hash())
1025		{
1026			held.payload = None;
1027		}
1028		if keys.get(held.change.epoch()).is_some() {
1029			let change = &held.change;
1030			held.keys.retain(|key| key.unwrap(change, keys).is_some());
1031			held.keys.truncate(1);
1032		} else {
1033			let mut distinct = Vec::new();
1034			for key in held.keys.drain(..) {
1035				if !distinct.contains(&key) && distinct.len() < WRAPPED_KEYS_PER_CHANGE {
1036					distinct.push(key);
1037				}
1038			}
1039			held.keys = distinct;
1040		}
1041		if !self.parents_accepted(&held.change)? {
1042			if self.waiting.len() >= self.waiting_limit {
1043				return Err(LogError::TooManyWaiting);
1044			}
1045			for parent in held.change.parents() {
1046				if !self.read(self.history.contains(*parent))? {
1047					self.waiting_on.entry(*parent).or_default().insert(id);
1048				}
1049			}
1050			if covered {
1051				self.covered.insert(id);
1052			}
1053			self.waiting.insert(id, held);
1054			return Ok(Received::Waiting);
1055		}
1056
1057		match self.check_accepted(&held.change) {
1058			Ok(()) => {}
1059			Err(LogError::Storage) => return Err(LogError::Storage),
1060			Err(error) => {
1061				self.reject(id, error.clone());
1062				return Err(error);
1063			}
1064		}
1065		self.clock.observe(held.change.timestamp(), wall_millis)?;
1066		if covered {
1067			self.covered.insert(id);
1068		}
1069		self.accept(held, keys)?;
1070		let mut accepted = vec![id];
1071		accepted.extend(self.accept_waiting(id, keys, wall_millis)?);
1072		self.check_storage()?;
1073		Ok(Received::Accepted(accepted))
1074	}
1075
1076	/// Checks a change from elsewhere against who may write to the space: a space whose
1077	/// first change governs it has that one first change, and takes no change of a key that
1078	/// no governing change lists.
1079	fn check_governed(
1080		&mut self,
1081		id: ChangeId,
1082		parcel: &Parcel,
1083		keys: &SpaceKeys,
1084		signature: Signature,
1085	) -> Result<(), LogError> {
1086		let change = &parcel.change;
1087		// A space whose first change must govern it has that one first change, which does;
1088		// another space takes any number of changes without parents, whatever order they
1089		// come in.
1090		if change.parents().is_empty()
1091			&& self
1092				.expected_roots
1093				.as_ref()
1094				.is_some_and(|expected| !expected.contains(&id))
1095			&& self.read(self.history.count())? == 0
1096		{
1097			return Err(LogError::UnexpectedRoot);
1098		}
1099		if change.parents().is_empty() && self.expects_governed {
1100			let refused = if change.kind() != Kind::Governing {
1101				Some(LogError::UngovernedRoot)
1102			} else if self.read(self.history.count())? > 0 {
1103				Some(LogError::SecondRoot)
1104			} else {
1105				None
1106			};
1107			if let Some(error) = refused {
1108				self.rejected.insert(id, error.clone());
1109				return Err(error);
1110			}
1111		}
1112		// A change from elsewhere by a key that no governing change lists is not kept, so
1113		// that nobody can fill a replica with changes that never count. It is taken once a
1114		// listing of its key arrives, as sync sends it again; a key's listing of itself by a
1115		// recovery code is taken where the replica holds the code's statement.
1116		let first = change.parents().is_empty() && change.kind() == Kind::Governing;
1117		if signature == Signature::Check && !first {
1118			let known = self.governance(keys)?.is_known(change.author().as_bytes());
1119			if !known && !self.lists_itself_by_code(parcel, keys)? {
1120				return Err(LogError::UnknownAuthor);
1121			}
1122		}
1123		Ok(())
1124	}
1125
1126	/// Whether a change lists its own author by a recovery code that a governing change the
1127	/// replica can read names, as its payload, which the keys the replica holds open, says:
1128	/// a new device listed by a code introduces itself so
1129	/// ([Log](../../../docs/spec/log.md#8-which-changes-count)).
1130	fn lists_itself_by_code(&self, parcel: &Parcel, keys: &SpaceKeys) -> Result<bool, LogError> {
1131		let change = &parcel.change;
1132		if change.kind() != Kind::Governing {
1133			return Ok(false);
1134		}
1135		// Only the change's own payload says what it does.
1136		let Some(payload) = parcel
1137			.payload
1138			.as_ref()
1139			.filter(|payload| payload.hash() == *change.payload_hash())
1140		else {
1141			return Ok(false);
1142		};
1143		let Some(opened) = parcel
1144			.keys
1145			.iter()
1146			.find_map(|key| change.open_checked(payload, key, keys).ok())
1147		else {
1148			return Ok(false);
1149		};
1150		if !holds_only_governing(&opened.operations) || !opened.restated.is_empty() {
1151			return Ok(false);
1152		}
1153		let mut fact = Fact::read(change, &opened.operations);
1154		let governance = self.governance(keys)?;
1155		if governance.governed() {
1156			fact.keep_signed();
1157		}
1158		Ok(governance.takes_listing_by_code(&fact))
1159	}
1160
1161	/// Takes what came with a change that the log holds, which may be what the log lacks;
1162	/// what is not the change's is dropped.
1163	fn take_parts(&mut self, parcel: Parcel, keys: &SpaceKeys) -> Result<Received, LogError> {
1164		let id = parcel.id();
1165		let mut kept = false;
1166		if let Some(payload) = parcel.payload {
1167			match self.add_payload(id, payload, keys) {
1168				Ok(added) => kept |= added,
1169				Err(LogError::Storage) => return Err(LogError::Storage),
1170				Err(_) => {}
1171			}
1172		}
1173		for key in parcel.keys {
1174			match self.add_change_key(id, key, keys) {
1175				Ok(added) => kept |= added,
1176				Err(LogError::Storage) => return Err(LogError::Storage),
1177				Err(_) => {}
1178			}
1179		}
1180		self.check_storage()?;
1181		Ok(if kept {
1182			Received::Completed
1183		} else {
1184			Received::Duplicate
1185		})
1186	}
1187
1188	/// The decrypted payloads of the changes whose operations the last call that makes or
1189	/// takes changes, payloads or keys applied, in the order it applied them, without those
1190	/// that the storage covered; each call forgets those of the one before.
1191	pub fn take_applied(&mut self) -> Vec<(ChangeId, Payload)> {
1192		std::mem::take(&mut self.applied)
1193	}
1194
1195	/// What the purges that the last call that makes or takes changes, payloads or keys
1196	/// acted on destroyed: only those of changes that count, also of one that came to count
1197	/// then. Each call forgets what the one before destroyed.
1198	pub fn take_destroyed(&mut self) -> Destroyed {
1199		std::mem::take(&mut self.destroyed)
1200	}
1201
1202	/// The payload of an accepted change, decrypted with `keys`, if the log has the payload
1203	/// and a key for it.
1204	///
1205	/// # Errors
1206	///
1207	/// Returns an error if `keys` lack the space key that the change's key was wrapped with,
1208	/// or the payload does not open or does not have the form of a payload, or the history
1209	/// cannot be read.
1210	pub fn payload(&self, id: ChangeId, keys: &SpaceKeys) -> Result<Option<Payload>, LogError> {
1211		match self.read(self.history.get(id))? {
1212			Some(accepted) => read_payload(&accepted, keys),
1213			None => Ok(None),
1214		}
1215	}
1216
1217	/// The sealed payload that the log has for a change, accepted or waiting.
1218	///
1219	/// # Errors
1220	///
1221	/// Returns an error if the history cannot be read.
1222	pub fn sealed_payload(&self, id: ChangeId) -> Result<Option<SealedPayload>, S::Error> {
1223		Ok(self.parcel(id)?.and_then(|parcel| parcel.payload))
1224	}
1225
1226	/// The wrapped keys that the log has for a change, accepted or waiting: one that it
1227	/// knows to be good, or a few that it cannot check yet.
1228	///
1229	/// # Errors
1230	///
1231	/// Returns an error if the history cannot be read.
1232	pub fn change_keys_of(&self, id: ChangeId) -> Result<Vec<WrappedChangeKey>, S::Error> {
1233		Ok(self.parcel(id)?.map_or_default(|parcel| parcel.keys))
1234	}
1235
1236	/// An accepted or waiting change, with its sealed payload and wrapped keys as far as the
1237	/// log has them.
1238	///
1239	/// # Errors
1240	///
1241	/// Returns an error if the history cannot be read.
1242	pub fn parcel(&self, id: ChangeId) -> Result<Option<Parcel>, S::Error> {
1243		if let Some(held) = self.waiting.get(&id) {
1244			return Ok(Some(held.parcel()));
1245		}
1246		Ok(self.history.get(id)?.map(|accepted| parcel_of(&accepted)))
1247	}
1248
1249	/// The accepted changes with their sealed payloads and wrapped keys, ordered by ID, for
1250	/// other replicas.
1251	///
1252	/// # Errors
1253	///
1254	/// Returns an error if the history cannot be read.
1255	pub fn parcels(&self) -> Result<Vec<Parcel>, S::Error> {
1256		let mut parcels = Vec::new();
1257		for id in self.history.ids()? {
1258			if let Some(accepted) = self.history.get(id)? {
1259				parcels.push(parcel_of(&accepted));
1260			}
1261		}
1262		Ok(parcels)
1263	}
1264
1265	/// Every accepted change in short, for reconciling with another replica, ordered by ID.
1266	///
1267	/// # Errors
1268	///
1269	/// Returns an error if the history cannot be read.
1270	pub fn summaries(&self) -> Result<Vec<Summary>, S::Error> {
1271		self.history.summaries()
1272	}
1273
1274	/// Whether the operations of an accepted change are applied, or its payload found not to
1275	/// have the form it must: whether it adds nothing more.
1276	///
1277	/// # Errors
1278	///
1279	/// Returns an error if the history cannot be read.
1280	pub fn is_complete(&self, id: ChangeId) -> Result<bool, S::Error> {
1281		Ok(self
1282			.history
1283			.get(id)?
1284			.is_some_and(|accepted| accepted.status != Status::Pending))
1285	}
1286
1287	/// Whether an accepted change is set aside: kept and passed on, but not applied, as its
1288	/// author is not listed, or was revoked by a replica that did not have it.
1289	///
1290	/// # Errors
1291	///
1292	/// Returns an error if the history cannot be read.
1293	pub fn is_set_aside(&self, id: ChangeId) -> Result<bool, S::Error> {
1294		Ok(self
1295			.history
1296			.get(id)?
1297			.is_some_and(|accepted| accepted.status == Status::SetAside))
1298	}
1299
1300	/// The accepted changes that are set aside, ordered by ID.
1301	///
1302	/// # Errors
1303	///
1304	/// Returns an error if the history cannot be read.
1305	pub fn set_aside_changes(&self) -> Result<Vec<ChangeId>, S::Error> {
1306		self.history.set_aside()
1307	}
1308
1309	/// Whether the space's first change governs it, so that only the changes of the keys it
1310	/// lists count.
1311	///
1312	/// # Errors
1313	///
1314	/// Returns [`LogError::Storage`] if the history cannot be read.
1315	pub fn is_governed(&self, keys: &SpaceKeys) -> Result<bool, LogError> {
1316		Ok(self.governance(keys)?.governed())
1317	}
1318
1319	/// The space's first change, if it governs the space.
1320	///
1321	/// # Errors
1322	///
1323	/// Returns an error if the history cannot be read.
1324	pub fn root(&self) -> Result<Option<ChangeId>, S::Error> {
1325		for id in self.history.governing()? {
1326			if self
1327				.history
1328				.change(id)?
1329				.is_some_and(|change| change.parents().is_empty())
1330			{
1331				return Ok(Some(id));
1332			}
1333		}
1334		Ok(None)
1335	}
1336
1337	/// The counting changes that revoke a key, ordered by ID, or every counting revocation
1338	/// if `key` is `None`.
1339	///
1340	/// # Errors
1341	///
1342	/// Returns [`LogError::Storage`] if the history cannot be read.
1343	pub fn revocations_of(
1344		&self,
1345		key: Option<&VerifyingKey>,
1346		keys: &SpaceKeys,
1347	) -> Result<Vec<ChangeId>, LogError> {
1348		let governance = self.governance(keys)?;
1349		Ok(match key {
1350			Some(key) => governance
1351				.revocations_of(key.as_bytes())
1352				.map_or_default(|revocations| revocations.iter().copied().collect()),
1353			None => governance.revocations().into_iter().collect(),
1354		})
1355	}
1356
1357	/// Every counting change that revokes a replica, ordered by ID.
1358	///
1359	/// # Errors
1360	///
1361	/// Returns [`LogError::Storage`] if the history cannot be read.
1362	pub fn revocations(&self, keys: &SpaceKeys) -> Result<Vec<ChangeId>, LogError> {
1363		self.revocations_of(None, keys)
1364	}
1365
1366	/// Whether a key is revoked by a change that counts.
1367	///
1368	/// # Errors
1369	///
1370	/// Returns [`LogError::Storage`] if the history cannot be read.
1371	pub fn is_revoked(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<bool, LogError> {
1372		Ok(self
1373			.governance(keys)?
1374			.revocations_of(key.as_bytes())
1375			.is_some())
1376	}
1377
1378	/// Whether a revoked key would stay if it revoked back the keys that revoked it, as of
1379	/// two that revoke each other: a replica takes from it what it made without knowing of
1380	/// its revocation, where that revocation of its own may be, and sends it nothing
1381	/// ([Sync](../../../docs/spec/sync.md#4-who-syncs)).
1382	///
1383	/// # Errors
1384	///
1385	/// Returns [`LogError::Storage`] if the history cannot be read.
1386	pub fn may_revoke_back(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<bool, LogError> {
1387		Ok(self.governance(keys)?.may_revoke_back(key.as_bytes()))
1388	}
1389
1390	/// Whether a governing change that counts lists a key, or the space's first change does
1391	/// not govern it.
1392	///
1393	/// # Errors
1394	///
1395	/// Returns [`LogError::Storage`] if the history cannot be read.
1396	pub fn is_listed(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<bool, LogError> {
1397		let governance = self.governance(keys)?;
1398		Ok(!governance.governed() || governance.is_listed(key.as_bytes()))
1399	}
1400
1401	/// Whether the space has members: whether its first change gives a role, as that of
1402	/// every space other than a user's personal one does. Only the listings that the listed
1403	/// keys signed count there ([`nibkeep_governance::Listing`]).
1404	///
1405	/// # Errors
1406	///
1407	/// Returns [`LogError::Storage`] if the history cannot be read.
1408	pub fn has_members(&self, keys: &SpaceKeys) -> Result<bool, LogError> {
1409		Ok(self.governance(keys)?.members())
1410	}
1411
1412	/// The members of a space with members, each with the role that the counting governing
1413	/// changes give them now: the lowest of those that no other of them builds on. Empty for
1414	/// a space without members.
1415	///
1416	/// # Errors
1417	///
1418	/// Returns [`LogError::Storage`] if the history cannot be read.
1419	pub fn member_roles(
1420		&self,
1421		keys: &SpaceKeys,
1422	) -> Result<BTreeMap<nibkeep_base::EntityId, Role>, LogError> {
1423		Ok(self.governance(keys)?.roles_now())
1424	}
1425
1426	/// Whether a space with members allows AI agents now, as its counting governing changes
1427	/// say: an AI agent's listing counts there only where they allow them. `false` for a
1428	/// space without members, which has no admins to allow them.
1429	///
1430	/// # Errors
1431	///
1432	/// Returns [`LogError::Storage`] if the history cannot be read.
1433	pub fn allows_ai_agents(&self, keys: &SpaceKeys) -> Result<bool, LogError> {
1434		Ok(self.governance(keys)?.allows_ai_agents())
1435	}
1436
1437	/// Whether a key is an AI agent's: whether the governing change that first listed it
1438	/// marks its replica as one ([Log](../../../docs/spec/log.md#8-which-changes-count)). Its
1439	/// changes then count only if they write what an AI agent may, and purge, seal and govern
1440	/// nothing.
1441	///
1442	/// # Errors
1443	///
1444	/// Returns [`LogError::Storage`] if the history cannot be read.
1445	pub fn is_ai_agent(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<bool, LogError> {
1446		Ok(self.governance(keys)?.is_ai_agent(key.as_bytes()))
1447	}
1448
1449	/// The choice of the device whose key is `key` that stands in a space with members, of
1450	/// those that counting changes state: its number and whether it holds the space; none if
1451	/// none states one, or the space has no members, where choices count for nothing
1452	/// ([technical design](../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
1453	///
1454	/// # Errors
1455	///
1456	/// Returns [`LogError::Storage`] if the history cannot be read.
1457	pub fn standing_choice(
1458		&self,
1459		key: &VerifyingKey,
1460		keys: &SpaceKeys,
1461	) -> Result<Option<(u64, bool)>, LogError> {
1462		let governance = self.governance(keys)?;
1463		Ok(governance
1464			.view()
1465			.filter(|_| governance.governed())
1466			.and_then(|view| view.standing_choice(key.as_bytes())))
1467	}
1468
1469	/// Whether the device whose key is `key` holds the space by its choices: whether its
1470	/// choice that stands holds it, or none does, as [`Log::standing_choice`] finds it.
1471	///
1472	/// # Errors
1473	///
1474	/// Returns [`LogError::Storage`] if the history cannot be read.
1475	pub fn holds_space(&self, key: &VerifyingKey, keys: &SpaceKeys) -> Result<bool, LogError> {
1476		let governance = self.governance(keys)?;
1477		Ok(governance
1478			.view()
1479			.filter(|_| governance.governed())
1480			.is_none_or(|view| view.holds_now(key.as_bytes())))
1481	}
1482
1483	/// Whether the accepted change `ancestor` is `of` or one of its ancestors.
1484	///
1485	/// # Errors
1486	///
1487	/// Returns [`LogError::Storage`] if the history cannot be read.
1488	pub fn is_ancestor_of(&self, ancestor: ChangeId, of: ChangeId) -> Result<bool, LogError> {
1489		self.had(ancestor, of)
1490	}
1491
1492	/// The wrapped record keys this replica has for a statement.
1493	#[must_use]
1494	pub fn wrapped_keys_of(&self, statement: StatementId) -> &[WrappedKey] {
1495		self.wrapped.get(&statement).map_or(&[], Vec::as_slice)
1496	}
1497
1498	/// Receives a wrapped record key of a secret statement from another replica, and opens
1499	/// the statement if `keys` hold the secrets key. A key for a purged statement is
1500	/// ignored.
1501	///
1502	/// # Errors
1503	///
1504	/// Returns [`LogError::Storage`] if the history cannot be read.
1505	pub fn receive_wrapped_key(
1506		&mut self,
1507		statement: StatementId,
1508		wrapped: WrappedKey,
1509		keys: &SpaceKeys,
1510	) -> Result<(), LogError> {
1511		if self.read(self.history.is_statement_purged(statement))? {
1512			return Ok(());
1513		}
1514		let candidates = self.wrapped.entry(statement).or_default();
1515		if !candidates.contains(&wrapped) && candidates.len() < WRAPPED_KEYS_PER_STATEMENT {
1516			candidates.push(wrapped);
1517		}
1518		self.open(statement, keys, &mut BTreeMap::new())
1519	}
1520
1521	/// The wrapped record keys this replica has, for other replicas.
1522	pub fn wrapped_keys(&self) -> impl Iterator<Item = (StatementId, &WrappedKey)> {
1523		self.wrapped
1524			.iter()
1525			.flat_map(|(&statement, keys)| keys.iter().map(move |key| (statement, key)))
1526	}
1527
1528	/// Opens every sealed statement that `keys` and the wrapped record keys allow, after
1529	/// the person has confirmed.
1530	///
1531	/// # Errors
1532	///
1533	/// Returns [`LogError::Storage`] if the history cannot be read.
1534	pub fn unlock_secrets(&mut self, keys: &SpaceKeys) -> Result<(), LogError> {
1535		let sealed = self.read(self.history.sealed())?;
1536		// Each change that holds sealed statements is decrypted once.
1537		let mut payloads = BTreeMap::new();
1538		for statement in sealed {
1539			self.open(statement, keys, &mut payloads)?;
1540		}
1541		let secret: Vec<Hash> = self.secret_candidates.iter().copied().collect();
1542		for sealed in secret {
1543			self.open_blob_key(sealed, keys);
1544		}
1545		Ok(())
1546	}
1547
1548	/// Forgets the sealed statements this replica has opened, and the secret blob keys, so
1549	/// that the log holds no secret values until they are unlocked again.
1550	pub fn lock_secrets(&mut self) {
1551		self.state.storage_mut().forget_all();
1552		for sealed in std::mem::take(&mut self.secret_blobs) {
1553			self.forget_blob_key(&sealed);
1554		}
1555	}
1556
1557	/// Restores what purges destroyed, as `restores` names it: makes a change that restores it,
1558	/// signed by `author`, and takes it in. What it names is no longer purged, unless a purge
1559	/// that the change does not build on purges it too: a change waits for its payload and
1560	/// key again, and a statement or a blob for its wrapped key, which a replica that kept
1561	/// them gives back, as [`Destroyed::restored`] says
1562	/// ([technical design: copies that wait]). The change holds nothing else, and counts
1563	/// only where its author may purge what it restores.
1564	///
1565	/// [technical design: copies that wait]: ../../../docs/Technical-design.md#911-copies-that-wait
1566	///
1567	/// # Errors
1568	///
1569	/// Returns [`LogError::InvalidPurge`] if it would restore nothing, or what this replica's
1570	/// history does not hold; [`LogError::CannotRestore`] if the change would not count, as
1571	/// the author's role does not allow it, in which case nothing is made; and another error
1572	/// if the clock has run out of timestamps.
1573	pub fn restore_purged(
1574		&mut self,
1575		author: &SigningKey,
1576		keys: &SpaceKeys,
1577		restores: Restores,
1578		wall_millis: u64,
1579		rng: &mut impl CryptoRng,
1580	) -> Result<Parcel, LogError> {
1581		self.check_storage()?;
1582		if restores.is_empty() {
1583			return Err(LogError::InvalidPurge);
1584		}
1585		for &change in &restores.changes {
1586			if !self.read(self.history.contains(change))? {
1587				return Err(LogError::InvalidPurge);
1588			}
1589		}
1590		for &statement in &restores.statements {
1591			if self.read(self.history.holder(statement))?.is_none() {
1592				return Err(LogError::InvalidPurge);
1593			}
1594		}
1595		self.applied.clear();
1596		self.destroyed = Destroyed::default();
1597		let heads = self.read(self.history.heads())?;
1598		let timestamp = self.clock.now(wall_millis)?;
1599		let mut draft = Draft::new(heads, timestamp, Payload::default());
1600		draft.restores = restores;
1601		let parcel = Change::create(self.space, keys, author, &draft, rng);
1602		// One that would be set aside is never made: it could come to count later, when
1603		// nobody asks for it.
1604		let counts = {
1605			let governance = self.governance(keys)?;
1606			self.counts_now(&parcel.change, None, &governance, |_| false)?
1607		};
1608		if !counts {
1609			return Err(LogError::CannotRestore);
1610		}
1611		self.accept(held(parcel.clone()), keys)?;
1612		self.check_storage()?;
1613		Ok(parcel)
1614	}
1615
1616	/// Purges statements: makes a change that destroys, everywhere, the record key of each
1617	/// secret one, and the key and payload of the change that asserted each other one,
1618	/// stating again everything else that those changes held. What a purged statement
1619	/// replaced stays replaced, so purging never brings back an older value.
1620	///
1621	/// # Errors
1622	///
1623	/// Returns an error if a statement is not one that this replica can purge: unknown, or
1624	/// asserted in a change that governs the space or whose payload it cannot read; or if the
1625	/// clock has run out of timestamps.
1626	pub fn purge(
1627		&mut self,
1628		author: &SigningKey,
1629		keys: &SpaceKeys,
1630		statements: impl IntoIterator<Item = StatementId>,
1631		wall_millis: u64,
1632		rng: &mut impl CryptoRng,
1633	) -> Result<Parcel, LogError> {
1634		self.purge_with_blobs(author, keys, statements, (&[], false), wall_millis, rng)
1635	}
1636
1637	/// Purges statements as [`Log::purge`] does, and in the same change the blobs with the
1638	/// content hashes `contents`: every key of the kind `secret` says that this replica has
1639	/// opened for them, secret blob keys or ordinary ones, as [`Log::purge_blob`] destroys
1640	/// them. Content that the replica has no such key for adds nothing.
1641	///
1642	/// # Errors
1643	///
1644	/// As [`Log::purge`].
1645	pub fn purge_with_blobs(
1646		&mut self,
1647		author: &SigningKey,
1648		keys: &SpaceKeys,
1649		statements: impl IntoIterator<Item = StatementId>,
1650		(contents, of_secrets): (&[Hash], bool),
1651		wall_millis: u64,
1652		rng: &mut impl CryptoRng,
1653	) -> Result<Parcel, LogError> {
1654		self.check_storage()?;
1655		let mut secret = BTreeSet::new();
1656		let mut ordinary = BTreeSet::new();
1657		for statement in statements {
1658			if self.read(self.history.holder(statement))?.is_some() {
1659				secret.insert(statement);
1660			} else {
1661				ordinary.insert(statement);
1662			}
1663		}
1664		let changes = self.asserting(&ordinary, keys)?;
1665		// What the purged changes held besides, by the change each part came from.
1666		let mut restating = Restating::default();
1667		for &change in &changes {
1668			let accepted = self
1669				.read(self.history.get(change))?
1670				.ok_or(LogError::CannotPurge)?;
1671			let payload = read_payload(&accepted, keys)?.ok_or(LogError::CannotPurge)?;
1672			let mut parts = vec![(change, payload.operations, payload.sealed)];
1673			parts.extend(
1674				payload
1675					.restated
1676					.into_iter()
1677					.map(|(source, part)| (source, part.operations, part.sealed)),
1678			);
1679			for (source, operations, sealed) in parts {
1680				let entry = restating.payload.restated.entry(source).or_default();
1681				entry.operations.extend(
1682					operations
1683						.into_iter()
1684						.filter_map(|operation| without(operation, &ordinary)),
1685				);
1686				for (id, envelope) in sealed {
1687					if secret.contains(&id) {
1688						continue;
1689					}
1690					if let Some(&hash) = accepted.change.sealed().get(&id) {
1691						restating.record_keys.insert(id, hash);
1692					}
1693					entry.sealed.insert(id, envelope);
1694				}
1695			}
1696		}
1697		restating
1698			.payload
1699			.restated
1700			.retain(|_, part| !part.is_empty());
1701		let blobs = contents
1702			.iter()
1703			.filter_map(|content| self.sealed_blobs.get(content))
1704			.flatten()
1705			.filter(|sealed| self.secret_blobs.contains(sealed) == of_secrets)
1706			.copied()
1707			.collect();
1708		let purges = Purges {
1709			changes,
1710			statements: secret,
1711			blobs,
1712		};
1713		self.commit_purges(author, keys, purges, restating, wall_millis, rng)
1714	}
1715
1716	/// The changes that purging these statements purges: every change that asserts one of
1717	/// them, which [`Log::purge`] purges and states again without them. Secret statements are
1718	/// purged through their record keys alone, and add none.
1719	///
1720	/// # Errors
1721	///
1722	/// Returns [`LogError::CannotPurge`] if a statement is not one that this replica can
1723	/// purge: unknown, or asserted in a change that governs the space or whose payload it
1724	/// cannot read; and [`LogError::Storage`] if the state or the history cannot be read.
1725	pub fn changes_to_purge(
1726		&self,
1727		statements: impl IntoIterator<Item = StatementId>,
1728		keys: &SpaceKeys,
1729	) -> Result<BTreeSet<ChangeId>, LogError> {
1730		let mut ordinary = BTreeSet::new();
1731		for statement in statements {
1732			if self.read(self.history.holder(statement))?.is_none() {
1733				ordinary.insert(statement);
1734			}
1735		}
1736		self.asserting(&ordinary, keys)
1737	}
1738
1739	/// The changes that assert any of these ordinary statements: the one that first did,
1740	/// every other that asserted it too, as devices that run one migration at once do, and
1741	/// the purges that state one again. Each must be one that a purge can purge.
1742	fn asserting(
1743		&self,
1744		statements: &BTreeSet<StatementId>,
1745		keys: &SpaceKeys,
1746	) -> Result<BTreeSet<ChangeId>, LogError> {
1747		let mut changes = BTreeSet::new();
1748		for &statement in statements {
1749			let origin = self
1750				.read(self.state.storage().get(statement))?
1751				.and_then(|recorded| recorded.change)
1752				.ok_or(LogError::CannotPurge)?;
1753			changes.insert(ChangeId::from_hash(origin));
1754			for again in self.read(self.state.storage().asserted_again(statement))? {
1755				changes.insert(ChangeId::from_hash(again));
1756			}
1757		}
1758		// Purges that state one again, which only they do besides the first.
1759		for id in self.read(self.history.purging())? {
1760			let Some(accepted) = self.read(self.history.get(id))? else {
1761				continue;
1762			};
1763			let Ok(Some(payload)) = read_payload(&accepted, keys) else {
1764				continue;
1765			};
1766			let restates = payload
1767				.restated
1768				.values()
1769				.flat_map(|restated| &restated.operations)
1770				.any(|operation| {
1771					matches!(operation, Operation::Assert { statement, .. } if statements.contains(&statement.id))
1772				});
1773			if restates {
1774				changes.insert(id);
1775			}
1776		}
1777		for &change in &changes {
1778			let purgeable = self
1779				.read(self.history.get(change))?
1780				.is_some_and(|accepted| {
1781					accepted.change.kind() == Kind::Ordinary && accepted.payload.is_some()
1782				});
1783			if !purgeable {
1784				return Err(LogError::CannotPurge);
1785			}
1786		}
1787		Ok(changes)
1788	}
1789
1790	/// The changes that were purged, ordered by ID.
1791	///
1792	/// # Errors
1793	///
1794	/// Returns an error if the history cannot be read.
1795	pub fn purged_changes(&self) -> Result<Vec<ChangeId>, S::Error> {
1796		self.history.purged_changes()
1797	}
1798
1799	/// Whether a change was purged: its key and payload destroyed.
1800	///
1801	/// # Errors
1802	///
1803	/// Returns an error if the history cannot be read.
1804	pub fn is_change_purged(&self, id: ChangeId) -> Result<bool, S::Error> {
1805		self.history.is_change_purged(id)
1806	}
1807
1808	/// Whether a secret statement was purged.
1809	///
1810	/// # Errors
1811	///
1812	/// Returns an error if the history cannot be read.
1813	pub fn is_purged(&self, statement: StatementId) -> Result<bool, S::Error> {
1814		self.history.is_statement_purged(statement)
1815	}
1816
1817	/// Whether a statement is secret: held sealed in an accepted change, whether or not
1818	/// this replica has opened it.
1819	///
1820	/// # Errors
1821	///
1822	/// Returns an error if the history cannot be read.
1823	pub fn is_sealed(&self, statement: StatementId) -> Result<bool, S::Error> {
1824		Ok(self.history.holder(statement)?.is_some())
1825	}
1826
1827	/// Adds the key of a blob that this replica sealed, wrapped with the newest space key, so
1828	/// that the replica can read the blob and pass the key on. The key of a purged sealed
1829	/// blob is ignored.
1830	///
1831	/// # Errors
1832	///
1833	/// Returns [`LogError::Storage`] if the history cannot be read.
1834	pub fn add_blob_key(
1835		&mut self,
1836		content: Hash,
1837		sealed: Hash,
1838		key: Key,
1839		keys: &SpaceKeys,
1840		rng: &mut impl CryptoRng,
1841	) -> Result<(), LogError> {
1842		if self.blob_keys.contains_key(&sealed) || self.is_blob_purged_reading(&sealed)? {
1843			return Ok(());
1844		}
1845		let wrapped = WrappedBlobKey::wrap(self.space, &sealed, &content, &key, keys, rng);
1846		self.add_wrapped_blob_key(sealed, wrapped, (content, key), false);
1847		Ok(())
1848	}
1849
1850	/// Adds the key of a blob of a secret field that this replica sealed, wrapped with the
1851	/// newest secrets key inside the newest space key, so that only a replica that holds the
1852	/// secrets can read the blob, and every replica can pass the key on. The key of a purged
1853	/// sealed blob is ignored.
1854	///
1855	/// # Errors
1856	///
1857	/// Returns [`LogError::SecretsLocked`] if `keys` hold no secrets key, and
1858	/// [`LogError::Storage`] if the history cannot be read.
1859	pub fn add_secret_blob_key(
1860		&mut self,
1861		content: Hash,
1862		sealed: Hash,
1863		key: Key,
1864		keys: &SpaceKeys,
1865		rng: &mut impl CryptoRng,
1866	) -> Result<(), LogError> {
1867		if keys.newest_secrets().is_none() {
1868			return Err(LogError::SecretsLocked);
1869		}
1870		if self.blob_keys.contains_key(&sealed) || self.is_blob_purged_reading(&sealed)? {
1871			return Ok(());
1872		}
1873		let wrapped = WrappedBlobKey::wrap_secret(self.space, &sealed, &content, &key, keys, rng)
1874			.ok_or(LogError::SecretsLocked)?;
1875		self.secret_candidates.insert(sealed);
1876		self.add_wrapped_blob_key(sealed, wrapped, (content, key), true);
1877		Ok(())
1878	}
1879
1880	/// Keeps a blob key that this replica made, first among the wrapped keys of its blob,
1881	/// opened.
1882	fn add_wrapped_blob_key(
1883		&mut self,
1884		sealed: Hash,
1885		wrapped: WrappedBlobKey,
1886		opened: (Hash, Key),
1887		secret: bool,
1888	) {
1889		let candidates = self.wrapped_blob_keys.entry(sealed).or_default();
1890		candidates.insert(0, wrapped);
1891		candidates.truncate(WRAPPED_KEYS_PER_BLOB);
1892		self.keep_blob_key(sealed, opened, secret);
1893	}
1894
1895	/// Keeps a blob key opened, with the content hash it claims.
1896	fn keep_blob_key(&mut self, sealed: Hash, (content, key): (Hash, Key), secret: bool) {
1897		self.sealed_blobs.entry(content).or_default().insert(sealed);
1898		self.blob_keys.insert(sealed, (content, key));
1899		if secret {
1900			self.secret_blobs.insert(sealed);
1901		}
1902	}
1903
1904	/// Forgets an opened blob key, and keeps its wrapped keys.
1905	fn forget_blob_key(&mut self, sealed: &Hash) {
1906		self.secret_blobs.remove(sealed);
1907		if let Some((content, _)) = self.blob_keys.remove(sealed)
1908			&& let Some(sealed_blobs) = self.sealed_blobs.get_mut(&content)
1909		{
1910			sealed_blobs.remove(sealed);
1911			if sealed_blobs.is_empty() {
1912				self.sealed_blobs.remove(&content);
1913			}
1914		}
1915	}
1916
1917	/// The sealed blobs with a wrapped key in the form of a secret blob key: those whose keys
1918	/// unlocking the secrets may open or drop.
1919	pub fn sealed_with_secret_keys(&self) -> impl Iterator<Item = &Hash> {
1920		self.secret_candidates.iter()
1921	}
1922
1923	/// Whether the opened key of a sealed blob is a secret blob key: one of a blob of a
1924	/// secret field, which only a replica that holds the secrets opens.
1925	#[must_use]
1926	pub fn is_secret_blob(&self, sealed: &Hash) -> bool {
1927		self.secret_blobs.contains(sealed)
1928	}
1929
1930	/// Whether a sealed blob's key was destroyed, as the history says.
1931	fn is_blob_purged_reading(&self, sealed: &Hash) -> Result<bool, LogError> {
1932		self.read(self.history.is_blob_purged(sealed))
1933	}
1934
1935	/// Receives a wrapped blob key from another replica, and opens it if `keys` hold the
1936	/// space key it needs, and for a secret blob key the secrets key too. A wrapped key that
1937	/// does not open with the keys it names is dropped, and a key of a purged sealed blob is
1938	/// ignored. One whose space key the replica holds is kept even when the replica keeps the
1939	/// most it does for one blob, in place of one whose space key it lacks, so that wrapped
1940	/// keys it cannot check never crowd out a good one; a secret blob key that waits for the
1941	/// secrets is never replaced, as it may be the good one. A secret blob key that opens
1942	/// takes the place of an ordinary key opened for the same sealed blob: only a replica
1943	/// that holds the secrets can make one, and any replica of the space an ordinary one.
1944	///
1945	/// # Errors
1946	///
1947	/// Returns [`LogError::Storage`] if the history cannot be read.
1948	pub fn receive_blob_key(
1949		&mut self,
1950		sealed: Hash,
1951		wrapped: WrappedBlobKey,
1952		keys: &SpaceKeys,
1953	) -> Result<(), LogError> {
1954		if self.is_blob_purged_reading(&sealed)? {
1955			return Ok(());
1956		}
1957		let checkable = keys.get(wrapped.epoch()).is_some();
1958		let opened = if checkable {
1959			match wrapped.unwrap(self.space, &sealed, keys) {
1960				None => return Ok(()),
1961				Some(Unwrapped::Secret) => {
1962					self.secret_candidates.insert(sealed);
1963					None
1964				}
1965				Some(Unwrapped::Key {
1966					content,
1967					key,
1968					secret,
1969				}) => {
1970					if secret {
1971						self.secret_candidates.insert(sealed);
1972					}
1973					Some(((content, key), secret))
1974				}
1975			}
1976		} else {
1977			None
1978		};
1979		let space = self.space;
1980		let candidates = self.wrapped_blob_keys.entry(sealed).or_default();
1981		// A secret blob key that opens shows the sealed blob to be a secret one, sealed by a
1982		// replica that holds the secrets: its ordinary keys are forged.
1983		if matches!(opened, Some((_, true))) {
1984			candidates.retain(|candidate| {
1985				!matches!(
1986					candidate.unwrap(space, &sealed, keys),
1987					Some(Unwrapped::Key { secret: false, .. })
1988				)
1989			});
1990		}
1991		if !candidates.contains(&wrapped) {
1992			if candidates.len() < WRAPPED_KEYS_PER_BLOB {
1993				candidates.push(wrapped);
1994			} else if checkable
1995				&& let Some(unchecked) = candidates
1996					.iter()
1997					.position(|candidate| keys.get(candidate.epoch()).is_none())
1998			{
1999				candidates[unchecked] = wrapped;
2000			}
2001		}
2002		if let Some((opened, secret)) = opened {
2003			self.prefer_blob_key(sealed, opened, secret);
2004		}
2005		Ok(())
2006	}
2007
2008	/// Keeps a blob key opened for a sealed blob that has none opened yet, or, for a secret
2009	/// blob key, in place of an ordinary one.
2010	fn prefer_blob_key(&mut self, sealed: Hash, opened: (Hash, Key), secret: bool) {
2011		if !self.blob_keys.contains_key(&sealed) {
2012			self.keep_blob_key(sealed, opened, secret);
2013		} else if secret && !self.secret_blobs.contains(&sealed) {
2014			self.forget_blob_key(&sealed);
2015			self.keep_blob_key(sealed, opened, secret);
2016		}
2017	}
2018
2019	/// Opens the wrapped blob keys that `keys` allow, for example after the replica received
2020	/// an older space key, or unlocked its secrets.
2021	pub fn open_blob_keys(&mut self, keys: &SpaceKeys) {
2022		// Those opened with an ordinary key too, if they have other keys, which a new space
2023		// key may show to be secret ones.
2024		let unopened: Vec<Hash> = self
2025			.wrapped_blob_keys
2026			.iter()
2027			.filter(|(sealed, candidates)| {
2028				!self.secret_blobs.contains(*sealed)
2029					&& (!self.blob_keys.contains_key(*sealed) || candidates.len() > 1)
2030			})
2031			.map(|(sealed, _)| *sealed)
2032			.collect();
2033		for sealed in unopened {
2034			self.open_blob_key(sealed, keys);
2035		}
2036	}
2037
2038	/// The wrapped keys this replica has for a sealed blob.
2039	#[must_use]
2040	pub fn wrapped_blob_keys_of(&self, sealed: &Hash) -> &[WrappedBlobKey] {
2041		self.wrapped_blob_keys
2042			.get(sealed)
2043			.map_or(&[], Vec::as_slice)
2044	}
2045
2046	/// The content that the key this replica opened for a sealed blob says it seals, if it
2047	/// opened one.
2048	#[must_use]
2049	pub fn content_of_sealed(&self, sealed: &Hash) -> Option<Hash> {
2050		self.blob_keys.get(sealed).map(|(content, _)| *content)
2051	}
2052
2053	/// The wrapped blob keys this replica has, by sealed hash, for other replicas.
2054	pub fn wrapped_blob_keys(&self) -> impl Iterator<Item = (&Hash, &WrappedBlobKey)> {
2055		self.wrapped_blob_keys
2056			.iter()
2057			.flat_map(|(sealed, keys)| keys.iter().map(move |key| (sealed, key)))
2058	}
2059
2060	/// The keys this replica has opened for the content with the hash `content`, by the
2061	/// sealed hash of the blob each key seals. There are several when replicas sealed the
2062	/// same content before they learned of each other's keys.
2063	///
2064	/// The content hash is what the wrapped keys claim, which only reading the whole sealed
2065	/// blob checks. These keys are therefore for reading, never for sealing other content.
2066	pub fn blob_keys(&self, content: &Hash) -> impl Iterator<Item = (&Hash, &Key)> {
2067		self.sealed_blobs
2068			.get(content)
2069			.into_iter()
2070			.flatten()
2071			.filter_map(|sealed| self.blob_keys.get(sealed).map(|(_, key)| (sealed, key)))
2072	}
2073
2074	/// Purges a blob: makes a change that destroys, everywhere, every key that this replica
2075	/// has opened for the content with the hash `content`.
2076	///
2077	/// # Errors
2078	///
2079	/// Returns an error if the replica has no key for the content, or if the clock has run
2080	/// out of timestamps.
2081	pub fn purge_blob(
2082		&mut self,
2083		author: &SigningKey,
2084		keys: &SpaceKeys,
2085		content: &Hash,
2086		wall_millis: u64,
2087		rng: &mut impl CryptoRng,
2088	) -> Result<Parcel, LogError> {
2089		let sealed = self
2090			.sealed_blobs
2091			.get(content)
2092			.filter(|sealed| !sealed.is_empty())
2093			.ok_or(LogError::UnknownBlob)?;
2094		let purges = Purges {
2095			blobs: sealed.clone(),
2096			..Purges::default()
2097		};
2098		self.commit_purges(author, keys, purges, Restating::default(), wall_millis, rng)
2099	}
2100
2101	/// Whether the key of a sealed blob was destroyed.
2102	///
2103	/// # Errors
2104	///
2105	/// Returns an error if the history cannot be read.
2106	pub fn is_blob_purged(&self, sealed: &Hash) -> Result<bool, S::Error> {
2107		self.history.is_blob_purged(sealed)
2108	}
2109
2110	/// The sealed hashes of the blobs whose keys were destroyed.
2111	///
2112	/// # Errors
2113	///
2114	/// Returns an error if the history cannot be read.
2115	pub fn purged_blobs(&self) -> Result<Vec<Hash>, S::Error> {
2116		self.history.purged_blobs()
2117	}
2118
2119	/// The content hashes of the blobs whose keys this replica has opened.
2120	pub fn blobs(&self) -> impl Iterator<Item = &Hash> {
2121		self.sealed_blobs.keys()
2122	}
2123
2124	/// The current state of the space, with the secret values this replica has opened.
2125	#[must_use]
2126	pub const fn state(&self) -> &SpaceState<S> {
2127		&self.state
2128	}
2129
2130	/// The state of the space as of a wall clock time: the result of the changes whose
2131	/// timestamps are at most `millis`, with the secret values this replica has opened. It is
2132	/// a view of the state, which knows when each statement was recorded and superseded.
2133	#[must_use]
2134	pub fn state_as_of(&self, millis: u64) -> State<AsOf<'_, Layers<S>>> {
2135		State::in_storage(AsOf::new(self.state.storage(), millis))
2136	}
2137
2138	/// The changes that no other change names as a parent.
2139	///
2140	/// # Errors
2141	///
2142	/// Returns an error if the history cannot be read.
2143	pub fn heads(&self) -> Result<BTreeSet<ChangeId>, S::Error> {
2144		self.history.heads()
2145	}
2146
2147	/// An accepted change.
2148	///
2149	/// # Errors
2150	///
2151	/// Returns an error if the history cannot be read.
2152	pub fn change(&self, id: ChangeId) -> Result<Option<Change>, S::Error> {
2153		Ok(self.history.change(id)?.map(Cow::into_owned))
2154	}
2155
2156	/// The accepted changes, ordered by ID.
2157	///
2158	/// # Errors
2159	///
2160	/// Returns an error if the history cannot be read.
2161	pub fn changes(&self) -> Result<Vec<Change>, S::Error> {
2162		let mut changes = Vec::new();
2163		for id in self.history.ids()? {
2164			changes.extend(self.change(id)?);
2165		}
2166		Ok(changes)
2167	}
2168
2169	/// Whether the log has a change, accepted or waiting.
2170	///
2171	/// # Errors
2172	///
2173	/// Returns an error if the history cannot be read.
2174	pub fn contains(&self, id: ChangeId) -> Result<bool, S::Error> {
2175		Ok(self.waiting.contains_key(&id) || self.history.contains(id)?)
2176	}
2177
2178	/// Whether waiting changes wait for a change: accepting it may accept them too, whatever
2179	/// they do.
2180	#[must_use]
2181	pub fn is_awaited(&self, id: ChangeId) -> bool {
2182		self.waiting_on.contains_key(&id)
2183	}
2184
2185	/// The changes rejected for good, with the reason. Another replica need not send them
2186	/// again.
2187	#[must_use]
2188	pub const fn rejected(&self) -> &BTreeMap<ChangeId, LogError> {
2189		&self.rejected
2190	}
2191
2192	/// How many changes the log keeps, accepted or waiting.
2193	///
2194	/// # Errors
2195	///
2196	/// Returns an error if the history cannot be read.
2197	pub fn kept(&self) -> Result<usize, S::Error> {
2198		Ok(self.history.count()? + self.waiting.len())
2199	}
2200
2201	/// The changes that waiting changes need and that the log does not have.
2202	///
2203	/// # Errors
2204	///
2205	/// Returns an error if the history cannot be read.
2206	pub fn missing(&self) -> Result<BTreeSet<ChangeId>, S::Error> {
2207		let mut missing = BTreeSet::new();
2208		for &id in self.waiting_on.keys() {
2209			if !self.contains(id)? {
2210				missing.insert(id);
2211			}
2212		}
2213		Ok(missing)
2214	}
2215
2216	/// The replica that first asserted a statement, if this replica can read the statement.
2217	///
2218	/// # Errors
2219	///
2220	/// Returns an error if the storage of the state or the history cannot be read.
2221	pub fn author_of(&self, statement: StatementId) -> Result<Option<VerifyingKey>, S::Error> {
2222		let Some(change) = self
2223			.state
2224			.storage()
2225			.get(statement)?
2226			.and_then(|recorded| recorded.change)
2227		else {
2228			return Ok(None);
2229		};
2230		Ok(self
2231			.history
2232			.change(ChangeId::from_hash(change))?
2233			.map(|change| *change.author()))
2234	}
2235
2236	fn parents_accepted(&self, change: &Change) -> Result<bool, LogError> {
2237		for parent in change.parents() {
2238			if !self.read(self.history.contains(*parent))? {
2239				return Ok(false);
2240			}
2241		}
2242		Ok(true)
2243	}
2244
2245	/// Checks a change whose parents are all accepted: it must be later than each of them,
2246	/// and purge, or restore, only changes it builds on that do not govern the space, and
2247	/// statements sealed in changes it builds on. A change that restores is an ordinary one
2248	/// that purges nothing.
2249	fn check_accepted(&self, change: &Change) -> Result<(), LogError> {
2250		for parent in change.parents() {
2251			let parent = self.read(self.history.change(*parent))?;
2252			if parent.is_some_and(|parent| change.timestamp() <= parent.timestamp()) {
2253				return Err(LogError::NotAfterParents);
2254			}
2255		}
2256		let restores = change.restores();
2257		if !restores.is_empty()
2258			&& (change.kind() != Kind::Ordinary
2259				|| !change.purges().is_empty()
2260				|| !change.sealed().is_empty())
2261		{
2262			return Err(LogError::InvalidPurge);
2263		}
2264		for named in [change.purges(), restores] {
2265			for &purged in &named.changes {
2266				let ordinary = self
2267					.read(self.history.change(purged))?
2268					.is_some_and(|purged| purged.kind() == Kind::Ordinary);
2269				if !(ordinary && self.is_ancestor(purged, change)?) {
2270					return Err(LogError::InvalidPurge);
2271				}
2272			}
2273			for &statement in &named.statements {
2274				let Some(holder) = self.read(self.history.holder(statement))? else {
2275					return Err(LogError::InvalidPurge);
2276				};
2277				if !self.is_ancestor(holder, change)? {
2278					return Err(LogError::InvalidPurge);
2279				}
2280			}
2281		}
2282		Ok(())
2283	}
2284
2285	/// Whether an ordinary change's payload asserts, without sealing it, a statement of a
2286	/// field that a counting governing change makes secret for good, where no such change for
2287	/// that field builds on it: only values written before the field became secret count in
2288	/// plain. So too for a statement it states again, by the change that it came from.
2289	/// Every replica seals what it knows to be secret, so a value written in plain since, as
2290	/// by a replica that turned against its user and leaves the mark out of its change's
2291	/// parents, would replace a password with one of its own; one that a device which did
2292	/// not know wrote at the same time is set aside too.
2293	fn writes_secret_plainly(
2294		&self,
2295		change: &Change,
2296		payload: &Payload,
2297		governance: &Governance,
2298	) -> Result<bool, LogError> {
2299		if !governance.governed() {
2300			return Ok(false);
2301		}
2302		// For each field written in plain that is secret for good, the changes that make it
2303		// so.
2304		let marked = |operations: &[Operation]| -> Vec<&BTreeSet<ChangeId>> {
2305			operations
2306				.iter()
2307				.filter_map(|operation| match operation {
2308					Operation::Assert { statement, .. } => governance.made_secret(&statement.field),
2309					_ => None,
2310				})
2311				.collect()
2312		};
2313		// Whether a mark builds on the change, so that the value was there before the field
2314		// became secret. The space's first change, which makes the standard vocabulary's
2315		// secret fields secret, builds on none.
2316		let before = |marks: &BTreeSet<ChangeId>, written: ChangeId| -> Result<bool, LogError> {
2317			for &mark in marks {
2318				if let Some(mark) = self.read(self.history.change(mark))?
2319					&& self.is_ancestor(written, &mark)?
2320				{
2321					return Ok(true);
2322				}
2323			}
2324			Ok(false)
2325		};
2326		for marks in marked(&payload.operations) {
2327			if !before(marks, change.id())? {
2328				return Ok(true);
2329			}
2330		}
2331		for (source, restated) in &payload.restated {
2332			for marks in marked(&restated.operations) {
2333				if !before(marks, *source)? {
2334					return Ok(true);
2335				}
2336			}
2337		}
2338		Ok(false)
2339	}
2340
2341	/// What a revocation, or a change of roles, of this replica builds on: its heads, but
2342	/// for what builds on a governing change whose payload it has not read, or is one. Such
2343	/// a change may revoke this replica, sent without its payload by a replica that it
2344	/// revoked, and this replica's own revocation of that one would otherwise build on it,
2345	/// and be set aside, though it would stay by revoking that one back
2346	/// (`docs/spec/log.md`, section 8). Where nothing is left, as when the space's first
2347	/// change is unread, it builds on the heads.
2348	fn defending_parents(&self) -> Result<BTreeSet<ChangeId>, LogError> {
2349		let heads = self.read(self.history.heads())?;
2350		let unread = self.unread_governing()?;
2351		if unread.is_empty() {
2352			return Ok(heads);
2353		}
2354		let tainted = self.building_on(&unread, &heads)?;
2355		let mut parents = BTreeSet::new();
2356		let mut to_visit: Vec<ChangeId> = heads.into_iter().collect();
2357		let mut visited = BTreeSet::new();
2358		while let Some(id) = to_visit.pop() {
2359			if !visited.insert(id) {
2360				continue;
2361			}
2362			if !tainted.contains(&id) {
2363				parents.insert(id);
2364			} else if let Some(change) = self.read(self.history.change(id))? {
2365				to_visit.extend(change.parents().iter().copied());
2366			}
2367		}
2368		if parents.is_empty() {
2369			return self.read(self.history.heads());
2370		}
2371		// None that another of them builds on.
2372		let mut floor = u64::MAX;
2373		for &id in &parents {
2374			if let Some(depth) = self.read(self.history.depth(id))? {
2375				floor = floor.min(depth);
2376			}
2377		}
2378		let mut below = BTreeSet::new();
2379		for &id in &parents {
2380			below.extend(self.ancestors_down_to(id, floor)?);
2381		}
2382		Ok(parents.difference(&below).copied().collect())
2383	}
2384
2385	/// The governing changes whose payloads, or keys that open them, are not there yet,
2386	/// with their depths.
2387	fn unread_governing(&self) -> Result<BTreeMap<ChangeId, u64>, LogError> {
2388		let mut unread = BTreeMap::new();
2389		for id in self.read(self.history.governing())? {
2390			if self.read(self.history.status(id))? == Some(Status::Pending)
2391				&& let Some(depth) = self.read(self.history.depth(id))?
2392			{
2393				unread.insert(id, depth);
2394			}
2395		}
2396		Ok(unread)
2397	}
2398
2399	/// Of `from` and their ancestors, those that are one of `unread` or build on one. Only
2400	/// changes as deep as the shallowest of them can, so the walk stops above it.
2401	fn building_on(
2402		&self,
2403		unread: &BTreeMap<ChangeId, u64>,
2404		from: &BTreeSet<ChangeId>,
2405	) -> Result<BTreeSet<ChangeId>, LogError> {
2406		let floor = unread.values().copied().min().unwrap_or(u64::MAX);
2407		let mut reached: BTreeMap<ChangeId, (u64, Vec<ChangeId>)> = BTreeMap::new();
2408		let mut to_visit: Vec<ChangeId> = from.iter().copied().collect();
2409		while let Some(id) = to_visit.pop() {
2410			if reached.contains_key(&id) {
2411				continue;
2412			}
2413			let Some(accepted) = self.read(self.history.get(id))? else {
2414				continue;
2415			};
2416			if accepted.depth < floor {
2417				continue;
2418			}
2419			let parents: Vec<ChangeId> = accepted.change.parents().iter().copied().collect();
2420			to_visit.extend(parents.iter().copied());
2421			reached.insert(id, (accepted.depth, parents));
2422		}
2423		// Parents first, as each is shallower than its children.
2424		let mut order: Vec<(u64, ChangeId)> = reached
2425			.iter()
2426			.map(|(&id, &(depth, _))| (depth, id))
2427			.collect();
2428		order.sort_unstable();
2429		let mut building = BTreeSet::new();
2430		for (_, id) in order {
2431			let parents = reached
2432				.get(&id)
2433				.map_or(&[][..], |(_, parents)| parents.as_slice());
2434			if unread.contains_key(&id) || parents.iter().any(|parent| building.contains(parent)) {
2435				building.insert(id);
2436			}
2437		}
2438		Ok(building)
2439	}
2440
2441	/// Whether an accepted change is an ancestor of `change`, whose parents are accepted.
2442	/// Only changes deeper than the ancestor can descend from it, so the walk stops at the
2443	/// others.
2444	fn is_ancestor(&self, ancestor: ChangeId, change: &Change) -> Result<bool, LogError> {
2445		let Some(depth) = self.read(self.history.depth(ancestor))? else {
2446			return Ok(false);
2447		};
2448		let mut to_visit: Vec<ChangeId> = change.parents().iter().copied().collect();
2449		let mut visited = BTreeSet::new();
2450		while let Some(id) = to_visit.pop() {
2451			if id == ancestor {
2452				return Ok(true);
2453			}
2454			if !visited.insert(id) {
2455				continue;
2456			}
2457			if self
2458				.read(self.history.depth(id))?
2459				.is_some_and(|visiting| visiting > depth)
2460				&& let Some(visiting) = self.read(self.history.change(id))?
2461			{
2462				to_visit.extend(visiting.parents());
2463			}
2464		}
2465		Ok(false)
2466	}
2467
2468	/// Every accepted change that a change builds on, all the way down.
2469	fn ancestors_of(&self, id: ChangeId) -> Result<BTreeSet<ChangeId>, LogError> {
2470		let mut found = BTreeSet::new();
2471		let mut to_visit: Vec<ChangeId> = self
2472			.read(self.history.change(id))?
2473			.map_or_else(Vec::new, |change| {
2474				change.parents().iter().copied().collect()
2475			});
2476		while let Some(id) = to_visit.pop() {
2477			if found.insert(id)
2478				&& let Some(change) = self.read(self.history.change(id))?
2479			{
2480				to_visit.extend(change.parents());
2481			}
2482		}
2483		Ok(found)
2484	}
2485
2486	/// The depth of a change whose parents are all accepted: one more than its deepest
2487	/// parent.
2488	fn depth_of(&self, change: &Change) -> Result<u64, LogError> {
2489		let mut deepest = 0;
2490		for parent in change.parents() {
2491			deepest = deepest.max(self.read(self.history.depth(*parent))?.unwrap_or(0));
2492		}
2493		Ok(deepest + 1)
2494	}
2495
2496	/// Accepts the waiting changes that `accepted` completes, then those that they
2497	/// complete, and so on. Returns them in the order they were accepted. A waiting change
2498	/// that cannot be accepted is rejected, together with everything that waits for it.
2499	fn accept_waiting(
2500		&mut self,
2501		accepted: ChangeId,
2502		keys: &SpaceKeys,
2503		wall_millis: u64,
2504	) -> Result<Vec<ChangeId>, LogError> {
2505		let mut accepted_now = Vec::new();
2506		let mut completed = vec![accepted];
2507		while let Some(parent) = completed.pop() {
2508			for child in self.waiting_on.remove(&parent).unwrap_or_default() {
2509				let ready = match self.waiting.get(&child) {
2510					Some(held) => self.parents_accepted(&held.change)?,
2511					None => false,
2512				};
2513				if !ready {
2514					continue;
2515				}
2516				let Some(held) = self.waiting.remove(&child) else {
2517					continue;
2518				};
2519				let accepted = self.check_accepted(&held.change).and_then(|()| {
2520					self.clock
2521						.observe(held.change.timestamp(), wall_millis)
2522						.map_err(LogError::from)
2523				});
2524				match accepted {
2525					Ok(()) => {
2526						self.accept(held, keys)?;
2527						accepted_now.push(child);
2528						completed.push(child);
2529					}
2530					Err(LogError::Storage) => return Err(LogError::Storage),
2531					Err(error) => {
2532						self.waiting.insert(child, held);
2533						self.reject(child, error);
2534					}
2535				}
2536			}
2537		}
2538		Ok(accepted_now)
2539	}
2540
2541	/// Rejects a change for good, and with it every waiting change that needs it.
2542	fn reject(&mut self, id: ChangeId, error: LogError) {
2543		let mut to_reject = vec![(id, error)];
2544		while let Some((id, error)) = to_reject.pop() {
2545			if let Some(held) = self.waiting.remove(&id) {
2546				for parent in held.change.parents() {
2547					if let Some(children) = self.waiting_on.get_mut(parent) {
2548						children.remove(&id);
2549						if children.is_empty() {
2550							self.waiting_on.remove(parent);
2551						}
2552					}
2553				}
2554			}
2555			self.covered.remove(&id);
2556			for child in self.waiting_on.remove(&id).unwrap_or_default() {
2557				to_reject.push((child, LogError::RejectedParent));
2558			}
2559			self.rejected.insert(id, error);
2560		}
2561	}
2562
2563	/// Accepts a change whose parents are all accepted: takes in what its header says, the
2564	/// statements it seals and what it purges, and then applies its operations if its
2565	/// payload and key are there.
2566	fn accept(&mut self, held: Held, keys: &SpaceKeys) -> Result<(), LogError> {
2567		let id = held.change.id();
2568		let governing = held.change.kind() == Kind::Governing;
2569		// A governing change is decided on once it can be read. An ordinary one arrives
2570		// after every revocation known, none of which builds on it.
2571		let counts = governing || {
2572			let governance = self.governance(keys)?;
2573			self.counts_now(&held.change, None, &governance, |_| false)?
2574		};
2575		let depth = self.depth_of(&held.change)?;
2576		let accepted = Accepted {
2577			change: held.change,
2578			depth,
2579			payload: held.payload,
2580			keys: held.keys,
2581			status: if counts {
2582				Status::Pending
2583			} else {
2584				Status::SetAside
2585			},
2586		};
2587		let added = self.history.add(&accepted);
2588		self.read(added)?;
2589		if !counts {
2590			self.hold_sealed(&accepted.change)?;
2591			return Ok(());
2592		}
2593		// What it purges goes first: a statement that it states again from a change it
2594		// purges is held by it.
2595		let recount = self.take_in_header(&accepted.change, true)?;
2596		self.hold_sealed(&accepted.change)?;
2597		if recount {
2598			self.recount_purges_and_decide(keys)?;
2599		}
2600		if self.stale
2601			&& let Some(fresh) = self.state.storage().ordinary().empty_like()
2602		{
2603			self.rebuild(fresh, keys)?;
2604		}
2605		self.complete(id, keys)
2606	}
2607
2608	/// Acts on what an accepted change's header says, once it counts: purges what it purges.
2609	/// A change that comes to count later, as when it was set aside, not `fresh`, leaves what a
2610	/// counting change that builds on it restored as it is. Returns whether what purges
2611	/// destroyed is to be counted again: after a change that restores.
2612	pub(super) fn take_in_header(
2613		&mut self,
2614		change: &Change,
2615		fresh: bool,
2616	) -> Result<bool, LogError> {
2617		let by = change.id();
2618		if !change.restores().is_empty() {
2619			if let Some(restoring) = self.restoring.get_mut() {
2620				restoring.insert(by);
2621			}
2622			return Ok(true);
2623		}
2624		let purges = change.purges().clone();
2625		// A change just accepted has no descendants yet, so nothing restores after it.
2626		let restorers = if fresh || purges.is_empty() {
2627			Vec::new()
2628		} else {
2629			self.counting_restorers()?
2630		};
2631		for purged in purges.changes {
2632			if !self.restored_after(by, &restorers, &|named| named.changes.contains(&purged))? {
2633				self.destroy_change(purged, by)?;
2634			}
2635		}
2636		for statement in purges.statements {
2637			if !self.restored_after(by, &restorers, &|named| {
2638				named.statements.contains(&statement)
2639			})? {
2640				self.destroy_statement(statement, by)?;
2641			}
2642		}
2643		for sealed in purges.blobs {
2644			if !self.restored_after(by, &restorers, &|named| named.blobs.contains(&sealed))? {
2645				self.destroy_blob_key(sealed, by)?;
2646			}
2647		}
2648		Ok(false)
2649	}
2650
2651	/// Whether one of `restorers`, which count, builds on `purge` and restores what `named`
2652	/// says.
2653	pub(super) fn restored_after(
2654		&self,
2655		purge: ChangeId,
2656		restorers: &[(ChangeId, Restores)],
2657		named: &dyn Fn(&Restores) -> bool,
2658	) -> Result<bool, LogError> {
2659		for (restorer, restores) in restorers {
2660			if named(restores) && self.had(purge, *restorer)? {
2661				return Ok(true);
2662			}
2663		}
2664		Ok(false)
2665	}
2666
2667	/// The accepted changes that restore anything and count now, with what each restores:
2668	/// rare, and found from the changes that ever came to count so, looked for once.
2669	fn counting_restorers(&self) -> Result<Vec<(ChangeId, Restores)>, LogError> {
2670		let known = self.restoring.borrow().clone();
2671		let restoring = if let Some(restoring) = known {
2672			restoring
2673		} else {
2674			let mut restoring = BTreeSet::new();
2675			for id in self.read(self.history.ids())? {
2676				if self
2677					.read(self.history.change(id))?
2678					.is_some_and(|change| !change.restores().is_empty())
2679				{
2680					restoring.insert(id);
2681				}
2682			}
2683			*self.restoring.borrow_mut() = Some(restoring.clone());
2684			restoring
2685		};
2686		let mut counting = Vec::new();
2687		for id in restoring {
2688			if self.read(self.history.status(id))? == Some(Status::SetAside) {
2689				continue;
2690			}
2691			if let Some(change) = self.read(self.history.change(id))? {
2692				counting.push((id, change.restores().clone()));
2693			}
2694		}
2695		Ok(counting)
2696	}
2697
2698	/// Destroys the record key of a secret statement, and remembers it, so that it is
2699	/// ignored if it arrives again; what it was is kept, if the log keeps what purges destroy.
2700	pub(super) fn destroy_statement(
2701		&mut self,
2702		statement: StatementId,
2703		by: ChangeId,
2704	) -> Result<(), LogError> {
2705		let purged = self.history.purge_statement(statement);
2706		self.read(purged)?;
2707		let wrapped = self.wrapped.remove(&statement);
2708		if self.keeping
2709			&& let Some(wrapped) = wrapped
2710		{
2711			self.destroyed
2712				.kept
2713				.push((by, Kept::RecordKeys(statement, wrapped)));
2714		}
2715		self.state.storage_mut().forget(statement);
2716		self.destroyed.statements.push(statement);
2717		Ok(())
2718	}
2719
2720	/// Records which accepted change holds each statement that a change seals, counting or
2721	/// not: of several, one that counts comes first, so that a purge of a statement is
2722	/// decided alike whether its change counts or not.
2723	fn hold_sealed(&mut self, change: &Change) -> Result<(), LogError> {
2724		let mut moved = Vec::new();
2725		for &statement in change.sealed().keys() {
2726			if self.hold(statement, change.id())? {
2727				moved.push(statement);
2728			}
2729		}
2730		// Statements opened from another change than the one that now holds them are
2731		// opened again, once this change can be read.
2732		for &statement in &moved {
2733			self.state.storage_mut().forget(statement);
2734		}
2735		Ok(())
2736	}
2737
2738	/// Destroys the key and the payload of a change, and remembers it, so that they are
2739	/// ignored if they arrive again. The statements it sealed are forgotten, and are held by
2740	/// the purge that states them again, if one does. If the state holds its operations, it
2741	/// is stale.
2742	pub(super) fn destroy_change(&mut self, id: ChangeId, by: ChangeId) -> Result<(), LogError> {
2743		if self.read(self.history.is_change_purged(id))? {
2744			return Ok(());
2745		}
2746		let Some(accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
2747			return Ok(());
2748		};
2749		self.destroyed.changes = true;
2750		if self.keeping && (accepted.payload.is_some() || !accepted.keys.is_empty()) {
2751			self.destroyed
2752				.kept
2753				.push((by, Kept::Change(Box::new(parcel_of(&accepted)))));
2754		}
2755		if accepted.status == Status::Applied {
2756			self.stale = true;
2757		}
2758		let purged = self.history.purge_change(id);
2759		self.read(purged)?;
2760		for statement in accepted.change.sealed().keys() {
2761			self.state.storage_mut().forget(*statement);
2762		}
2763		Ok(())
2764	}
2765
2766	/// Builds the state again in `fresh`, an empty storage, from the operations of every
2767	/// change that adds them, after a purge took some away, and opens again the secret
2768	/// statements that `keys` open. The operations that the state took in are not among
2769	/// those that [`Log::take_applied`] gives.
2770	///
2771	/// # Errors
2772	///
2773	/// Returns [`LogError::Storage`] if the history cannot be read, or the storage written,
2774	/// also if that failed before: a fresh storage does not mend the history, which only
2775	/// [`Log::reset`] empties.
2776	pub fn rebuild(&mut self, fresh: S, keys: &SpaceKeys) -> Result<(), LogError> {
2777		self.check_storage()?;
2778		*self.state.storage_mut().ordinary_mut() = fresh;
2779		self.state.storage_mut().forget_all();
2780		self.stale = false;
2781		self.covered.clear();
2782		for id in self.read(self.history.ids())? {
2783			let Some(accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
2784				continue;
2785			};
2786			if accepted.status != Status::Applied {
2787				continue;
2788			}
2789			let Ok(Some(payload)) = read_payload(&accepted, keys) else {
2790				continue;
2791			};
2792			self.apply_payload(id, accepted.change.timestamp(), &payload)?;
2793		}
2794		self.unlock_secrets(keys)?;
2795		self.check_storage()
2796	}
2797
2798	/// Resumes the space's clock from the latest time of the changes that the history holds,
2799	/// as a log that reads its history from disk does not take them back one by one.
2800	pub fn resume_clock(&mut self, latest: Timestamp) {
2801		let _ = self.clock.observe(latest, u64::MAX);
2802	}
2803
2804	/// Applies again the operations of an accepted change whose history says they are
2805	/// applied, to a storage of the state that lacks them, such as one that a crash left
2806	/// behind the history, or one made anew. Nothing is decided again: what was applied is
2807	/// applied. They are among those that [`Log::take_applied`] gives.
2808	///
2809	/// # Errors
2810	///
2811	/// Returns [`LogError::Storage`] if the history cannot be read or the storage written,
2812	/// and an error if the payload no longer opens with `keys`.
2813	pub fn reapply(&mut self, id: ChangeId, keys: &SpaceKeys) -> Result<(), LogError> {
2814		self.check_storage()?;
2815		let Some(accepted) = self.read(self.history.get(id))?.map(Cow::into_owned) else {
2816			return Ok(());
2817		};
2818		if accepted.status != Status::Applied {
2819			return Ok(());
2820		}
2821		// A payload that no longer opens with `keys` adds nothing here, as when building
2822		// again.
2823		let Ok(Some(payload)) = read_payload(&accepted, keys) else {
2824			return Ok(());
2825		};
2826		self.apply_payload(id, accepted.change.timestamp(), &payload)?;
2827		self.applied.push((id, payload));
2828		self.check_storage()
2829	}
2830
2831	/// Whether a purge left the state stale, to be built again by the caller.
2832	#[must_use]
2833	pub const fn is_stale(&self) -> bool {
2834		self.stale
2835	}
2836
2837	/// Whether a purge left the state stale, which the caller then builds again, as it is
2838	/// in storage that the log cannot make anew; the log forgets that it was.
2839	pub fn take_stale(&mut self) -> bool {
2840		std::mem::take(&mut self.stale)
2841	}
2842
2843	/// Applies the operations of a change's payload, its own and those it states again,
2844	/// unless writing to the storage failed before.
2845	fn apply_payload(
2846		&mut self,
2847		id: ChangeId,
2848		timestamp: Timestamp,
2849		payload: &Payload,
2850	) -> Result<(), LogError> {
2851		let own = Origin::new(timestamp, Some(*id.hash()));
2852		let mut origins: Vec<(Origin, &Operation)> = payload
2853			.operations
2854			.iter()
2855			.map(|operation| (own, operation))
2856			.collect();
2857		for (source, restated) in &payload.restated {
2858			let Some(at) = self
2859				.read(self.history.change(*source))?
2860				.map(|source| source.timestamp())
2861			else {
2862				continue;
2863			};
2864			let origin = Origin::restated(at, timestamp, Some(*id.hash()));
2865			origins.extend(
2866				restated
2867					.operations
2868					.iter()
2869					.map(|operation| (origin, operation)),
2870			);
2871		}
2872		for (origin, operation) in origins {
2873			self.check_storage()?;
2874			let applied = self.state.apply_from(operation, origin);
2875			self.read(applied)?;
2876		}
2877		Ok(())
2878	}
2879
2880	/// Applies the operations of an accepted change, if it has not added everything yet and
2881	/// its payload and a good key are there, and opens the secret statements it holds.
2882	/// Wrapped keys that turn out not to be the change's are dropped. A payload that is the
2883	/// change's but does not open, or does not have the form it must, adds nothing, for
2884	/// good.
2885	fn complete(&mut self, id: ChangeId, keys: &SpaceKeys) -> Result<(), LogError> {
2886		self.complete_with(id, keys, true)
2887	}
2888
2889	/// Applies a governing change that counts, as [`Log::complete`] does, without deciding
2890	/// again which changes count.
2891	fn complete_now(&mut self, id: ChangeId, keys: &SpaceKeys) -> Result<(), LogError> {
2892		self.complete_with(id, keys, false)
2893	}
2894
2895	/// Applies an accepted change, as [`Log::complete`] says. A governing change, in a space
2896	/// whose first change governs it, has every change decided again unless `deciding` is
2897	/// `false`, which then decides whether it counts.
2898	fn complete_with(
2899		&mut self,
2900		id: ChangeId,
2901		keys: &SpaceKeys,
2902		deciding: bool,
2903	) -> Result<(), LogError> {
2904		let Some(accepted) = self.read(self.history.get(id))? else {
2905			return Ok(());
2906		};
2907		if accepted.status != Status::Pending || accepted.payload.is_none() {
2908			return Ok(());
2909		}
2910		let mut accepted = accepted.into_owned();
2911		let before = accepted.keys.len();
2912		let opened = open_payload(&mut accepted, keys);
2913		let payload = match opened {
2914			// Only keys that turned out not to be the change's are dropped.
2915			Opened::NotYet if accepted.keys.len() == before => return Ok(()),
2916			Opened::NotYet => return self.store(&accepted),
2917			Opened::Nothing => {
2918				accepted.status = Status::Ignored;
2919				return self.store(&accepted);
2920			}
2921			Opened::Payload(payload) => payload,
2922		};
2923		let fits = fits_its_kind(&accepted.change, &payload);
2924		// What it states again must come from changes it builds on, whose times it takes.
2925		let mut restates_its_ancestors = true;
2926		for &source in payload.restated.keys() {
2927			if !self.is_ancestor(source, &accepted.change)? {
2928				restates_its_ancestors = false;
2929				break;
2930			}
2931		}
2932		if !(fits && restates_its_ancestors) {
2933			accepted.status = Status::Ignored;
2934			return self.store(&accepted);
2935		}
2936		// An AI agent's change counts only if it writes what an AI agent may; no change counts
2937		// that writes plainly what its author knew to be secret.
2938		if accepted.change.kind() == Kind::Ordinary {
2939			let set_aside = {
2940				let governance = self.governance(keys)?;
2941				let mut failed = None;
2942				// In a space with members, what its author's role allows of what it writes.
2943				let by_role = governance.view().is_none()
2944					|| self.counts_now(&accepted.change, Some(&payload), &governance, |other| {
2945						self.had(id, other).unwrap_or_else(|error| {
2946							failed = Some(error);
2947							false
2948						})
2949					})?;
2950				if let Some(error) = failed {
2951					return Err(error);
2952				}
2953				!by_role
2954					|| (governance.is_ai_agent(accepted.change.author().as_bytes())
2955						&& !fits_an_ai_agent(&payload))
2956					|| self.writes_secret_plainly(&accepted.change, &payload, &governance)?
2957			};
2958			if set_aside {
2959				if self.covered.remove(&id) {
2960					self.stale = true;
2961				}
2962				accepted.status = Status::SetAside;
2963				self.store(&accepted)?;
2964				// What its header purged was taken in as it was accepted: an AI agent's change
2965				// never purges, but this one may have.
2966				let header = &accepted.change;
2967				if header.purges_or_restores() || !header.sealed().is_empty() {
2968					self.recount_purges_and_decide(keys)?;
2969				}
2970				return Ok(());
2971			}
2972		}
2973		// A governing change without parents makes the space governed, if it was not.
2974		if deciding
2975			&& accepted.change.kind() == Kind::Governing
2976			&& (accepted.change.parents().is_empty() || self.governance(keys)?.governed())
2977		{
2978			// It can be read now: which changes count is decided again, this one included.
2979			self.store(&accepted)?;
2980			return self.govern(keys);
2981		}
2982		// The history says it is applied once the state holds its operations.
2983		let covered = self.covered.remove(&id);
2984		if !covered {
2985			self.apply_payload(id, accepted.change.timestamp(), &payload)?;
2986		}
2987		accepted.status = Status::Applied;
2988		self.store(&accepted)?;
2989		let mut held_here = Vec::new();
2990		for (&statement, _) in payload.all_sealed() {
2991			if self.read(self.history.holder(statement))? == Some(id) {
2992				held_here.push(statement);
2993			}
2994		}
2995		// The change's own payload is at hand for opening its sealed statements.
2996		let mut payloads = BTreeMap::from([(id, payload)]);
2997		for statement in held_here {
2998			self.open(statement, keys, &mut payloads)?;
2999		}
3000		if !covered && let Some(payload) = payloads.remove(&id) {
3001			self.applied.push((id, payload));
3002		}
3003		Ok(())
3004	}
3005
3006	/// Makes a change that purges, and states again what `restating` holds, and accepts it.
3007	fn commit_purges(
3008		&mut self,
3009		author: &SigningKey,
3010		keys: &SpaceKeys,
3011		purges: Purges,
3012		restating: Restating,
3013		wall_millis: u64,
3014		rng: &mut impl CryptoRng,
3015	) -> Result<Parcel, LogError> {
3016		self.check_storage()?;
3017		self.applied.clear();
3018		self.destroyed = Destroyed::default();
3019		let heads = self.read(self.history.heads())?;
3020		let timestamp = self.clock.now(wall_millis)?;
3021		let mut draft = Draft::new(heads, timestamp, restating.payload);
3022		draft.purges = purges;
3023		draft.record_keys = restating.record_keys;
3024		let parcel = Change::create(self.space, keys, author, &draft, rng);
3025		self.accept(held(parcel.clone()), keys)?;
3026		self.check_storage()?;
3027		Ok(parcel)
3028	}
3029
3030	/// Opens a sealed blob's key, if `keys` hold the space key that one of its wrapped keys
3031	/// needs, and for a secret blob key the secrets key too; a secret blob key takes the
3032	/// place of an ordinary one opened before, as [`Log::receive_blob_key`] says, and its
3033	/// ordinary keys go. Wrapped keys that do not open with the keys they name are dropped,
3034	/// also those after the one that opened.
3035	fn open_blob_key(&mut self, sealed: Hash, keys: &SpaceKeys) {
3036		if self.secret_blobs.contains(&sealed) {
3037			return;
3038		}
3039		let space = self.space;
3040		let Some(candidates) = self.wrapped_blob_keys.get(&sealed) else {
3041			return;
3042		};
3043		let opened_ordinarily = self.blob_keys.contains_key(&sealed);
3044		if opened_ordinarily && candidates.len() < 2 {
3045			return;
3046		}
3047		// What each wrapped key gives: `None` if the replica lacks its space key.
3048		let results: Vec<Option<Option<Unwrapped>>> = candidates
3049			.iter()
3050			.map(|candidate| {
3051				keys.get(candidate.epoch())
3052					.map(|_| candidate.unwrap(space, &sealed, keys))
3053			})
3054			.collect();
3055		let secret_opened = results
3056			.iter()
3057			.any(|result| matches!(result, Some(Some(Unwrapped::Key { secret: true, .. }))));
3058		// Those that do not open go; so do ordinary ones once a secret one opens, as only a
3059		// replica that holds the secrets can make one, and the blob is a secret one.
3060		let keep: Vec<bool> = results
3061			.iter()
3062			.map(|result| match result {
3063				None | Some(Some(Unwrapped::Secret)) => true,
3064				Some(None) => false,
3065				Some(Some(Unwrapped::Key { secret, .. })) => *secret || !secret_opened,
3066			})
3067			.collect();
3068		let secret_form = results.iter().any(|result| {
3069			matches!(
3070				result,
3071				Some(Some(
3072					Unwrapped::Secret | Unwrapped::Key { secret: true, .. }
3073				))
3074			)
3075		});
3076		let unchecked = results.iter().any(Option::is_none);
3077		let mut opened: Option<((Hash, Key), bool)> = None;
3078		for result in results {
3079			if let Some(Some(Unwrapped::Key {
3080				content,
3081				key,
3082				secret,
3083			})) = result
3084				&& opened.as_ref().is_none_or(|(_, taken)| secret && !taken)
3085			{
3086				opened = Some(((content, key), secret));
3087			}
3088		}
3089		let candidates = self
3090			.wrapped_blob_keys
3091			.get_mut(&sealed)
3092			.expect("its keys were just read");
3093		let mut index = 0;
3094		candidates.retain(|_| {
3095			index += 1;
3096			keep[index - 1]
3097		});
3098		if candidates.is_empty() {
3099			self.wrapped_blob_keys.remove(&sealed);
3100		}
3101		// One the replica cannot check yet may still be a secret one.
3102		if secret_form {
3103			self.secret_candidates.insert(sealed);
3104		} else if !unchecked {
3105			self.secret_candidates.remove(&sealed);
3106		}
3107		if let Some((opened, secret)) = opened {
3108			self.prefer_blob_key(sealed, opened, secret);
3109		}
3110	}
3111
3112	/// Destroys the key of a sealed blob, and remembers it, so that it is ignored if it
3113	/// arrives again; what it was is kept, if the log keeps what purges destroy.
3114	pub(super) fn destroy_blob_key(&mut self, sealed: Hash, by: ChangeId) -> Result<(), LogError> {
3115		let purged = self.history.purge_blob(sealed);
3116		self.read(purged)?;
3117		let wrapped = self.wrapped_blob_keys.remove(&sealed);
3118		if self.keeping
3119			&& let Some(wrapped) = wrapped
3120		{
3121			self.destroyed
3122				.kept
3123				.push((by, Kept::BlobKeys(sealed, wrapped)));
3124		}
3125		self.secret_candidates.remove(&sealed);
3126		self.forget_blob_key(&sealed);
3127		self.destroyed.blobs.push(sealed);
3128		Ok(())
3129	}
3130
3131	/// Records that a change holds a sealed statement. Of several changes that hold one,
3132	/// which only a faulty replica makes, the earliest counts, and of equally early ones the
3133	/// smallest. Returns whether the holder changed.
3134	fn hold(&mut self, statement: StatementId, change: ChangeId) -> Result<bool, LogError> {
3135		// A change that holds it and was not purged comes first.
3136		let order = |log: &Self, id: ChangeId| -> Result<_, LogError> {
3137			Ok((
3138				log.read(log.history.is_change_purged(id))?
3139					|| log.read(log.history.status(id))? == Some(Status::SetAside),
3140				log.read(log.history.change(id))?
3141					.map(|change| change.timestamp()),
3142				id,
3143			))
3144		};
3145		if let Some(holder) = self.read(self.history.holder(statement))?
3146			&& order(self, holder)? <= order(self, change)?
3147		{
3148			return Ok(false);
3149		}
3150		let held = self.history.set_holder(statement, change);
3151		self.read(held)?;
3152		Ok(true)
3153	}
3154
3155	/// Opens a sealed statement and applies it, if this replica has the change that holds
3156	/// it with its payload and key, a good wrapped record key and the secrets key. Wrapped
3157	/// record keys that do not open with the secrets key they name, or are not the keys
3158	/// whose hashes the holder's header holds, are dropped.
3159	///
3160	/// `payloads` holds the decrypted payloads of changes that hold sealed statements, which
3161	/// it takes in as it reads them, so that a change is decrypted once for many statements.
3162	fn open(
3163		&mut self,
3164		id: StatementId,
3165		keys: &SpaceKeys,
3166		payloads: &mut BTreeMap<ChangeId, Payload>,
3167	) -> Result<(), LogError> {
3168		if self.state.storage().is_open(id) || self.read(self.history.is_statement_purged(id))? {
3169			return Ok(());
3170		}
3171		let Some(holder) = self.read(self.history.holder(id))? else {
3172			return Ok(());
3173		};
3174		let Some(accepted) = self.read(self.history.get(holder))?.map(Cow::into_owned) else {
3175			return Ok(());
3176		};
3177		// A payload that adds nothing reveals nothing either.
3178		if accepted.status != Status::Applied {
3179			return Ok(());
3180		}
3181		let Some(&expected) = accepted.change.sealed().get(&id) else {
3182			return Ok(());
3183		};
3184		let Some(candidates) = self.wrapped.get_mut(&id) else {
3185			return Ok(());
3186		};
3187		// A key that does not open is dropped. One that opens to another hash than the
3188		// holder's is kept, and not used: another change may seal the statement too, as
3189		// devices that run one migration at once do, and come to hold it, as an earlier one
3190		// arrives.
3191		let mut record_key = None;
3192		candidates.retain(|candidate| {
3193			if record_key.is_some() || keys.secrets(candidate.epoch()).is_none() {
3194				return true;
3195			}
3196			let Some(key) = candidate.unwrap(self.space, id, keys) else {
3197				return false;
3198			};
3199			if key_hash(&key) == expected {
3200				record_key = Some(key);
3201			}
3202			true
3203		});
3204		let Some(record_key) = record_key else {
3205			return Ok(());
3206		};
3207		let timestamp = accepted.change.timestamp();
3208		let hash = *holder.hash();
3209		// The payload is read again, as the log does not keep it opened.
3210		let payload = match payloads.entry(holder) {
3211			btree_map::Entry::Occupied(known) => known.into_mut(),
3212			btree_map::Entry::Vacant(unknown) => {
3213				let Ok(Some(payload)) = read_payload(&accepted, keys) else {
3214					return Ok(());
3215				};
3216				unknown.insert(payload)
3217			}
3218		};
3219		// A statement that a purge states again counts from the change it came from.
3220		let (envelope, origin) = if let Some(envelope) = payload.sealed.get(&id) {
3221			(Some(envelope), Origin::new(timestamp, Some(hash)))
3222		} else {
3223			let Some((&source, restated)) = payload
3224				.restated
3225				.iter()
3226				.find(|(_, restated)| restated.sealed.contains_key(&id))
3227			else {
3228				return Ok(());
3229			};
3230			let Some(at) = self
3231				.read(self.history.change(source))?
3232				.map(|source| source.timestamp())
3233			else {
3234				return Ok(());
3235			};
3236			let origin = Origin::restated(at, timestamp, Some(hash));
3237			(restated.sealed.get(&id), origin)
3238		};
3239		let Some(statement) =
3240			envelope.and_then(|envelope| open_sealed(self.space, id, envelope, &record_key))
3241		else {
3242			return Ok(());
3243		};
3244		self.state.storage_mut().open(&statement, origin);
3245		Ok(())
3246	}
3247}
3248
3249/// Keeps a wrapped key of a change among its candidates, as [`Log::receive_change_key`]
3250/// says. Returns whether it was kept.
3251fn keep_key(
3252	change: &Change,
3253	candidates: &mut Vec<WrappedChangeKey>,
3254	key: WrappedChangeKey,
3255	keys: &SpaceKeys,
3256) -> Result<bool, LogError> {
3257	if candidates.contains(&key) {
3258		return Ok(false);
3259	}
3260	if keys.get(change.epoch()).is_some() {
3261		if key.unwrap(change, keys).is_none() {
3262			return Err(LogError::OtherKey);
3263		}
3264		if candidates
3265			.iter()
3266			.any(|known| known.unwrap(change, keys).is_some())
3267		{
3268			return Ok(false);
3269		}
3270		*candidates = vec![key];
3271	} else if candidates.len() < WRAPPED_KEYS_PER_CHANGE {
3272		candidates.push(key);
3273	} else {
3274		return Ok(false);
3275	}
3276	Ok(true)
3277}
3278
3279/// An operation of a purged change, as the purge states it again: without the assertions
3280/// of the statements it purges, whose replacing of other statements stays as a retraction.
3281fn without(operation: Operation, purged: &BTreeSet<StatementId>) -> Option<Operation> {
3282	match operation {
3283		Operation::Assert {
3284			statement,
3285			supersedes,
3286			any_entity,
3287		} if purged.contains(&statement.id) => (!supersedes.is_empty()).then(|| Operation::Retract {
3288			entity: (!any_entity).then_some(statement.entity),
3289			statements: supersedes,
3290		}),
3291		other => Some(other),
3292	}
3293}
3294
3295/// The secret statements that a change being made takes away: the secret statements it seals,
3296/// with their entities, and those it takes away so far.
3297struct TakingSecrets {
3298	sealing: BTreeMap<StatementId, EntityId>,
3299	taken: BTreeSet<StatementId>,
3300}
3301
3302/// What a purge states again: its payload, and the hashes of the record keys of the
3303/// statements it seals again.
3304#[derive(Default)]
3305struct Restating {
3306	payload: Payload,
3307	record_keys: BTreeMap<StatementId, Hash>,
3308}
3309
3310/// A change as the log first holds it, with the parts that came with it.
3311fn held(parcel: Parcel) -> Held {
3312	Held {
3313		change: parcel.change,
3314		payload: parcel.payload,
3315		keys: parcel.keys,
3316	}
3317}
3318
3319/// Whether operations set a field that governs the space.
3320fn holds_governing(operations: &[Operation]) -> bool {
3321	operations.iter().any(|operation| {
3322		matches!(operation, Operation::Assert { statement, .. } if fields::is_governing(&statement.field))
3323	})
3324}
3325
3326/// Whether a payload holds only what an AI agent may write: statements that
3327/// [`fields::ai_agent_may_write`] allows, and retractions, but of secret statements, with
3328/// nothing sealed or stated again. An AI agent, which reads no secrets, takes none away.
3329fn fits_an_ai_agent(payload: &Payload) -> bool {
3330	payload.sealed.is_empty()
3331		&& payload.restated.is_empty()
3332		&& payload.operations.iter().all(|operation| match operation {
3333			Operation::Assert { statement, .. } => fields::ai_agent_may_write(statement),
3334			Operation::Retract { .. } => true,
3335			Operation::RetractSecret { .. } | Operation::Unknown(_) => false,
3336		})
3337}
3338
3339/// Whether operations only set fields that govern the space, or retract statements, but
3340/// secret ones, as no statement that governs is secret. A field of NibKeep's own that this
3341/// version does not know may govern in a later version: its statements are kept, with no
3342/// effect here.
3343fn holds_only_governing(operations: &[Operation]) -> bool {
3344	operations.iter().all(|operation| match operation {
3345		Operation::Assert { statement, .. } => {
3346			fields::is_governing(&statement.field) || fields::is_later_governing(&statement.field)
3347		}
3348		Operation::Retract { .. } => true,
3349		Operation::RetractSecret { .. } | Operation::Unknown(_) => false,
3350	})
3351}
3352
3353#[cfg(test)]
3354mod tests {
3355	use nibkeep_model::{Statement, Value};
3356	use nibkeep_testkit::TestRng;
3357	use nibkeep_time::Timestamp;
3358
3359	use super::*;
3360
3361	/// A change whose payload does not fit its kind seals a statement: whenever its record
3362	/// key arrives, before or after the change, and also when secrets are unlocked, the
3363	/// statement stays sealed, as the payload adds nothing.
3364	#[test]
3365	fn a_payload_that_adds_nothing_reveals_no_secret() {
3366		let mut rng = TestRng::new("ignored secrets");
3367		let space = rng.space_id();
3368		let mut keys = SpaceKeys::new(0, rng.key());
3369		keys.insert_secrets(0, rng.key());
3370		let author = rng.signing_key();
3371		let entity = rng.entity_id();
3372		let secret = Statement::new(
3373			rng.statement_id(),
3374			entity,
3375			"local.password".parse().expect("a field name"),
3376			Value::Text("hunter2".to_owned()),
3377		);
3378		let record_key = Key::generate(&mut rng);
3379		let key = Statement::new(
3380			rng.statement_id(),
3381			entity,
3382			fields::SIGNING_KEY,
3383			Value::Text("a key".to_owned()),
3384		);
3385		// An ordinary change that sets a replica's key, which it must not.
3386		let mut payload = Payload::from(vec![Operation::assert(key)]);
3387		payload
3388			.sealed
3389			.insert(secret.id, seal(space, &secret, &record_key, &mut rng));
3390		let mut draft = Draft::new([], Timestamp::new(1_800_000_000_000, 0), payload);
3391		draft.record_keys.insert(secret.id, key_hash(&record_key));
3392		let parcel = Change::create(space, &keys, &author, &draft, &mut rng);
3393		let wrapped = WrappedKey::wrap(
3394			space,
3395			secret.id,
3396			&record_key,
3397			keys.newest_secrets().expect("a secrets key"),
3398			&mut rng,
3399		);
3400
3401		let mut key_first = Log::new(space, Clock::new(3_600_000));
3402		key_first
3403			.receive_wrapped_key(secret.id, wrapped.clone(), &keys)
3404			.expect("keeps the key");
3405		key_first
3406			.receive(parcel.clone(), &keys, 1_800_000_000_000)
3407			.expect("accepts");
3408		let mut key_after = Log::new(space, Clock::new(3_600_000));
3409		key_after
3410			.receive(parcel, &keys, 1_800_000_000_000)
3411			.expect("accepts");
3412		key_after
3413			.receive_wrapped_key(secret.id, wrapped, &keys)
3414			.expect("keeps the key");
3415		key_after.unlock_secrets(&keys).expect("unlocks");
3416		for log in [&key_first, &key_after] {
3417			assert!(log.is_sealed(secret.id).expect("reads"));
3418			assert!(!log.state().storage().is_open(secret.id));
3419			assert_eq!(log.state().statements().expect("reads").len(), 0);
3420		}
3421	}
3422}