Skip to main content

nibkeep_node/library/
secrets_keys.rs

1//! The secrets keys of a space once the secrets are set up: the one that seals new secret
2//! values, a new one after a replica that may hold the secrets departs, and giving them to
3//! every replica known to hold the secrets, which takes a key from any replica if the gift
4//! carries a link made with a secrets key that it holds already
5//! ([technical design](../../../../docs/Technical-design.md#13-sharing)). A replica that never
6//! held the secrets cannot make such a link, so it neither gives a key of its own making to
7//! seal with, nor is given one by the others.
8
9use std::collections::BTreeSet;
10
11use nibkeep_base::{EntityId, Hash, SpaceId};
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_crypto::{EncryptionKey, Key, RecoveryCode, VerifyingKey, key_hash};
14use nibkeep_governance::{Roster, SealedSecretsKey, recovery_record};
15use nibkeep_keys::{SecretsKeys, SpaceKeyMap};
16use nibkeep_log::ChangeId;
17use nibkeep_time::Timestamp;
18
19use super::Library;
20use super::revocation::Makers;
21use crate::NodeError;
22
23/// A secrets key that a statement seals to this replica's record in a space, which it takes
24/// if the key opens with its hash: one that the replica it takes the secrets from gave, or
25/// one whose link a secrets key it holds checks, made by a member's replica.
26pub(super) struct Given {
27	pub(super) space: SpaceId,
28	/// The replica's record that it is given to.
29	pub(super) replica: EntityId,
30	pub(super) sealed: SealedSecretsKey,
31	/// Given by the replica it takes the secrets from, in a counting change signed by that
32	/// replica's key of its own, as [technical design](../../../../docs/Technical-design.md#12-secrets)
33	/// says.
34	pub(super) asked: bool,
35	/// Whether a member's replica made the change that gives it and the key's rotation, by
36	/// the changes they build on, whatever later set them aside.
37	pub(super) made: bool,
38}
39
40/// A replica known to hold the secrets of a space, which this one gives the keys it lacks.
41struct Holder {
42	replica: EntityId,
43	encryption: EncryptionKey,
44	/// The keys given to it, by number and hash, as far as this replica can tell.
45	has: BTreeSet<(u64, Hash)>,
46	/// For a replica of this user's, known to hold the personal space's secrets, the newest
47	/// key of the personal space given to it that this replica holds, by its space and
48	/// number, which links what no key of the space itself can.
49	personal: Option<(SpaceId, u64, Key)>,
50}
51
52/// This user's replicas known to hold the personal space's secrets, by their personal
53/// records, each with the newest personal key given to it that this replica holds, which
54/// links a gift of another space's key to it; with the personal space's roster, and the
55/// spaces that each holds by its newest choice there, as `(space, record)`. Read once for
56/// every space that the secrets settle in.
57pub(super) struct PersonalHolders {
58	roster: Roster,
59	links: std::collections::BTreeMap<EntityId, (SpaceId, u64, Key)>,
60	holding: BTreeSet<(SpaceId, EntityId)>,
61}
62
63/// A secrets key that this replica holds and gives out: its rotation a member's replica
64/// made, by the changes it builds on.
65struct GivenOut {
66	rotation: (Timestamp, ChangeId),
67	epoch: u64,
68	key: Key,
69	hash: Hash,
70}
71
72/// Takes into `keys` the secrets keys of `given` that open with their secrets decryption key
73/// and whose hashes are those stated: those that the replica asked gave, and those whose
74/// links a key of `keys` checks, as one taken here may. Returns how many it took.
75pub(super) fn take_given(given: &[Given], keys: &mut SecretsKeys) -> usize {
76	let mut taken = 0;
77	loop {
78		let mut opened = Vec::new();
79		for gift in given {
80			let held = |space: SpaceId, epoch: u64| {
81				keys.spaces.get(&space).and_then(|held| held.get(&epoch))
82			};
83			if held(gift.space, gift.sealed.epoch).is_some() {
84				continue;
85			}
86			let link = &gift.sealed.link;
87			let linked = || {
88				gift.made
89					&& held(link.space, link.epoch)
90						.is_some_and(|key| gift.sealed.link_holds(gift.space, gift.replica, key))
91			};
92			if !gift.asked && !linked() {
93				continue;
94			}
95			if let Some(key) = gift
96				.sealed
97				.open(&keys.decryption, gift.space, gift.replica)
98				.filter(|key| key_hash(key) == gift.sealed.hash)
99			{
100				opened.push((gift.space, gift.sealed.epoch, key));
101			}
102		}
103		let before = taken;
104		for (space, epoch, key) in opened {
105			if let std::collections::btree_map::Entry::Vacant(vacant) =
106				keys.spaces.entry(space).or_default().entry(epoch)
107			{
108				vacant.insert(key);
109				taken += 1;
110			}
111		}
112		if taken == before {
113			return taken;
114		}
115	}
116}
117
118/// The keys of `held` that `given` gives, by number and hash: those that the replica asked
119/// gave, and those whose links a key kept checks, as one kept here may; so a copy of a
120/// replica keeps what that replica would have taken.
121pub(super) fn keep_given(given: &[Given], held: &SpaceKeyMap) -> SpaceKeyMap {
122	let mut kept = SpaceKeyMap::new();
123	loop {
124		let mut more = Vec::new();
125		for gift in given {
126			if kept
127				.get(&gift.space)
128				.is_some_and(|kept| kept.contains_key(&gift.sealed.epoch))
129			{
130				continue;
131			}
132			let Some(key) = held
133				.get(&gift.space)
134				.and_then(|held| held.get(&gift.sealed.epoch))
135				.filter(|key| key_hash(key) == gift.sealed.hash)
136			else {
137				continue;
138			};
139			let link = &gift.sealed.link;
140			let linked = || {
141				gift.made
142					&& kept
143						.get(&link.space)
144						.and_then(|kept| kept.get(&link.epoch))
145						.is_some_and(|key| gift.sealed.link_holds(gift.space, gift.replica, key))
146			};
147			if gift.asked || linked() {
148				more.push((gift.space, gift.sealed.epoch, key.clone()));
149			}
150		}
151		if more.is_empty() {
152			return kept;
153		}
154		for (space, epoch, key) in more {
155			kept.entry(space).or_default().insert(epoch, key);
156		}
157	}
158}
159
160/// A random number for a new secrets key, which no key of `known` has, so that two keys
161/// made at the same time differ.
162pub(super) fn fresh_number(known: &BTreeSet<u64>, rng: &mut impl CryptoRng) -> u64 {
163	loop {
164		let epoch = rng.next_u64();
165		if !known.contains(&epoch) {
166			return epoch;
167		}
168	}
169}
170
171impl Library {
172	/// The numbers of the secrets keys of a space that this replica holds while its secrets
173	/// are unlocked, in order, and the number of the one it seals new secret values with.
174	///
175	/// # Errors
176	///
177	/// Returns an error if the library has no such space.
178	pub fn secrets_key_numbers(
179		&self,
180		space: SpaceId,
181	) -> Result<(Vec<u64>, Option<u64>), NodeError> {
182		let open = self.space(space)?;
183		Ok((
184			open.keys.secrets_keys().map(|(epoch, _)| epoch).collect(),
185			open.keys.newest_secrets().map(|(epoch, _)| epoch),
186		))
187	}
188
189	/// The secrets keys that statements of `rosters` seal to the record of the replica whose
190	/// key is `whose`, or else of this replica, to the secrets encryption key whose hash is
191	/// `recipient`, or else to the one that each space states for it, with whether that
192	/// replica may take each.
193	pub(super) fn secrets_given(
194		&self,
195		rosters: &std::collections::BTreeMap<SpaceId, Roster>,
196		whose: Option<&VerifyingKey>,
197		recipient: Option<Hash>,
198	) -> Result<Vec<Given>, NodeError> {
199		let mut given = Vec::new();
200		for (&space, roster) in rosters {
201			let own = match whose {
202				Some(key) => match roster.replica_of(key) {
203					Some(record) => record,
204					None => continue,
205				},
206				None => self.own_record(space)?,
207			};
208			let Some(recipient) = recipient.or_else(|| {
209				roster
210					.secrets_encryption_of(own)
211					.map(nibkeep_governance::secrets_recipient)
212			}) else {
213				continue;
214			};
215			let asked_key = roster
216				.secrets_from(own)
217				.and_then(|from| roster.own_key_of(from));
218			let mut makers = Makers::of(self.space(space)?);
219			for gift in roster.secrets_gifts(own) {
220				if gift.sealed.recipient != recipient {
221					continue;
222				}
223				let asked = gift.counts && asked_key == Some(&gift.author);
224				let made = !asked && self.linked_and_made(space, roster, &mut makers, gift)?;
225				given.push(Given {
226					space,
227					replica: own,
228					sealed: gift.sealed.clone(),
229					asked,
230					made,
231				});
232			}
233		}
234		Ok(given)
235	}
236
237	/// The secrets keys that statements of `rosters` seal to the recovery code `code`, on
238	/// each of its records, to the secrets encryption key that it signed, with whether a
239	/// replica that recovers with the code may take each: those that the replica which made
240	/// the code gave it on the person's record of the code in the personal space, signed by
241	/// that replica's key of its own, as a replica takes those of the replica it asked; and
242	/// those whose links a key taken checks.
243	/// A code asks nobody: the replica that made it gave it the secrets, as its person chose
244	/// then ([technical design](../../../../docs/Technical-design.md#111-recovery-codes)).
245	pub(super) fn code_secrets_given(
246		&self,
247		rosters: &std::collections::BTreeMap<SpaceId, Roster>,
248		code: &RecoveryCode,
249	) -> Result<Vec<Given>, NodeError> {
250		let key = code.signing_key().verifying_key();
251		let recipient =
252			nibkeep_governance::secrets_recipient(&code.secrets_decryption_key().encryption_key());
253		// The code's record for the person in the personal space, whose first statement is
254		// its maker's: a statement copied onto a record for another member, as its signature
255		// allows, makes nobody its maker.
256		let own = recovery_record(self.info.personal, self.info.user, &key);
257		let mut given = Vec::new();
258		for (&space, roster) in rosters {
259			let mut makers = Makers::of(self.space(space)?);
260			for named in roster.codes().filter(|named| named.statement.key == key) {
261				let maker = space == self.info.personal
262					&& named.record == own
263					&& roster
264						.replica_of(&named.author)
265						.is_some_and(|maker| roster.own_key_of(maker) == Some(&named.author));
266				for gift in roster.secrets_gifts(named.record) {
267					if gift.sealed.recipient != recipient {
268						continue;
269					}
270					let asked = maker && gift.counts && gift.author == named.author;
271					let made = !asked && self.linked_and_made(space, roster, &mut makers, gift)?;
272					given.push(Given {
273						space,
274						replica: named.record,
275						sealed: gift.sealed.clone(),
276						asked,
277						made,
278					});
279				}
280			}
281		}
282		Ok(given)
283	}
284
285	/// The secrets keys that the recovery code `code` opens, of those that statements of
286	/// `rosters` seal to it, by space and number: those that a replica which recovers with the
287	/// code takes, as [`Library::code_secrets_given`] says.
288	pub(super) fn secrets_code_opens(
289		&self,
290		rosters: &std::collections::BTreeMap<SpaceId, Roster>,
291		code: &RecoveryCode,
292	) -> Result<SpaceKeyMap, NodeError> {
293		let given = self.code_secrets_given(rosters, code)?;
294		let mut keys = SecretsKeys {
295			spaces: SpaceKeyMap::new(),
296			decryption: code.secrets_decryption_key(),
297		};
298		take_given(&given, &mut keys);
299		Ok(keys.spaces)
300	}
301
302	/// Whether a gift of a secrets key in `space` carries a link, which proves the giver
303	/// held a key of this space, or of the personal space, which only this user's replicas
304	/// hold, as another space's proves nothing here; and whether a member's replica made the
305	/// change that gives it and the key's rotation, by the changes they build on.
306	fn linked_and_made(
307		&self,
308		space: SpaceId,
309		roster: &Roster,
310		makers: &mut Makers<'_>,
311		gift: &nibkeep_governance::SecretsGift,
312	) -> Result<bool, NodeError> {
313		let link = &gift.sealed.link;
314		Ok((link.space == space || link.space == self.info.personal)
315			&& makers.made(gift.change)?
316			&& match roster.secrets_rotation(gift.sealed.epoch, &gift.sealed.hash) {
317				Some(rotation) => makers.made(rotation.change)?,
318				None => false,
319			})
320	}
321
322	/// The departures after which a space's secrets need a new key: every counting change
323	/// that revokes a replica that a statement gave a secrets key, or that ends it in a space
324	/// with members, as a member's leaving or removal does; and every one that revokes a
325	/// recovery code that a statement gave one.
326	fn secrets_departures(
327		&self,
328		space: SpaceId,
329		roster: &Roster,
330	) -> Result<Vec<ChangeId>, NodeError> {
331		let open = self.space(space)?;
332		let log = open.stored.log();
333		let mut departures = BTreeSet::new();
334		for replica in roster.replicas() {
335			if !roster.may_hold_secrets(replica) {
336				continue;
337			}
338			for key in roster.keys_of(replica) {
339				departures.extend(log.revocations_of(Some(key), &open.keys)?);
340				departures.extend(log.removals_of(key, &open.keys)?);
341			}
342		}
343		// And every counting revocation of a recovery code that a statement gave one.
344		for code in roster.codes() {
345			if roster.may_hold_secrets(code.record) {
346				departures.extend(code.revoked_by.iter().copied());
347			}
348		}
349		Ok(departures.into_iter().collect())
350	}
351
352	/// Has a space seal new secret values with the newest secrets key that this replica
353	/// holds and that is safe: whose rotation a member's replica made, by the changes it
354	/// builds on, and builds on every departure after which the secrets need a new key, so
355	/// that whoever made it knew of each; the newest is the one whose rotation came last, by
356	/// time and then by ID. Until one is safe, it seals with the newest whose rotation counts.
357	/// Returns whether one is safe, or none needs to be, as no replica that held the secrets
358	/// departed and no key it holds has a rotation, as one set up before records said so.
359	pub(super) fn choose_secrets_key_with(
360		&mut self,
361		space: SpaceId,
362		roster: &Roster,
363	) -> Result<bool, NodeError> {
364		let open = self.space(space)?;
365		if open.keys.newest_secrets().is_none() {
366			return Ok(true);
367		}
368		let log = open.stored.log();
369		let mut makers = Makers::of(open);
370		let mut candidates: Vec<((Timestamp, ChangeId), u64)> = Vec::new();
371		let mut counting: BTreeSet<ChangeId> = BTreeSet::new();
372		// Keys that no statement names, as one set up before the records said so.
373		let mut unstated = Vec::new();
374		for (epoch, key) in open.keys.secrets_keys() {
375			match roster.secrets_rotation(epoch, &key_hash(key)) {
376				Some(rotation) if makers.made(rotation.change)? => {
377					candidates.push(((rotation.at, rotation.change), epoch));
378					if rotation.counts {
379						counting.insert(rotation.change);
380					}
381				}
382				Some(_) => {}
383				None => unstated.push(epoch),
384			}
385		}
386		candidates.sort_by(|a, b| b.cmp(a));
387		let departures = self.secrets_departures(space, roster)?;
388		let mut writing = None;
389		for &((_, rotation), epoch) in &candidates {
390			if log.builds_on_all(rotation, &departures)? {
391				writing = Some(epoch);
392				break;
393			}
394		}
395		let safe = writing.is_some() || (candidates.is_empty() && departures.is_empty());
396		// Never by the number alone, which is a random one: a key that no statement names
397		// before one that someone not a member made.
398		let writing = writing
399			.or_else(|| {
400				candidates
401					.iter()
402					.find(|((_, rotation), _)| counting.contains(rotation))
403					.map(|(_, epoch)| *epoch)
404			})
405			.or_else(|| unstated.first().copied())
406			.or_else(|| candidates.first().map(|(_, epoch)| *epoch));
407		let open = self
408			.spaces
409			.get_mut(&space)
410			.ok_or(NodeError::NoSpace(space))?;
411		open.keys.write_secrets_with(writing);
412		Ok(safe)
413	}
414
415	/// While the secrets are unlocked, after they settle: in each space whose secrets this
416	/// replica holds, and where it remains, has a key of its own and is no AI agent's, makes
417	/// a new secrets key if none is safe, and gives the keys it holds to the replicas known to
418	/// hold the secrets that lack them.
419	pub(super) fn settle_secrets_keys(
420		&mut self,
421		wall_millis: u64,
422		rng: &mut impl CryptoRng,
423	) -> Result<(), NodeError> {
424		let own_key = self.replica.signing.verifying_key();
425		let personal = self.personal_holders()?;
426		for space in self.secret_spaces()? {
427			if !self.secrets_unlocked(space) {
428				continue;
429			}
430			let open = self.space(space)?;
431			let log = open.stored.log();
432			if log.is_revoked(&own_key, &open.keys)?
433				|| !log.is_listed(&own_key, &open.keys)?
434				|| log.is_ai_agent(&own_key, &open.keys)?
435				|| log.is_removed(&own_key, &open.keys)?
436			{
437				continue;
438			}
439			let roster = self.roster(space)?;
440			if roster.owner_of(&own_key) != Some(self.own_record(space)?) {
441				continue;
442			}
443			if !self.choose_secrets_key_with(space, &roster)? {
444				self.new_secrets_key(space, (&roster, personal.as_ref()), wall_millis, rng)?;
445			}
446			let roster = self.roster(space)?;
447			self.give_secrets_to_holders(space, (&roster, personal.as_ref()), wall_millis, rng)?;
448		}
449		Ok(())
450	}
451
452	/// This user's replicas known to hold the personal space's secrets, as
453	/// [`PersonalHolders`] says, while this replica's are unlocked.
454	fn personal_holders(&self) -> Result<Option<PersonalHolders>, NodeError> {
455		let personal = self.info.personal;
456		if !self.secrets_unlocked(personal) {
457			return Ok(None);
458		}
459		let roster = self.roster(personal)?;
460		let given = self.given_out(personal, &roster)?;
461		let mut links = std::collections::BTreeMap::new();
462		for holder in self.known_holders(personal, &roster, self.info.replica, None)? {
463			if let Some(key) = given
464				.iter()
465				.find(|key| holder.has.contains(&(key.epoch, key.hash)))
466			{
467				links.insert(holder.replica, (personal, key.epoch, key.key.clone()));
468			}
469		}
470		let read = self.read_personal()?;
471		let holding = Self::newest_choices(&read, &roster)
472			.into_iter()
473			.filter(|(_, (_, choice))| choice.holds)
474			.map(|((space, _), (record, _))| (space, record))
475			.collect();
476		Ok(Some(PersonalHolders {
477			roster,
478			links,
479			holding,
480		}))
481	}
482
483	/// The replicas of a space, but this one's record `own`, known to hold the secrets: those
484	/// that remain, are no AI agent's, have a secrets encryption key, and that this replica
485	/// gave a secrets key, or that a counting gift to whose key carries a link that a key it
486	/// holds checks, or that it takes the secrets from. A replica that only says it holds the
487	/// secrets, with a key of its own making, is none of these.
488	fn known_holders(
489		&self,
490		space: SpaceId,
491		roster: &Roster,
492		own: EntityId,
493		personal: Option<&PersonalHolders>,
494	) -> Result<Vec<Holder>, NodeError> {
495		// In another space, this user's replicas known to hold the personal space's secrets
496		// too: the person chose them already.
497		let personal = personal.filter(|_| space != self.info.personal);
498		let remaining = self.remaining(space, roster, &[])?;
499		let open = self.space(space)?;
500		let log = open.stored.log();
501		let own_key = self.replica.signing.verifying_key();
502		let asked = roster.secrets_from(own);
503		let mut holders = Vec::new();
504		'replicas: for (replica, _) in remaining {
505			if replica == own {
506				continue;
507			}
508			for key in roster.keys_of(replica) {
509				if log.is_ai_agent(key, &open.keys)? {
510					continue 'replicas;
511				}
512			}
513			let Some(encryption) = roster.secrets_encryption_of(replica) else {
514				continue;
515			};
516			let recipient = nibkeep_governance::secrets_recipient(encryption);
517			let giver = roster
518				.secrets_from(replica)
519				.and_then(|from| roster.own_key_of(from));
520			let mut known = asked == Some(replica);
521			let mut has = BTreeSet::new();
522			for gift in roster.secrets_gifts(replica) {
523				let ours = gift.author == own_key;
524				// Its own gifts whether they count or not, which giving again would not change.
525				if gift.sealed.recipient != recipient || !(gift.counts || ours) {
526					continue;
527				}
528				let link = &gift.sealed.link;
529				let linked = (link.space == space || link.space == self.info.personal)
530					&& self.space(link.space).is_ok_and(|linked| {
531						linked
532							.keys
533							.secrets(link.epoch)
534							.is_some_and(|key| gift.sealed.link_holds(space, replica, key))
535					});
536				known |= linked || ours;
537				if linked || ours || giver == Some(&gift.author) {
538					has.insert((gift.sealed.epoch, gift.sealed.hash));
539				}
540			}
541			// Only a replica that holds the space, by its newest choice of it in the personal
542			// space: one that declined it, or never took it, as a phone through a group, is
543			// given none of its secrets by its user's devices.
544			let personal_link = personal.and_then(|personal| {
545				roster.keys_of(replica).iter().find_map(|key| {
546					personal
547						.roster
548						.replica_of(key)
549						.filter(|record| personal.holding.contains(&(space, *record)))
550						.and_then(|record| personal.links.get(&record))
551				})
552			});
553			known |= personal_link.is_some();
554			if known {
555				holders.push(Holder {
556					replica,
557					encryption: encryption.clone(),
558					has,
559					personal: personal_link.cloned(),
560				});
561			}
562		}
563		holders.extend(self.code_holders(space, roster, personal)?);
564		Ok(holders)
565	}
566
567	/// The recovery codes of a space known to hold its secrets, as
568	/// [`Library::known_holders`] knows replicas to: those that stand, whose members have a
569	/// role, and that this replica gave a secrets key, or that a counting gift to whose
570	/// secrets encryption key carries a link that a key it holds checks; and, in a space other
571	/// than the personal one, the codes of this user's that are known to hold the personal
572	/// space's secrets. A code asks nobody: the replica that made it gave it the secrets, as
573	/// its person chose then
574	/// ([technical design](../../../../docs/Technical-design.md#111-recovery-codes)).
575	fn code_holders(
576		&self,
577		space: SpaceId,
578		roster: &Roster,
579		personal: Option<&PersonalHolders>,
580	) -> Result<Vec<Holder>, NodeError> {
581		let own_key = self.replica.signing.verifying_key();
582		let standing: BTreeSet<EntityId> = self
583			.key_recipients(space, roster, &[])?
584			.into_iter()
585			.map(|(record, _)| record)
586			.collect();
587		let mut holders = Vec::new();
588		for code in roster.codes() {
589			if !standing.contains(&code.record) {
590				continue;
591			}
592			let encryption = &code.statement.secrets_encryption;
593			let recipient = nibkeep_governance::secrets_recipient(encryption);
594			let mut known = false;
595			let mut has = BTreeSet::new();
596			for gift in roster.secrets_gifts(code.record) {
597				let ours = gift.author == own_key;
598				if gift.sealed.recipient != recipient || !(gift.counts || ours) {
599					continue;
600				}
601				let link = &gift.sealed.link;
602				let linked = (link.space == space || link.space == self.info.personal)
603					&& self.space(link.space).is_ok_and(|linked| {
604						linked
605							.keys
606							.secrets(link.epoch)
607							.is_some_and(|key| gift.sealed.link_holds(space, code.record, key))
608					});
609				if linked || ours {
610					known = true;
611					has.insert((gift.sealed.epoch, gift.sealed.hash));
612				}
613			}
614			// The same code, in the personal space, by its recovery key.
615			let personal_link = personal.and_then(|personal| {
616				personal
617					.roster
618					.codes()
619					.filter(|named| named.statement.key == code.statement.key)
620					.find_map(|named| personal.links.get(&named.record))
621			});
622			known |= personal_link.is_some();
623			if known {
624				holders.push(Holder {
625					replica: code.record,
626					encryption: encryption.clone(),
627					has,
628					personal: personal_link.cloned(),
629				});
630			}
631		}
632		Ok(holders)
633	}
634
635	/// Gives a recovery code of the person's the secrets keys of the personal space that this
636	/// replica holds and gives out, and that the code has not been given, each sealed to the
637	/// secrets encryption key that the code signed, in one change that governs the space;
638	/// the first linked with itself, so that every holder knows that the code holds them, and
639	/// gives it the keys made later. The person chose so, with the secrets unlocked.
640	pub(super) fn give_code_secrets(
641		&mut self,
642		record: EntityId,
643		wall_millis: u64,
644		rng: &mut impl CryptoRng,
645	) -> Result<(), NodeError> {
646		let personal = self.info.personal;
647		if !self.secrets_unlocked(personal) {
648			return Err(NodeError::SecretsLocked);
649		}
650		let roster = self.roster(personal)?;
651		let Some(code) = roster.code(record) else {
652			return Err(NodeError::NoEntity(record.to_string()));
653		};
654		let encryption = code.statement.secrets_encryption.clone();
655		let recipient = nibkeep_governance::secrets_recipient(&encryption);
656		let has: BTreeSet<(u64, Hash)> = roster
657			.secrets_gifts(record)
658			.iter()
659			.filter(|gift| gift.sealed.recipient == recipient)
660			.map(|gift| (gift.sealed.epoch, gift.sealed.hash))
661			.collect();
662		let holder = Holder {
663			replica: record,
664			encryption,
665			has,
666			personal: None,
667		};
668		let given = self.given_out(personal, &roster)?;
669		let operations: Vec<nibkeep_model::Operation> = given
670			.iter()
671			.filter(|key| !holder.has.contains(&(key.epoch, key.hash)))
672			.map(|key| {
673				linked_gift(
674					personal,
675					&holder,
676					(key.epoch, &key.key, key.hash),
677					&given,
678					rng,
679				)
680			})
681			.collect();
682		if operations.is_empty() {
683			return Ok(());
684		}
685		self.commit(personal, operations, wall_millis, rng)
686	}
687
688	/// The secrets keys of a space that this replica holds and gives out, the newest first,
689	/// by their rotations.
690	fn given_out(&self, space: SpaceId, roster: &Roster) -> Result<Vec<GivenOut>, NodeError> {
691		let open = self.space(space)?;
692		let mut makers = Makers::of(open);
693		let mut given = Vec::new();
694		for (epoch, key) in open.keys.secrets_keys() {
695			let hash = key_hash(key);
696			if let Some(rotation) = roster.secrets_rotation(epoch, &hash)
697				&& makers.made(rotation.change)?
698			{
699				given.push(GivenOut {
700					rotation: (rotation.at, rotation.change),
701					epoch,
702					key: key.clone(),
703					hash,
704				});
705			}
706		}
707		given.sort_by_key(|key| std::cmp::Reverse(key.rotation));
708		Ok(given)
709	}
710
711	/// Gives the secrets keys of a space that this replica holds and gives out to the
712	/// replicas known to hold the secrets that lack them, in one change that governs the
713	/// space: each linked with the newest key given to that replica that this one holds, so
714	/// that it takes the key from this one, or else with the key itself, so that the others
715	/// know this one held it.
716	fn give_secrets_to_holders(
717		&mut self,
718		space: SpaceId,
719		(roster, personal): (&Roster, Option<&PersonalHolders>),
720		wall_millis: u64,
721		rng: &mut impl CryptoRng,
722	) -> Result<(), NodeError> {
723		let own = self.own_record(space)?;
724		let holders = self.known_holders(space, roster, own, personal)?;
725		let given = self.given_out(space, roster)?;
726		let mut operations = Vec::new();
727		for holder in &holders {
728			for key in &given {
729				if !holder.has.contains(&(key.epoch, key.hash)) {
730					let gift = (key.epoch, &key.key, key.hash);
731					operations.push(linked_gift(space, holder, gift, &given, rng));
732				}
733			}
734		}
735		if operations.is_empty() {
736			return Ok(());
737		}
738		self.commit(space, operations, wall_millis, rng)
739	}
740
741	/// Sets up the secrets of a shared space whose secrets no remaining replica holds, as the
742	/// first secret value written there does, on an admin's replica that holds the secrets
743	/// compartment open: a secrets key of a random number, saved in the compartment first,
744	/// then, in one change that governs the space, this replica's secrets encryption key,
745	/// that it takes the secrets from itself, and the key given to itself, linked with the
746	/// personal space's key it seals with, so that this user's other replicas take it.
747	///
748	/// # Errors
749	///
750	/// Returns [`NodeError::SpaceSecretsElsewhere`] if another replica that remains holds the
751	/// space's secrets, [`NodeError::SetUpSecretsFirst`] if this replica has no secrets
752	/// compartment, [`NodeError::SecretsLocked`] if it is locked, [`NodeError::AdminsOnly`]
753	/// if this replica's member is no admin of the space, [`NodeError::ForeignKey`] if its
754	/// record lists a key it did not make, and an error if the key file or the change cannot
755	/// be saved.
756	pub(super) fn set_up_space_secrets(
757		&mut self,
758		space: SpaceId,
759		wall_millis: u64,
760		rng: &mut impl CryptoRng,
761	) -> Result<(), NodeError> {
762		self.check_not_ai_agent("hold secrets")?;
763		let compartment = self.open_compartment()?;
764		// Another program may have saved the space's keys since: they are opened.
765		let held = self.key_file_on_disk()?.secrets(&compartment)?;
766		if held.spaces.get(&space).is_some_and(|keys| !keys.is_empty()) {
767			return self.open_secrets(&held);
768		}
769		// Linked with a key of the personal space, so that this user's other replicas take
770		// it: one that asked for the secrets, and was not given them yet, sets up none.
771		if !self.secrets_unlocked(self.info.personal) {
772			return Err(NodeError::SecretsElsewhere);
773		}
774		let roster = self.roster(space)?;
775		let own = self.own_record(space)?;
776		for holder in roster.secrets_holders() {
777			if holder != own && self.is_remaining(space, &roster, holder)? {
778				return Err(NodeError::SpaceSecretsElsewhere);
779			}
780		}
781		self.check_admin(space, "set up the secrets of a shared space")?;
782		if roster.owner_of(&self.replica.signing.verifying_key()) != Some(own) {
783			return Err(NodeError::ForeignKey);
784		}
785		let mut known = roster.secrets_numbers();
786		known.extend(
787			held.spaces
788				.get(&space)
789				.into_iter()
790				.flatten()
791				.map(|(epoch, _)| *epoch),
792		);
793		let epoch = fresh_number(&known, rng);
794		let key = Key::generate(rng);
795		let hash = key_hash(&key);
796		self.update_key_file(|key_file| {
797			let mut keys = key_file.secrets(&compartment)?;
798			keys.spaces
799				.entry(space)
800				.or_default()
801				.insert(epoch, key.clone());
802			key_file.update_secrets(&keys, &compartment, rng)?;
803			Ok(())
804		})?;
805		self.spaces
806			.get_mut(&space)
807			.ok_or(NodeError::NoSpace(space))?
808			.keys
809			.insert_secrets(epoch, key.clone());
810		let encryption = held.decryption.encryption_key();
811		let mut operations = Vec::new();
812		if roster.secrets_encryption_of(own) != Some(&encryption) {
813			operations.push(nibkeep_governance::state_secrets_key(own, &encryption, rng));
814		}
815		operations.push(nibkeep_governance::state_secrets_from(own, own, rng));
816		let personal = self.info.personal;
817		let link = self
818			.space(personal)?
819			.keys
820			.newest_secrets()
821			.map(|(epoch, key)| (personal, epoch, key.clone()));
822		let (link_space, link_epoch, link_key) = link.unwrap_or((space, epoch, key.clone()));
823		let mine = SealedSecretsKey::seal(
824			&encryption,
825			space,
826			own,
827			(epoch, &key, hash),
828			(link_space, link_epoch, &link_key),
829			rng,
830		);
831		operations.push(nibkeep_governance::give_secrets_key(own, &mine, rng));
832		self.commit(space, operations, wall_millis, rng)?;
833		let roster = self.roster(space)?;
834		self.choose_secrets_key_with(space, &roster)?;
835		// This user's other replicas that hold the secrets get it at once.
836		let personal = self.personal_holders()?;
837		self.give_secrets_to_holders(space, (&roster, personal.as_ref()), wall_millis, rng)
838	}
839
840	/// Gives a space a new secrets key, whose number is a random one that no secrets key of
841	/// the space has: saved in the secrets compartment first, then given to this replica,
842	/// linked with the key it sealed with until now, and to the replicas known to hold the
843	/// secrets, as [`Library::give_secrets_to_holders`] links them, in one change that
844	/// governs the space. New secret values are sealed with it.
845	fn new_secrets_key(
846		&mut self,
847		space: SpaceId,
848		(roster, personal): (&Roster, Option<&PersonalHolders>),
849		wall_millis: u64,
850		rng: &mut impl CryptoRng,
851	) -> Result<(), NodeError> {
852		let Some(compartment) = self.secrets_compartment.clone() else {
853			return Ok(());
854		};
855		let own = self.own_record(space)?;
856		let Some(own_encryption) = roster.secrets_encryption_of(own).cloned() else {
857			return Ok(());
858		};
859		let open = self.space(space)?;
860		let mut known: BTreeSet<u64> = open.keys.secrets_keys().map(|(epoch, _)| epoch).collect();
861		known.extend(roster.secrets_numbers());
862		let epoch = fresh_number(&known, rng);
863		let previous = open
864			.keys
865			.newest_secrets()
866			.map(|(epoch, key)| (epoch, key.clone()));
867		let key = Key::generate(rng);
868		let hash = key_hash(&key);
869		// Saved before it is given, as space keys are.
870		self.update_key_file(|key_file| {
871			let mut keys = key_file.secrets(&compartment)?;
872			keys.spaces
873				.entry(space)
874				.or_default()
875				.insert(epoch, key.clone());
876			key_file.update_secrets(&keys, &compartment, rng)?;
877			Ok(())
878		})?;
879		self.spaces
880			.get_mut(&space)
881			.ok_or(NodeError::NoSpace(space))?
882			.keys
883			.insert_secrets(epoch, key.clone());
884		let (link_epoch, link_key) = previous
885			.as_ref()
886			.map_or((epoch, &key), |(epoch, key)| (*epoch, key));
887		let mine = SealedSecretsKey::seal(
888			&own_encryption,
889			space,
890			own,
891			(epoch, &key, hash),
892			(space, link_epoch, link_key),
893			rng,
894		);
895		let mut operations = vec![nibkeep_governance::give_secrets_key(own, &mine, rng)];
896		let given = self.given_out(space, roster)?;
897		for holder in &self.known_holders(space, roster, own, personal)? {
898			operations.push(linked_gift(space, holder, (epoch, &key, hash), &given, rng));
899		}
900		self.commit(space, operations, wall_millis, rng)?;
901		let roster = self.roster(space)?;
902		self.choose_secrets_key_with(space, &roster)?;
903		Ok(())
904	}
905}
906
907/// The operation that gives `holder` of `space` the secrets key `key`, by its number, the
908/// key and its hash, linked with the newest of `given` that `holder` was given, or else with
909/// the personal space's key that `holder` names, or else with `key` itself.
910fn linked_gift(
911	space: SpaceId,
912	holder: &Holder,
913	(epoch, key, hash): (u64, &Key, Hash),
914	given: &[GivenOut],
915	rng: &mut impl CryptoRng,
916) -> nibkeep_model::Operation {
917	let link = given
918		.iter()
919		.find(|link| holder.has.contains(&(link.epoch, link.hash)))
920		.map(|link| (space, link.epoch, &link.key))
921		.or_else(|| {
922			holder
923				.personal
924				.as_ref()
925				.map(|(space, epoch, key)| (*space, *epoch, key))
926		})
927		.unwrap_or((space, epoch, key));
928	let sealed = SealedSecretsKey::seal(
929		&holder.encryption,
930		space,
931		holder.replica,
932		(epoch, key, hash),
933		link,
934		rng,
935	);
936	nibkeep_governance::give_secrets_key(holder.replica, &sealed, rng)
937}