Skip to main content

nibkeep_node/library/
sync.rs

1//! The library's replicas, and what pairing and syncing read and change: the list of
2//! replicas in the personal space, a new replica's records, and each space's changes, keys
3//! and blobs ([Sync](../../../../docs/spec/sync.md), [Identity](../../../../docs/spec/identity.md#3-a-new-replica)).
4
5use std::cell::RefCell;
6use std::collections::{BTreeMap, BTreeSet};
7use std::fs;
8use std::io::Read;
9use std::path::Path;
10use std::rc::Rc;
11use std::time::{Duration, Instant};
12
13use getrandom::SysRng;
14use getrandom::rand_core::UnwrapErr;
15use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
16use nibkeep_crypto::rand_core::CryptoRng;
17use nibkeep_crypto::{DecryptionKey, Key, Signature, SigningKey, VerifyingKey};
18use nibkeep_governance::{
19	ENCRYPTION_KEY, ENDPOINT, Grant, JoinRequest, Listing, MAX_NAME_LEN, NewReplica,
20	RecoveryListing, SealedSpaceKey, encryption_key_text, endpoint_of_text, endpoint_secret,
21	endpoint_text,
22};
23use nibkeep_keys::{
24	CompartmentKey, KeyFile, NewProtection, ReplicaKeys, SealedSecrets, SecretsKeys, SpaceKeyMap,
25};
26use nibkeep_log::{ChangeId, LogError, Parcel, Received, WrappedBlobKey, WrappedKey};
27use nibkeep_model::{Operation, Statement, Value, fields};
28use nibkeep_store::{StoreError, log_path};
29use nibkeep_sync::{Challenge, Holder, Holding, Sponsoring};
30
31use super::planner::Keeps;
32use super::removal::{Removals, answer_from_file};
33use super::secrets::SecretsState;
34use super::taking::NewDevice;
35use super::{INFO, KEYS, Library, Space, code_types, new_replica_folder};
36use crate::NodeError;
37use crate::info::Info;
38use crate::role::Records;
39
40/// A replica of the library, as its personal space lists it.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[expect(
43	clippy::struct_excessive_bools,
44	reason = "each says something apart of the replica, which lists show apart"
45)]
46pub struct Replica {
47	/// The replica.
48	pub id: EntityId,
49	/// Its name: the name of the app that keeps it.
50	pub name: Option<String>,
51	/// Its device.
52	pub device: Option<EntityId>,
53	/// Its device's name.
54	pub device_name: Option<String>,
55	/// Its endpoint ID, which the others connect to, if it has one.
56	pub endpoint: Option<[u8; 32]>,
57	/// Its verifying key.
58	pub signing: Option<VerifyingKey>,
59	/// Whether it is this replica.
60	pub this: bool,
61	/// Whether it was revoked, every key of it: no replica sends it anything, and of its
62	/// changes only those that every replica which revoked it had count.
63	pub revoked: bool,
64	/// Whether its record was deleted, which keeps it from nothing: only revoking does.
65	pub deleted: bool,
66	/// Whether it is an AI agent's, as the change that listed its key says.
67	pub ai_agent: bool,
68	/// How many of its changes are set aside in the personal space, waiting for review.
69	pub set_aside: usize,
70	/// Whether it holds the secrets: the records give it the secrets keys.
71	pub holds_secrets: bool,
72	/// Whether the records give it any secrets key at all, by whichever replica, so that it
73	/// may read the secrets: what revoking it cannot take back. A replica that turned against
74	/// its user can stop holding them, as the records say, by listing a key on its record.
75	pub given_secrets: bool,
76	/// Whether it asked for the secrets, and was not given them yet.
77	pub asks_for_secrets: bool,
78	/// The replica it takes the secrets from: the one it asked, or itself.
79	pub secrets_from: Option<EntityId>,
80	/// For another user's replica, a shared space that lists it, with which this replica
81	/// syncs it; `None` for the user's own.
82	pub shared: Option<SpaceId>,
83	/// For another user's replica, the name of the member it is of there.
84	pub member: Option<String>,
85	/// How the person marked its device: as an archive node, and as kept away from home;
86	/// for another user's replica, unmarked, as only its own account says.
87	pub marks: super::accounts::DeviceMarks,
88}
89
90impl Replica {
91	/// Another member's replica, as a shared space lists it.
92	pub(crate) fn of_member(
93		(space, member): (SpaceId, Option<&str>),
94		replica: &super::members::MemberReplica,
95	) -> Self {
96		Self {
97			id: replica.record,
98			name: replica.app.clone(),
99			device: None,
100			device_name: replica.device.clone(),
101			endpoint: replica.endpoint,
102			signing: Some(replica.signing),
103			this: false,
104			revoked: replica.revoked,
105			deleted: false,
106			ai_agent: replica.ai_agent,
107			set_aside: 0,
108			holds_secrets: false,
109			given_secrets: false,
110			asks_for_secrets: false,
111			secrets_from: None,
112			shared: Some(space),
113			member: member.map(str::to_owned),
114			marks: super::accounts::DeviceMarks::default(),
115		}
116	}
117}
118
119impl Library {
120	/// The 32-byte secret of this replica's endpoint key, derived from its signing key.
121	pub(crate) fn endpoint_secret(&self) -> Key {
122		endpoint_secret(&self.replica.signing)
123	}
124
125	/// This replica's endpoint ID.
126	#[must_use]
127	pub fn endpoint(&self) -> [u8; 32] {
128		endpoint_of(&self.endpoint_secret())
129	}
130
131	/// The replicas that the personal space's counting governing changes list, with what
132	/// their records say of them, revoked and deleted ones too, as all of them but the
133	/// revoked sync: this one first, then the others by ID.
134	///
135	/// # Errors
136	///
137	/// Returns an error if the personal space cannot be read.
138	pub fn replicas(&self) -> Result<Vec<Replica>, NodeError> {
139		let personal = &self.spaces[&self.info.personal];
140		let roster = personal.stored.log().roster(&personal.keys)?;
141		let log = personal.stored.log();
142		let state = log.state();
143		let name = |entity: EntityId| {
144			super::entities::display_name(state, &personal.types, &self.languages, entity)
145		};
146		// The changes set aside, by the key that signed them.
147		let mut set_aside: std::collections::BTreeMap<[u8; 32], usize> =
148			std::collections::BTreeMap::new();
149		for id in log.set_aside_changes()? {
150			if let Some(change) = log.change(id)? {
151				*set_aside.entry(*change.author().as_bytes()).or_default() += 1;
152			}
153		}
154		let holders = roster.secrets_holders();
155		let mut replicas = Vec::new();
156		for id in roster.replicas() {
157			// What the record says only names it: a record without a type, or deleted, or
158			// another owner's, is of a replica all the same.
159			let record = nibkeep_governance::replica(state, id)?;
160			let keys = roster.keys_of(id);
161			let mut revoked = true;
162			let mut ai_agent = false;
163			for key in keys {
164				revoked &= log.is_revoked(key, &personal.keys)?;
165				ai_agent |= log.is_ai_agent(key, &personal.keys)?;
166			}
167			let device = record.as_ref().and_then(|record| record.device);
168			replicas.push(Replica {
169				id,
170				name: name(id)?,
171				device,
172				device_name: device.map(name).transpose()?.flatten(),
173				endpoint: record.as_ref().and_then(|record| record.endpoint),
174				signing: keys.first().copied(),
175				this: id == self.info.replica,
176				revoked,
177				deleted: record.is_none_or(|record| record.deleted),
178				ai_agent,
179				set_aside: keys
180					.iter()
181					.filter_map(|key| set_aside.get(key.as_bytes()))
182					.sum(),
183				holds_secrets: holders.contains(&id),
184				given_secrets: roster.given_any_secrets(id),
185				asks_for_secrets: roster.secrets_encryption_of(id).is_some()
186					&& roster.secrets_from(id).is_some_and(|from| from != id)
187					&& !holders.contains(&id),
188				secrets_from: roster.secrets_from(id),
189				shared: None,
190				member: None,
191				marks: device
192					.map(|device| self.device_marks(device))
193					.transpose()?
194					.unwrap_or_default(),
195			});
196		}
197		replicas.sort_by_key(|replica| (!replica.this, replica.id));
198		Ok(replicas)
199	}
200
201	/// The replicas to sync with: the user's other replicas, then those of other members of
202	/// the shared spaces that this replica is listed in, each with an endpoint and not
203	/// revoked.
204	///
205	/// # Errors
206	///
207	/// Returns an error if a space cannot be read.
208	pub fn peers(&self) -> Result<Vec<Replica>, NodeError> {
209		let own = self.replica.signing.verifying_key();
210		let mut peers: Vec<Replica> = self
211			.replicas()?
212			.into_iter()
213			.filter(|replica| {
214				!replica.this
215					&& !replica.revoked
216					&& replica.endpoint.is_some()
217					&& replica.signing != Some(own)
218			})
219			.collect();
220		for other in self.other_members_replicas() {
221			if !peers.iter().any(|peer| peer.signing == other.signing) {
222				peers.push(other);
223			}
224		}
225		Ok(peers)
226	}
227
228	/// Makes sure that this replica's record has its current encryption key and endpoint ID,
229	/// which an AI agent may have taken away.
230	/// An AI agent's replica, which may not write them, leaves them to the replica that paired
231	/// it.
232	///
233	/// # Errors
234	///
235	/// Returns an error if the personal space cannot be read or the change saved.
236	pub fn record_own_endpoint(
237		&mut self,
238		wall_millis: u64,
239		rng: &mut impl CryptoRng,
240	) -> Result<(), NodeError> {
241		if self.is_ai_agent()? {
242			return Ok(());
243		}
244		let personal = &self.spaces[&self.info.personal];
245		let roster = personal.stored.log().roster(&personal.keys)?;
246		let state = personal.stored.log().state();
247		let endpoint = self.endpoint();
248		let mut operations = Vec::new();
249		if roster.encryption_of(self.info.replica).is_none() {
250			operations.push(Operation::assert(Statement::new(
251				StatementId::random(rng),
252				self.info.replica,
253				ENCRYPTION_KEY,
254				Value::Text(encryption_key_text(
255					&self.replica.decryption.encryption_key(),
256				)),
257			)));
258		}
259		// Read as the record reads it, the first that is an endpoint ID, but also where the
260		// record is no longer a replica's, which an infected device of the user's can make
261		// it: else this replica would state its endpoint again at every sync.
262		let stated = state.current(self.info.replica, &ENDPOINT)?;
263		let first = stated
264			.iter()
265			.filter_map(|statement| statement.value.as_text())
266			.find_map(endpoint_of_text);
267		if first != Some(endpoint) {
268			let current: Vec<StatementId> = stated.iter().map(|statement| statement.id).collect();
269			operations.push(Operation::replace(
270				Statement::new(
271					StatementId::random(rng),
272					self.info.replica,
273					ENDPOINT,
274					Value::Text(endpoint_text(&endpoint)),
275				),
276				current,
277			));
278		}
279		if operations.is_empty() {
280			return Ok(());
281		}
282		self.commit(self.info.personal, operations, wall_millis, rng)
283	}
284
285	/// What to grant a replica that asks to join, and the operations that record it, as
286	/// the identity specification says: who it is, and every space key sealed to it, and for
287	/// an AI agent's replica, that it is one, named after the AI agent. This replica's own
288	/// record gets its encryption key and endpoint ID first, if it lacks them, and the keys it
289	/// holds.
290	fn prepare_replica(
291		&mut self,
292		request: &JoinRequest,
293		(endpoint, ai_agent, give_secrets): (&[u8; 32], Option<&str>, bool),
294		wall_millis: u64,
295		rng: &mut impl CryptoRng,
296	) -> Result<(Grant, Vec<Operation>, AskedFor), NodeError> {
297		self.record_own_endpoint(wall_millis, rng)?;
298		// So that the new replica knows which keys this one holds, and gives it none of them.
299		self.give_keys(self.info.personal, wall_millis, rng)?;
300		// The new replica's record is derived from the space and its key, as the keys are
301		// sealed to it.
302		let replica = nibkeep_governance::replica_record(self.info.personal, &request.signing);
303		// Only the personal space's keys: the others reach a new replica as they reach every
304		// replica of the user, through the personal space, once it asks to be listed there,
305		// and never an AI agent's.
306		let personal_keys: std::collections::BTreeMap<_, _> = self
307			.replica
308			.spaces
309			.iter()
310			.filter(|(space, _)| **space == self.info.personal)
311			.map(|(space, keys)| (*space, keys.clone()))
312			.collect();
313		let sealed =
314			nibkeep_governance::seal_space_keys(&request.encryption, replica, &personal_keys, rng);
315		// Its records state the keys of the personal space it is granted, as sealed, but key
316		// 0, which every replica holds, and keys whose rotation does not count, which no
317		// replica writes with: so that a statement of a key never makes it count.
318		let personal = self.info.personal;
319		let roster = self.roster(personal)?;
320		let mut makers = super::revocation::Makers::of(self.space(personal)?);
321		let mut granted: Vec<SealedSpaceKey> = Vec::new();
322		for (epoch, sealed) in sealed
323			.iter()
324			.filter(|space| space.space == personal)
325			.flat_map(|space| &space.keys)
326		{
327			let Some(key) = self
328				.replica
329				.spaces
330				.get(&personal)
331				.and_then(|keys| keys.get(epoch))
332			else {
333				continue;
334			};
335			let hash = nibkeep_crypto::key_hash(key);
336			if let Some(rotation) = roster.rotation(*epoch, &hash)
337				&& makers.made(rotation.change)?
338			{
339				granted.push(SealedSpaceKey {
340					epoch: *epoch,
341					hash,
342					sealed: sealed.clone(),
343				});
344			}
345		}
346		drop(makers);
347		// It asks this replica for the secrets, if the records say that this one holds them,
348		// and is given them, if the person chose to, and they are unlocked; it states itself
349		// that it asks, after its first sync, as only its own key may. A key that the
350		// library's passphrase opens would make the two layers one.
351		let asks = match &request.secrets {
352			Some(key) if *key == request.encryption => {
353				return Err(NodeError::Damaged(
354					"the new replica asks for the secrets with the key of its replica".to_owned(),
355				));
356			}
357			Some(key) if ai_agent.is_none() && self.secrets_state()? == SecretsState::Here => {
358				let unlocked = give_secrets && self.unlock_kept_secrets()?;
359				if unlocked {
360					// Records that do not say yet that this replica holds them say so now.
361					self.settle_secrets(wall_millis, rng)?;
362				}
363				let own = self.info.replica;
364				let holds = self.roster(personal)?.secrets_holders().contains(&own);
365				let given = if unlocked && holds {
366					let held = self.space(personal)?.keys.secrets_keys();
367					super::secrets::sealed_secrets_keys(held, (personal, replica), key, rng)
368				} else {
369					Vec::new()
370				};
371				holds.then_some(given)
372			}
373			_ => None,
374		};
375		let asked_for = match &asks {
376			None => AskedFor::Nothing,
377			Some(given) if given.is_empty() => AskedFor::Secrets,
378			Some(_) => AskedFor::SecretsGiven,
379		};
380		let added = nibkeep_governance::add_replica(
381			&NewReplica {
382				space: personal,
383				user: self.info.user,
384				signing: &request.signing,
385				encryption: &request.encryption,
386				endpoint,
387				device: &request.device,
388				app: ai_agent.unwrap_or(&request.app),
389				keys: &granted,
390				ai_agent: ai_agent.is_some(),
391				given: asks.as_deref().unwrap_or_default(),
392				// Its key signs its listing once it knows who it is, from the grant.
393				listing: None,
394			},
395			rng,
396		);
397		let mut operations = added.governing;
398		operations.extend(added.operations);
399		let grant = Grant {
400			chosen: Vec::new(),
401			asks_first: false,
402			user: self.info.user,
403			device: added.device,
404			replica: added.replica,
405			space: personal,
406			sponsor: self.replica.signing.verifying_key(),
407			keys: sealed,
408			ai_agent: ai_agent.is_some(),
409		};
410		Ok((grant, operations, asked_for))
411	}
412
413	/// Revokes a replica that pairing added, after its first sync failed: the pairing
414	/// failed, and as it got the space keys, the personal space gets a new key. Its records
415	/// and its device's are deleted too, so that they are not listed.
416	pub(crate) fn forget_replica(
417		&mut self,
418		grant: &Grant,
419		key: &VerifyingKey,
420		wall_millis: u64,
421		rng: &mut impl CryptoRng,
422	) -> Result<(), NodeError> {
423		self.revoke_key(grant.replica, key, wall_millis, rng)?;
424		let operations = [grant.replica, grant.device]
425			.into_iter()
426			.map(|entity| {
427				Operation::assert(Statement::new(
428					StatementId::random(rng),
429					entity,
430					fields::DELETED,
431					Value::Boolean(true),
432				))
433			})
434			.collect();
435		self.commit(self.info.personal, operations, wall_millis, rng)
436	}
437}
438
439/// The public half of an endpoint key: an Ed25519 key, as the signing keys are.
440pub(crate) fn endpoint_of(secret: &Key) -> [u8; 32] {
441	*SigningKey::from_bytes(secret.expose_bytes())
442		.verifying_key()
443		.as_bytes()
444}
445
446/// The library as a sync reads and changes it.
447pub struct Syncing<'a> {
448	library: &'a mut Library,
449	/// The key that a new replica trusts for its first sync, for spaces that list no replica
450	/// yet: its sponsor's.
451	trusted: Option<VerifyingKey>,
452	/// The peer that introduced itself with its listings by a recovery code, and the spaces
453	/// and groups where a code that stands here signed its listing, which sync with it as
454	/// with their replicas.
455	introduced: Option<(VerifyingKey, BTreeSet<SpaceId>)>,
456	/// The wall clock, read as each change arrives.
457	now: &'a dyn Fn() -> u64,
458	/// How many blobs and ordinary changes were refused, as the disk would have had too
459	/// little room left.
460	refused: usize,
461	/// How many bytes the disk had free, as last read, less what was received since.
462	free: Option<u64>,
463	/// For each space, the peers that it ended, as found since a governing change last came:
464	/// what ended them, and what they may still get.
465	ended: RefCell<BTreeMap<SpaceId, EndedPeers>>,
466	/// The batch that saves together what is received of a space, if one is open.
467	batch: Option<Receiving>,
468	/// Random numbers for the envelopes of this replica's pages of accounts.
469	rng: UnwrapErr<SysRng>,
470	/// Pages of accounts received and checked, kept together when the batch ends.
471	pages: Vec<(SpaceId, nibkeep_store::StoredPage)>,
472	/// The sealed blobs received, each read whole as it came, with when: checks, recorded
473	/// together as the space's sync ends.
474	received_checks: Vec<(SpaceId, Hash, u64)>,
475	/// What the replica keeps of each space's blobs, as worked out for this sync: again only
476	/// once changes or keys came since, which may change what its files are.
477	plan: Option<BTreeMap<SpaceId, Keeps>>,
478	/// The records of the sync role, opened once the other replica asks for proofs, which
479	/// hold what was proved.
480	records: Option<Records>,
481	/// The pass of removals whose challenges this sync puts to the other replica, if one is.
482	removals: Option<&'a mut Removals>,
483}
484
485/// A batch of what a sync receives of a space, saved together ([technical design: saving in
486/// batches]): changes and record keys, up to [`BATCH_ITEMS`] or for [`BATCH_TIME`].
487///
488/// [technical design: saving in batches]: ../../../../docs/Technical-design.md#77-saving-in-batches
489struct Receiving {
490	space: SpaceId,
491	/// How many items it holds.
492	items: usize,
493	/// When it began.
494	began: Instant,
495}
496
497/// How many items a batch of what a sync receives holds at most, as importers' batches do.
498const BATCH_ITEMS: usize = 1_000;
499
500/// How long a batch of what a sync receives stays open at most, as importers' batches do:
501/// the space's other writers wait meanwhile.
502const BATCH_TIME: Duration = Duration::from_secs(1);
503
504/// For each peer's key, what ended its replica in a space, if anything did.
505type EndedPeers = BTreeMap<[u8; 32], Option<Rc<Ended>>>;
506
507/// What ended a peer's replica in a space, as its member left or was removed, or another
508/// replica of its member's revoked it, and the changes that it may still get: those that
509/// ended it and what they build on, but none at all once it is revoked.
510pub(crate) struct Ended {
511	/// The removals and revocations of it.
512	ending: Vec<ChangeId>,
513	reach: BTreeSet<ChangeId>,
514	revoked: bool,
515}
516
517impl<'a> Syncing<'a> {
518	/// Whether a space syncs with a peer through groups: a group's log with the replicas of
519	/// each space that adds the group, which remain there, as a space's sync carries its
520	/// groups' logs; and a space that this replica has nothing of yet, which a group it is in
521	/// gave it, with the replicas of that group.
522	fn through_groups(
523		&self,
524		id: SpaceId,
525		governed: bool,
526		peer: &VerifyingKey,
527	) -> Result<bool, NodeError> {
528		let own = self.library.replica.signing.verifying_key();
529		for (&other, open) in &self.library.spaces {
530			if other == id || other == self.library.info.personal {
531				continue;
532			}
533			let log = open.stored.log();
534			let remains = |key: &VerifyingKey| -> Result<bool, NodeError> {
535				Ok(log.is_listed(key, &open.keys)?
536					&& !log.is_revoked(key, &open.keys)?
537					&& !log.is_removed(key, &open.keys)?)
538			};
539			let adds = self.library.inner_groups(other)?.contains(&id);
540			if adds && remains(peer)? {
541				return Ok(true);
542			}
543			if !governed
544				&& open.is_group()?
545				&& remains(&own)?
546				&& remains(peer)?
547				&& gave(log, &open.keys, &own, other, id)?
548			{
549				return Ok(true);
550			}
551		}
552		Ok(false)
553	}
554
555	/// A sync of `library`, with the wall clock `now`.
556	pub fn new(library: &'a mut Library, now: &'a dyn Fn() -> u64) -> Self {
557		library.observe_wall(now());
558		Self {
559			library,
560			trusted: None,
561			introduced: None,
562			now,
563			refused: 0,
564			free: None,
565			ended: RefCell::new(BTreeMap::new()),
566			batch: None,
567			rng: UnwrapErr(SysRng),
568			pages: Vec::new(),
569			received_checks: Vec::new(),
570			plan: None,
571			records: None,
572			removals: None,
573		}
574	}
575
576	/// The same, putting to the other replica the challenges that a pass of removals has for
577	/// it, and noting its answers there.
578	#[must_use]
579	pub fn proving(mut self, removals: &'a mut Removals) -> Self {
580		self.removals = Some(removals);
581		self
582	}
583
584	/// What ended `peer`'s replica in a space, if the space ended it, found once for each
585	/// sync of the space, and again after a governing change came.
586	fn ended(&self, space: SpaceId, peer: &VerifyingKey) -> Result<Option<Rc<Ended>>, NodeError> {
587		if let Some(found) = self
588			.ended
589			.borrow()
590			.get(&space)
591			.and_then(|peers| peers.get(peer.as_bytes()))
592		{
593			return Ok(found.clone());
594		}
595		let open = self.library.space(space)?;
596		let log = open.stored.log();
597		let removals = log.removals_of(peer, &open.keys)?;
598		let revocations = log.revocations_of(Some(peer), &open.keys)?;
599		let found = if removals.is_empty() && revocations.is_empty() {
600			None
601		} else {
602			// A revoked replica gets nothing, which would tell it of its revocation.
603			let revoked = !revocations.is_empty();
604			let reach = if revoked {
605				BTreeSet::new()
606			} else {
607				log.with_ancestors(&removals)?
608			};
609			let mut ending = removals;
610			ending.extend(revocations);
611			Some(Rc::new(Ended {
612				ending,
613				reach,
614				revoked,
615			}))
616		};
617		self.ended
618			.borrow_mut()
619			.entry(space)
620			.or_default()
621			.insert(*peer.as_bytes(), found.clone());
622		Ok(found)
623	}
624
625	/// Whether the disk has room for `size` bytes more and 1 GiB besides. The free space is
626	/// read once, and again whenever what was received since may have used up the room.
627	fn has_room(&mut self, size: u64) -> Result<bool, NodeError> {
628		let directory = &self.library.directory;
629		let free = match self.free {
630			Some(free) if leaves_room(free, size.saturating_mul(2)) => free,
631			_ => fs4::available_space(directory).map_err(NodeError::file(directory))?,
632		};
633		if !leaves_room(free, size) {
634			self.free = Some(free);
635			return Ok(false);
636		}
637		self.free = Some(free - size);
638		Ok(true)
639	}
640
641	/// How many blobs and ordinary changes were refused, as the disk would have had less
642	/// than 1 GiB free.
643	#[must_use]
644	pub const fn refused(&self) -> usize {
645		self.refused
646	}
647
648	/// The same, for a new replica's first sync with its sponsor.
649	pub(crate) fn trusting(mut self, sponsor: VerifyingKey) -> Self {
650		self.trusted = Some(sponsor);
651		self
652	}
653
654	fn space(&mut self, space: SpaceId) -> Result<&mut Space, NodeError> {
655		self.library
656			.spaces
657			.get_mut(&space)
658			.ok_or(NodeError::NoSpace(space))
659	}
660
661	/// Saves what comes of `space` in a batch from now on, beginning one unless one is open:
662	/// one of another space ends first. While another program has the space open, which
663	/// would wait for the batch, what comes is saved item by item, as the changes of a burst
664	/// are then.
665	fn batch(&mut self, space: SpaceId) -> Result<(), NodeError> {
666		if self
667			.batch
668			.as_ref()
669			.is_some_and(|batch| batch.space == space)
670		{
671			return Ok(());
672		}
673		self.end_batch()?;
674		let open = self.space(space)?;
675		if open.stored.shared_with_others() {
676			return Ok(());
677		}
678		open.stored.begin_batch(&open.keys)?;
679		self.batch = Some(Receiving {
680			space,
681			items: 0,
682			began: Instant::now(),
683		});
684		Ok(())
685	}
686
687	/// Counts an item that the open batch received, if one is open, and ends the batch once it
688	/// holds [`BATCH_ITEMS`], has been open for [`BATCH_TIME`], or holds a purge, whose
689	/// files and keys are to leave the disk soon.
690	fn received_in_batch(&mut self) -> Result<(), NodeError> {
691		let Some(batch) = &mut self.batch else {
692			return Ok(());
693		};
694		batch.items += 1;
695		let purged = self
696			.library
697			.spaces
698			.get(&batch.space)
699			.is_some_and(|open| open.stored.batch_purged());
700		if purged || batch.items >= BATCH_ITEMS || batch.began.elapsed() >= BATCH_TIME {
701			self.end_batch()?;
702		}
703		Ok(())
704	}
705
706	/// Ends the open batch, if one is, which saves what it received. If saving fails, none of
707	/// it is saved, and what the library keeps of the space is read again.
708	fn end_batch(&mut self) -> Result<(), NodeError> {
709		let ended = match self.batch.take() {
710			None => Ok(()),
711			Some(batch) => {
712				let ended = self.space(batch.space)?.stored.end_batch();
713				if ended.is_err() {
714					let _ = self.library.read_again(batch.space);
715				}
716				ended.map_err(NodeError::from)
717			}
718		};
719		self.save_pages();
720		ended
721	}
722
723	/// Keeps the pages of accounts received since the last were kept, together for each
724	/// space. Accounts only count and show copies, so pages that cannot be kept now, as
725	/// while another program holds the log file, are left for the next sync, which brings
726	/// them again, and the sync goes on.
727	fn save_pages(&mut self) {
728		let pages = std::mem::take(&mut self.pages);
729		let mut by_space: BTreeMap<SpaceId, Vec<nibkeep_store::StoredPage>> = BTreeMap::new();
730		for (space, page) in pages {
731			by_space.entry(space).or_default().push(page);
732		}
733		for (space, pages) in by_space {
734			let _ = self.library.save_accounts(space, &pages);
735		}
736	}
737
738	/// Records the checks of the sealed blobs received: a check that cannot be recorded
739	/// waits for the regular check, and the sync goes on.
740	fn save_received_checks(&mut self) {
741		let mut by_space: BTreeMap<SpaceId, Vec<(Hash, u64)>> = BTreeMap::new();
742		for (space, sealed, at) in std::mem::take(&mut self.received_checks) {
743			by_space.entry(space).or_default().push((sealed, at));
744		}
745		for (space, intact) in by_space {
746			if let Some(open) = self.library.spaces.get_mut(&space) {
747				let _ = open.stored.record_checks(intact, Vec::new(), Vec::new());
748			}
749		}
750	}
751}
752
753impl Syncing<'_> {
754	/// The sealed blobs of a space that the replica keeps and lacks, of those that `lists`
755	/// says another holds, at most `most` of them, none of `asked`: of two of one content,
756	/// the one with the smallest sealed hash of those, unless one held here is smaller.
757	///
758	/// # Errors
759	///
760	/// Returns an error if the library cannot be read.
761	pub(crate) fn wanted_among(
762		&mut self,
763		space: SpaceId,
764		lists: &dyn Fn(&Hash) -> bool,
765		asked: &BTreeSet<Hash>,
766		most: usize,
767	) -> Result<Vec<Hash>, NodeError> {
768		if self.plan.is_none() {
769			self.plan = Some(self.library.plan((self.now)())?);
770		}
771		let keeps = self
772			.plan
773			.as_ref()
774			.and_then(|plan| plan.get(&space))
775			.cloned()
776			.unwrap_or(Keeps::All);
777		let open = self.library.space(space)?;
778		let log = open.stored.log();
779		let held: BTreeSet<Hash> = open.stored.sealed_blobs()?.into_iter().collect();
780		let aside: BTreeSet<Hash> = open.stored.aside_blobs().into_iter().collect();
781		let sealed: BTreeSet<Hash> = log.wrapped_blob_keys().map(|(sealed, _)| *sealed).collect();
782		let mut wanted = Vec::new();
783		for sealed in sealed {
784			if held.contains(&sealed) || asked.contains(&sealed) || !lists(&sealed) {
785				continue;
786			}
787			// A blob whose content this replica cannot tell, as a secret file's while the
788			// secrets are locked, is kept, as every secret file is.
789			let ordinary = !log.is_secret_blob(&sealed);
790			if let Some(content) = log.content_of_sealed(&sealed).filter(|_| ordinary) {
791				// One whose damaged copy is kept aside comes again all the same, so that the
792				// damaged copy goes, and the copy that came then goes the planner's way.
793				if !keeps.keeps(&content) && !aside.contains(&sealed) {
794					continue;
795				}
796				// Of sealed copies of one content, the one with the smallest sealed hash of those
797				// that the other replica holds, unless one held here is smaller: a replica
798				// settles on the smallest, and lets a larger one that it holds go once the
799				// smaller has come.
800				let copies: Vec<Hash> = log
801					.blob_keys(&content)
802					.map(|(copy, _)| *copy)
803					.filter(|copy| !log.is_secret_blob(copy))
804					.collect();
805				let first_listed = copies.iter().filter(|copy| lists(copy)).min();
806				let first_held = copies.iter().filter(|copy| held.contains(copy)).min();
807				if first_listed != Some(&sealed) || first_held.is_some_and(|first| *first < sealed)
808				{
809					continue;
810				}
811			}
812			wanted.push(sealed);
813			if wanted.len() >= most {
814				break;
815			}
816		}
817		Ok(wanted)
818	}
819}
820
821impl Drop for Syncing<'_> {
822	/// Saves what the open batch received, as a sync that fails keeps what it received; after
823	/// a panic, leaves it out, as the log may hold a change half taken.
824	fn drop(&mut self) {
825		if std::thread::panicking() {
826			if let Some(batch) = self.batch.take()
827				&& let Some(open) = self.library.spaces.get_mut(&batch.space)
828			{
829				open.stored.abandon_batch();
830			}
831		} else {
832			let _ = self.end_batch();
833			self.save_received_checks();
834		}
835	}
836}
837
838/// How much of its disk a replica keeps free when it receives blobs: 1 GiB.
839pub(crate) const MIN_FREE_BYTES: u64 = 1 << 30;
840
841/// Whether a disk with `free` bytes free has room for a blob of `size` bytes, and
842/// [`MIN_FREE_BYTES`] besides.
843/// Whether a group's log gives the replica whose key is `own` the space `space`: whether a
844/// counting statement there gives it an entry for that space, on its record in the group.
845fn gave(
846	log: &nibkeep_log::Log<nibkeep_store::StateFile, nibkeep_store::LogFile>,
847	keys: &nibkeep_log::SpaceKeys,
848	own: &VerifyingKey,
849	group: SpaceId,
850	space: SpaceId,
851) -> Result<bool, NodeError> {
852	let record = nibkeep_governance::replica_record(group, own);
853	Ok(log.governing_statements(keys)?.iter().any(|governing| {
854		governing.statement.entity == record
855			&& governing
856				.counting_text(&nibkeep_model::fields::SPACE_ENTRY)
857				.and_then(nibkeep_governance::SpaceEntry::from_text)
858				.is_some_and(|entry| entry.space == space)
859	}))
860}
861
862fn leaves_room(free: u64, size: u64) -> bool {
863	free.checked_sub(size)
864		.is_some_and(|left| left >= MIN_FREE_BYTES)
865}
866
867/// Whether an error of receiving is the log's refusal of what came, which drops it, and not
868/// a failure of the storage.
869fn refused(error: &StoreError) -> bool {
870	matches!(error, StoreError::Log(error) if *error != LogError::Storage)
871}
872
873impl Holder for Syncing<'_> {
874	type Error = NodeError;
875
876	fn verifying_key(&self) -> VerifyingKey {
877		self.library.replica.signing.verifying_key()
878	}
879
880	fn sign(&self, context: &'static str, message: &[u8]) -> Signature {
881		self.library.replica.signing.sign(context, message)
882	}
883
884	fn spaces_with(&self, peer: &VerifyingKey) -> Result<Vec<SpaceId>, NodeError> {
885		if *peer == self.library.replica.signing.verifying_key() {
886			return Ok(Vec::new());
887		}
888		// The user's own replicas, as the personal space lists them, but AI agents'.
889		let own_replica = {
890			let personal = self.library.space(self.library.info.personal)?;
891			let log = personal.stored.log();
892			log.is_governed(&personal.keys)?
893				&& log.is_listed(peer, &personal.keys)?
894				&& !log.is_revoked(peer, &personal.keys)?
895				&& !log.is_ai_agent(peer, &personal.keys)?
896		};
897		let mut spaces = Vec::new();
898		for (&id, space) in &self.library.spaces {
899			// Who may sync is decided by key, as the space's counting governing changes say.
900			let log = space.stored.log();
901			let governed = log.is_governed(&space.keys)?;
902			// A replica that another of its member's revoked, but which would stay if it
903			// revoked that one back, is heard: it is sent nothing, and what it made without
904			// knowing of its revocation is taken, set aside, so that two replicas that revoke
905			// each other meet wherever either revocation is, and the one listed first stays.
906			let listed = governed
907				&& log.is_listed(peer, &space.keys)?
908				&& (!log.is_revoked(peer, &space.keys)?
909					|| log.may_revoke_back(peer, &space.keys)?);
910			// A new replica trusts its sponsor for a space it has nothing of yet, and a replica
911			// its user's other replicas for a space that the personal space gave it.
912			let trusted = !governed
913				&& (self.trusted == Some(*peer)
914					|| (own_replica && id != self.library.info.personal));
915			// A new device introduced itself here by a recovery code that stands.
916			let introduced = self
917				.introduced
918				.as_ref()
919				.is_some_and(|(key, spaces)| key == peer && spaces.contains(&id));
920			if listed || trusted || introduced || self.through_groups(id, governed, peer)? {
921				spaces.push(id);
922			}
923		}
924		Ok(spaces)
925	}
926
927	fn introductions(&self, peer: &[u8; 32]) -> Result<Vec<RecoveryListing>, NodeError> {
928		// Only a replica that listed itself by a code has any.
929		let own = self.library.replica.signing.verifying_key();
930		let mut listings: BTreeMap<SpaceId, RecoveryListing> = BTreeMap::new();
931		for (&id, open) in &self.library.spaces {
932			if let Some(listing) = open.stored.log().listings_by_code(&own, &open.keys)?.pop() {
933				listings.insert(id, listing);
934			}
935		}
936		if listings.is_empty() {
937			return Ok(Vec::new());
938		}
939		// It shows them to the replica it connected to alone, by the endpoint ID that its
940		// record states, for the spaces that list that replica, which holds those IDs
941		// already; the personal space first, should there be more than a hello carries.
942		let Some(key) = self
943			.library
944			.peers()?
945			.into_iter()
946			.find(|replica| replica.endpoint == Some(*peer))
947			.and_then(|replica| replica.signing)
948		else {
949			return Ok(Vec::new());
950		};
951		let shared = self.spaces_with(&key)?;
952		let personal = self.library.info.personal;
953		let mut shown: Vec<RecoveryListing> = listings
954			.into_iter()
955			.filter(|(space, _)| shared.contains(space))
956			.map(|(_, listing)| listing)
957			.collect();
958		shown.sort_by_key(|listing| listing.space != personal);
959		Ok(shown)
960	}
961
962	fn introduced(
963		&mut self,
964		peer: &VerifyingKey,
965		listings: &[RecoveryListing],
966	) -> Result<(), NodeError> {
967		// Listings of the peer's own key, by space, each space once.
968		let mut by_space: BTreeMap<SpaceId, Vec<&RecoveryListing>> = BTreeMap::new();
969		for listing in listings.iter().filter(|listing| listing.key == *peer) {
970			by_space.entry(listing.space).or_default().push(listing);
971		}
972		// In a governed space or group held here that neither lists the peer, which syncs
973		// with it anyway, nor revoked it: a listing signed by a code that counts there, one
974		// that stands for a member with a role, so that strangers, and members who left,
975		// still fill nobody's log. The cheap checks first, and the roster once.
976		let mut spaces = BTreeSet::new();
977		for (space, listings) in by_space {
978			let Some(open) = self.library.spaces.get(&space) else {
979				continue;
980			};
981			let log = open.stored.log();
982			if !log.is_governed(&open.keys)?
983				|| log.is_listed(peer, &open.keys)?
984				|| log.is_revoked(peer, &open.keys)?
985			{
986				continue;
987			}
988			let roster = log.roster(&open.keys)?;
989			let codes: BTreeSet<EntityId> = self
990				.library
991				.code_recipients(space, &roster, &[])?
992				.iter()
993				.map(|code| code.record)
994				.collect();
995			if listings
996				.iter()
997				.any(|listing| codes.contains(&listing.code_record()) && listing.verifies())
998			{
999				spaces.insert(space);
1000			}
1001		}
1002		self.introduced = Some((*peer, spaces));
1003		Ok(())
1004	}
1005
1006	fn prepare(&mut self, space: SpaceId) -> Result<(), NodeError> {
1007		self.end_batch()?;
1008		// A replica gives an account of a space only once it counts there. Accounts only
1009		// count and show copies, so one that cannot be brought up to date now, as while
1010		// another program holds the log file, waits for the next sync, and this one goes on.
1011		let own = self.library.replica.signing.verifying_key();
1012		if self.library.counts_in(space, &own)? {
1013			let wall = (self.now)();
1014			let _ = self.library.refresh_account(space, wall, &mut self.rng);
1015		}
1016		Ok(())
1017	}
1018
1019	fn holdings(&self, space: SpaceId) -> Result<Vec<Holding>, NodeError> {
1020		let stored = &self.library.space(space)?.stored;
1021		let log = stored.log();
1022		let mut holdings: Vec<Holding> = log
1023			.summaries()?
1024			.into_iter()
1025			.map(|summary| Holding::Change {
1026				id: summary.id,
1027				millis: summary.millis,
1028				depth: summary.depth,
1029				complete: summary.complete,
1030			})
1031			.collect();
1032		holdings.extend(
1033			log.wrapped_keys()
1034				.map(|(statement, key)| Holding::RecordKey {
1035					statement,
1036					key: key.clone(),
1037				}),
1038		);
1039		holdings.extend(
1040			log.wrapped_blob_keys()
1041				.map(|(sealed, key)| Holding::BlobKey {
1042					sealed: *sealed,
1043					key: key.clone(),
1044				}),
1045		);
1046		holdings.extend(
1047			self.library
1048				.account_holdings(space)?
1049				.into_iter()
1050				.map(|(id, issued)| Holding::Account { id, issued }),
1051		);
1052		Ok(holdings)
1053	}
1054
1055	fn account(&self, space: SpaceId, id: &Hash) -> Result<Option<Vec<u8>>, NodeError> {
1056		self.library.account_page(space, id)
1057	}
1058
1059	fn receive_account(&mut self, space: SpaceId, page: Vec<u8>) -> Result<bool, NodeError> {
1060		// Not where the disk would have too little room left after it, as for blobs; kept
1061		// with the others that came, once the batch of changes ends.
1062		if !self.has_room(u64::try_from(page.len()).unwrap_or(u64::MAX))? {
1063			return Ok(false);
1064		}
1065		let Some(checked) = self.library.check_account(space, &page)? else {
1066			return Ok(false);
1067		};
1068		self.pages.push((space, checked));
1069		Ok(true)
1070	}
1071
1072	fn sends(
1073		&self,
1074		space: SpaceId,
1075		peer: &VerifyingKey,
1076		holding: &Holding,
1077	) -> Result<bool, NodeError> {
1078		// A replica whose member left or was removed, or an AI agent's where the space allows
1079		// none, gets the changes that ended it and what they build on, and nothing after: no
1080		// keys or files either, which it holds already or does without. A revoked one gets
1081		// nothing.
1082		match (self.ended(space, peer)?, holding) {
1083			(None, _) => Ok(true),
1084			(Some(ended), Holding::Change { id, .. }) => Ok(ended.reach.contains(id)),
1085			(Some(_), _) => Ok(false),
1086		}
1087	}
1088
1089	fn wanted_blobs(
1090		&mut self,
1091		space: SpaceId,
1092		peer: &VerifyingKey,
1093		asked: &BTreeSet<Hash>,
1094		most: usize,
1095	) -> Result<Vec<Hash>, NodeError> {
1096		// Nor does a revoked replica give any.
1097		if self.ended(space, peer)?.is_some_and(|ended| ended.revoked) {
1098			return Ok(Vec::new());
1099		}
1100		let listed = self.library.listed_blobs(space, peer)?;
1101		let lists = |sealed: &Hash| listed.as_ref().is_none_or(|listed| listed.contains(sealed));
1102		self.wanted_among(space, &lists, asked, most)
1103	}
1104
1105	fn sends_blobs(&self, space: SpaceId, peer: &VerifyingKey) -> Result<bool, NodeError> {
1106		// A replica that the space ended gets no files, which it holds already or does
1107		// without.
1108		Ok(self.ended(space, peer)?.is_none())
1109	}
1110
1111	fn challenges(
1112		&mut self,
1113		space: SpaceId,
1114		peer: &VerifyingKey,
1115	) -> Result<Vec<Challenge>, NodeError> {
1116		// A revoked replica's copies count for nothing.
1117		if self.ended(space, peer)?.is_some_and(|ended| ended.revoked) {
1118			return Ok(Vec::new());
1119		}
1120		Ok(self
1121			.removals
1122			.as_deref_mut()
1123			.map_or_default(|removals| removals.challenges(space, peer)))
1124	}
1125
1126	fn proved(
1127		&mut self,
1128		space: SpaceId,
1129		peer: &VerifyingKey,
1130		challenges: &[Challenge],
1131		answers: &[Option<[u8; 32]>],
1132	) -> Result<(), NodeError> {
1133		if let Some(removals) = self.removals.as_deref_mut() {
1134			removals.proved(space, peer, challenges, answers);
1135		}
1136		Ok(())
1137	}
1138
1139	fn prove(
1140		&mut self,
1141		space: SpaceId,
1142		peer: &VerifyingKey,
1143		challenges: &[Challenge],
1144	) -> Result<Vec<Option<[u8; 32]>>, NodeError> {
1145		let mut answers = vec![None; challenges.len()];
1146		// A replica that the space ended removes nothing of it on this one's word.
1147		if !self.sends_blobs(space, peer)? {
1148			return Ok(answers);
1149		}
1150		// Plain challenges, of a content's own bytes, are answered from an unchanged original
1151		// of it on this device, which NibKeep never removes, so nothing is held for them;
1152		// never from a checkout, which NibKeep deletes and the person edits.
1153		if challenges.iter().any(|challenge| challenge.plain) {
1154			let originals: BTreeMap<Hash, String> = self
1155				.library
1156				.origin_places_here(space)?
1157				.into_iter()
1158				.filter(|place| place.untouched)
1159				.map(|place| (place.content, place.path))
1160				.collect();
1161			for (challenge, answer) in challenges.iter().zip(answers.iter_mut()) {
1162				if challenge.plain
1163					&& let Some(path) = originals.get(&challenge.sealed)
1164					&& let Ok(mut file) = fs::File::open(path)
1165				{
1166					*answer = answer_from_file(challenge, &mut file).ok();
1167				}
1168			}
1169		}
1170		let held: Vec<Hash> = {
1171			let stored = &self.library.space(space)?.stored;
1172			challenges
1173				.iter()
1174				.filter(|challenge| !challenge.plain)
1175				.map(|challenge| challenge.sealed)
1176				.filter(|sealed| {
1177					!stored.log().wrapped_blob_keys_of(sealed).is_empty()
1178						&& stored.holds_sealed(sealed)
1179				})
1180				.collect()
1181		};
1182		if held.is_empty() {
1183			return Ok(answers);
1184		}
1185		if self.records.is_none() {
1186			self.records = Some(self.library.sync_records(UnwrapErr(SysRng))?);
1187		}
1188		let records = self
1189			.records
1190			.as_ref()
1191			.unwrap_or_else(|| unreachable!("set above"));
1192		// Held before it answers, so that it removes none of them while the other replica
1193		// counts on them; none that it is removing itself.
1194		let holding = records.hold(&held, (self.now)())?;
1195		let stored = &self.library.space(space)?.stored;
1196		for (challenge, answer) in challenges.iter().zip(answers.iter_mut()) {
1197			if challenge.plain || !holding.contains(&challenge.sealed) {
1198				continue;
1199			}
1200			if let Some((_, mut file)) = stored.open_sealed_blob(&challenge.sealed)? {
1201				*answer = answer_from_file(challenge, &mut file).ok();
1202			}
1203		}
1204		Ok(answers)
1205	}
1206
1207	fn parcel(&self, space: SpaceId, id: ChangeId) -> Result<Option<Parcel>, NodeError> {
1208		Ok(self.library.space(space)?.stored.log().parcel(id)?)
1209	}
1210
1211	fn blob(
1212		&self,
1213		space: SpaceId,
1214		sealed: &Hash,
1215	) -> Result<Option<(u64, nibkeep_sync::BlobBytes<'_>)>, NodeError> {
1216		Ok(self
1217			.library
1218			.space(space)?
1219			.stored
1220			.open_sealed_blob(sealed)?
1221			.map(|(size, file)| {
1222				let file: Box<dyn Read + '_> = Box::new(file);
1223				(size, file)
1224			}))
1225	}
1226
1227	fn receive_change(
1228		&mut self,
1229		space: SpaceId,
1230		peer: &VerifyingKey,
1231		mut parcel: Parcel,
1232	) -> Result<bool, NodeError> {
1233		let wall_millis = (self.now)();
1234		// Of what a replica that the space ended made itself, only what it made without
1235		// knowing of that, built on changes held here, which a revocation sets aside unless
1236		// one of its own of the replica that revoked it comes; what it passes on of others'
1237		// is taken as from anyone.
1238		if parcel.change.author() == peer
1239			&& let Some(ended) = self.ended(space, peer)?
1240		{
1241			let log = self.library.space(space)?.stored.log();
1242			for parent in parcel.change.parents() {
1243				// Accepted, not only waiting, so that what it builds on is known.
1244				if log.change(*parent)?.is_none() {
1245					return Ok(false);
1246				}
1247				for &ending in &ended.ending {
1248					if log.is_ancestor_of(ending, *parent)? {
1249						return Ok(false);
1250					}
1251				}
1252			}
1253		}
1254		let governs = parcel.change.kind() == nibkeep_log::Kind::Governing;
1255		// An ordinary change's payload, too, is refused if the disk would have too little
1256		// room left after it. Its header is taken, so that the changes that build on it,
1257		// such as a revocation, are not held up; the payload comes at a later sync.
1258		if parcel.change.kind() == nibkeep_log::Kind::Ordinary
1259			&& let Some(payload) = &parcel.payload
1260		{
1261			let size = u64::try_from(payload.byte_len()).unwrap_or(u64::MAX);
1262			if !self.has_room(size)? {
1263				self.refused += 1;
1264				parcel.payload = None;
1265			}
1266		}
1267		self.batch(space)?;
1268		let open = self.space(space)?;
1269		let mut alone = false;
1270		let mut received = open.stored.receive(&parcel, &open.keys, wall_millis);
1271		// A change that governs, or that waiting changes wait for, which may govern, is
1272		// received alone, as one made here that governs is made outside a batch.
1273		if matches!(received, Err(StoreError::InBatch)) {
1274			self.end_batch()?;
1275			let open = self.space(space)?;
1276			received = open.stored.receive(&parcel, &open.keys, wall_millis);
1277			alone = true;
1278		}
1279		let received = match received {
1280			Ok(Received::Duplicate) => false,
1281			Ok(_) => true,
1282			Err(error) if refused(&error) => false,
1283			Err(error) => return Err(error.into()),
1284		};
1285		// Who the space ended may differ once a governing change came.
1286		if (governs || alone) && received {
1287			self.ended.borrow_mut().remove(&space);
1288		}
1289		if received {
1290			self.plan = None;
1291		}
1292		self.received_in_batch()?;
1293		Ok(received)
1294	}
1295
1296	fn receive_record_key(
1297		&mut self,
1298		space: SpaceId,
1299		statement: StatementId,
1300		key: WrappedKey,
1301	) -> Result<bool, NodeError> {
1302		self.batch(space)?;
1303		let open = self.space(space)?;
1304		let before = open.stored.log().wrapped_keys_of(statement).len();
1305		let kept = match open.stored.receive_wrapped_key(statement, key, &open.keys) {
1306			Err(error) if !refused(&error) => return Err(error.into()),
1307			_ => open.stored.log().wrapped_keys_of(statement).len() > before,
1308		};
1309		self.received_in_batch()?;
1310		Ok(kept)
1311	}
1312
1313	fn receive_blob_key(
1314		&mut self,
1315		space: SpaceId,
1316		sealed: Hash,
1317		key: WrappedBlobKey,
1318	) -> Result<bool, NodeError> {
1319		// Saved at once, under the replica's blob lock, which a batch would hold too long.
1320		self.end_batch()?;
1321		let open = self.space(space)?;
1322		let before = open.stored.log().wrapped_blob_keys_of(&sealed).to_vec();
1323		let kept = match open.stored.receive_blob_key(sealed, key, &open.keys) {
1324			Err(error) if !refused(&error) => return Err(error.into()),
1325			_ => open.stored.log().wrapped_blob_keys_of(&sealed) != before.as_slice(),
1326		};
1327		if kept {
1328			self.plan = None;
1329		}
1330		Ok(kept)
1331	}
1332
1333	fn receive_blob(
1334		&mut self,
1335		space: SpaceId,
1336		sealed: Hash,
1337		size: u64,
1338		bytes: &mut dyn Read,
1339	) -> Result<bool, NodeError> {
1340		// A blob takes long to come, and is written apart from the log.
1341		self.end_batch()?;
1342		// Keys come before blobs: a blob without one is no blob of the space, and whatever
1343		// its size, none of it is written.
1344		if self
1345			.space(space)?
1346			.stored
1347			.log()
1348			.wrapped_blob_keys_of(&sealed)
1349			.is_empty()
1350		{
1351			return Ok(false);
1352		}
1353		// Nor is one that would leave the disk too full, so that another replica cannot
1354		// fill it; the sync goes on without it.
1355		if !self.has_room(size)? {
1356			self.refused += 1;
1357			return Ok(false);
1358		}
1359		let now = (self.now)();
1360		let stored = &mut self.space(space)?.stored;
1361		let kept = stored.receive_sealed_blob(sealed, size, bytes)?;
1362		if kept {
1363			self.received_checks.push((space, sealed, now));
1364		}
1365		Ok(kept)
1366	}
1367
1368	fn finish_space(&mut self, space: SpaceId) -> Result<(), NodeError> {
1369		self.end_batch()?;
1370		self.save_received_checks();
1371		// What came may define types, or change the lists of languages.
1372		self.library.read_again(space)
1373	}
1374
1375	fn pause(&mut self) -> Result<(), NodeError> {
1376		self.end_batch()
1377	}
1378}
1379
1380/// The library as pairing changes it: what grants a new replica the space keys, and records
1381/// it once it has joined.
1382pub struct Sponsor<'a> {
1383	library: &'a mut Library,
1384	now: &'a dyn Fn() -> u64,
1385	/// The name of the AI agent whose replica it adds, if it adds one.
1386	ai_agent: Option<String>,
1387	/// The spaces besides the personal one chosen for that AI agent.
1388	spaces: Vec<SpaceId>,
1389	/// What the replica granted last asked with, where it connected from, and what it was
1390	/// granted, for listing an AI agent's replica in the spaces chosen for it.
1391	granted: Option<(JoinRequest, [u8; 32], Grant)>,
1392	/// Whether it gives the secrets to a new replica that asks for them, as the person chose.
1393	give_secrets: bool,
1394	/// What records the replica granted last.
1395	pending: Option<Vec<Operation>>,
1396	/// What the replica granted last asked for, and got.
1397	asked_for: AskedFor,
1398	/// Whether a code matched: a joiner's request came with the tag of the code's key.
1399	matched: bool,
1400	/// What the person chose for a new device of theirs: a computer or a phone, and its
1401	/// spaces.
1402	device: NewDevice,
1403}
1404
1405/// What a new replica asked for, besides the library, as it paired.
1406#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1407pub enum AskedFor {
1408	/// Nothing, or the secrets from a replica that holds none.
1409	#[default]
1410	Nothing,
1411	/// The secrets, which it was not given: the replica that added it gives them later.
1412	Secrets,
1413	/// The secrets, which it was given.
1414	SecretsGiven,
1415}
1416
1417impl<'a> Sponsor<'a> {
1418	/// Pairing of `library`, with the wall clock `now`.
1419	pub fn new(library: &'a mut Library, now: &'a dyn Fn() -> u64) -> Self {
1420		Self {
1421			library,
1422			now,
1423			ai_agent: None,
1424			spaces: Vec::new(),
1425			granted: None,
1426			give_secrets: false,
1427			pending: None,
1428			asked_for: AskedFor::Nothing,
1429			matched: false,
1430			device: NewDevice::computer(),
1431		}
1432	}
1433
1434	/// The same, pairing a device of the person's as they chose: a computer, which takes
1435	/// every space of this device's, or the spaces chosen, and those given to it later; or a
1436	/// phone, which takes the personal space alone, or the spaces chosen, and asks before it
1437	/// takes a space given to it later
1438	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
1439	#[must_use]
1440	pub fn for_device(mut self, device: NewDevice) -> Self {
1441		self.device = device;
1442		self
1443	}
1444
1445	/// The same, giving the secrets, which are unlocked, to a new replica that asks for them:
1446	/// the person chose to.
1447	#[must_use]
1448	pub fn giving_secrets(mut self) -> Self {
1449		self.give_secrets = true;
1450		self
1451	}
1452
1453	/// What the replica granted last asked for, and got.
1454	#[must_use]
1455	pub fn asked_for(&self) -> AskedFor {
1456		self.asked_for
1457	}
1458
1459	/// Whether the code matched: a joiner was granted, or would have been, had granting not
1460	/// failed. A pairing that failed before then leaves the code for another try.
1461	#[must_use]
1462	pub const fn matched(&self) -> bool {
1463		self.matched
1464	}
1465
1466	/// Pairing of `library` with an AI agent's replica, named after the AI agent, as
1467	/// [`Sponsor::new`] pairs a replica of the user's.
1468	pub fn ai_agent(library: &'a mut Library, name: &str, now: &'a dyn Fn() -> u64) -> Self {
1469		Self::ai_agent_in(library, (name, &[]), now)
1470	}
1471
1472	/// The same, listing the AI agent's replica in the spaces besides the personal one that
1473	/// the person chose for it too, which the AI agent's replica signs its listings in.
1474	pub fn ai_agent_in(
1475		library: &'a mut Library,
1476		(name, spaces): (&str, &[SpaceId]),
1477		now: &'a dyn Fn() -> u64,
1478	) -> Self {
1479		Self {
1480			ai_agent: Some(name.to_owned()),
1481			spaces: spaces.to_vec(),
1482			..Self::new(library, now)
1483		}
1484	}
1485}
1486
1487impl Sponsoring for Sponsor<'_> {
1488	type Error = NodeError;
1489
1490	fn grant<R: CryptoRng>(
1491		&mut self,
1492		request: &JoinRequest,
1493		endpoint: &[u8; 32],
1494		rng: &mut R,
1495	) -> Result<Grant, NodeError> {
1496		// Pairing asks for a grant only once the code matched.
1497		self.matched = true;
1498		let (mut grant, operations, asked_for) = self.library.prepare_replica(
1499			request,
1500			(endpoint, self.ai_agent.as_deref(), self.give_secrets),
1501			(self.now)(),
1502			rng,
1503		)?;
1504		// The AI agent's replica signs its listing in each space chosen, as the user's
1505		// member there.
1506		self.library.check_ai_spaces(&self.spaces)?;
1507		let mut chosen = Vec::new();
1508		for &space in &self.spaces {
1509			let member = self.library.member_in(space)?.ok_or(NodeError::NotListed)?;
1510			chosen.push((space, member));
1511		}
1512		chosen.sort();
1513		chosen.dedup();
1514		grant.chosen = chosen;
1515		grant.asks_first = self.ai_agent.is_none() && self.device.phone;
1516		self.pending = Some(operations);
1517		self.granted = Some((request.clone(), *endpoint, grant.clone()));
1518		self.asked_for = asked_for;
1519		Ok(grant)
1520	}
1521
1522	fn record<R: CryptoRng>(&mut self, listings: &[String], rng: &mut R) -> Result<(), NodeError> {
1523		let Some(operations) = self.pending.take() else {
1524			return Ok(());
1525		};
1526		let Some((request, endpoint, grant)) = &self.granted else {
1527			return Err(NodeError::Damaged(
1528				"pairing records a replica that it granted nothing".to_owned(),
1529			));
1530		};
1531		let personal = self.library.info.personal;
1532		let wall_millis = (self.now)();
1533		// Its listing in the personal space, which its key signed for the record and the
1534		// owner that the grant named, as an AI agent's if it is one, with the encryption key it
1535		// asked with, goes with its records there: no other lists it.
1536		let Some((own, chosen)) = listings.split_first() else {
1537			return Err(NodeError::Damaged(
1538				"the new replica sent no listing of its own".to_owned(),
1539			));
1540		};
1541		let encryption = nibkeep_governance::encryption_hash(&request.encryption.to_bytes());
1542		Listing::from_text(own)
1543			.filter(|listing| {
1544				listing.space == personal
1545					&& listing.record == grant.replica
1546					&& listing.owner == grant.user
1547					&& listing.ai_agent == grant.ai_agent
1548					&& listing.key == request.signing
1549					&& listing.encryption == encryption
1550					&& listing.verifies()
1551			})
1552			.ok_or_else(|| {
1553				NodeError::Damaged("the new replica's listing is not the one asked for".to_owned())
1554			})?;
1555		let mut operations = operations;
1556		operations.push(Operation::assert(Statement::new(
1557			StatementId::random(rng),
1558			grant.replica,
1559			fields::LISTING,
1560			Value::Text(own.clone()),
1561		)));
1562		// An AI agent's listings in the spaces chosen for it are checked before anything is
1563		// committed; the personal space's entries go with its records there.
1564		let mut listed = Vec::new();
1565		if let Some(name) = &self.ai_agent
1566			&& !grant.chosen.is_empty()
1567		{
1568			let prepared =
1569				self.library
1570					.ai_agent_listings((request, endpoint, grant, name), chosen, rng)?;
1571			operations.extend(prepared.entries);
1572			listed = prepared.spaces;
1573		}
1574		// A device of the person's gets the spaces chosen for it, with its records: it takes
1575		// them after its first sync, whatever it says of the spaces given to it later.
1576		if self.ai_agent.is_none() {
1577			operations.extend(self.library.entries_for_new(
1578				(grant.replica, &request.encryption),
1579				&self.device,
1580				rng,
1581			)?);
1582		}
1583		self.library
1584			.commit(personal, operations, wall_millis, rng)?;
1585		self.library.list_ai_agent(listed, wall_millis, rng)
1586	}
1587}
1588
1589/// A new replica that is joining a library: its keys, and the names of its device and app,
1590/// before the sponsor grants it the space keys.
1591pub struct Joining<'a> {
1592	signing: SigningKey,
1593	decryption: DecryptionKey,
1594	device: String,
1595	app: String,
1596	/// The key it asks for the secrets with, if it does, and how its secrets compartment is
1597	/// protected.
1598	secrets: Option<(DecryptionKey, NewProtection<'a>)>,
1599	/// That compartment, once sealed, and its key.
1600	sealed: Option<(SealedSecrets, CompartmentKey)>,
1601}
1602
1603impl<'a> Joining<'a> {
1604	/// A new replica on a device, kept by an app, with new keys.
1605	///
1606	/// # Errors
1607	///
1608	/// Returns [`NodeError::EmptyName`] if a name is empty.
1609	pub fn new(device: &str, app: &str, rng: &mut impl CryptoRng) -> Result<Self, NodeError> {
1610		if device.is_empty() || app.is_empty() {
1611			return Err(NodeError::EmptyName);
1612		}
1613		// The sponsor refuses longer names, which would spend the code.
1614		if device.len().max(app.len()) > MAX_NAME_LEN {
1615			return Err(NodeError::LongName(MAX_NAME_LEN));
1616		}
1617		Ok(Self {
1618			signing: SigningKey::generate(rng),
1619			decryption: DecryptionKey::generate(rng),
1620			device: device.to_owned(),
1621			app: app.to_owned(),
1622			secrets: None,
1623			sealed: None,
1624		})
1625	}
1626
1627	/// Asks the sponsor for the secrets too, with a new secrets key, which the new library
1628	/// keeps in a secrets compartment protected as `protection` says, never by the library's
1629	/// passphrase: the sponsor gives them, if it holds them and the person chose to there.
1630	/// After its first sync, the new replica states that it asks the sponsor, with that key,
1631	/// and takes what was given; if the sponsor held none, the compartment is removed again.
1632	#[must_use]
1633	pub fn asking_for_secrets(
1634		mut self,
1635		protection: NewProtection<'a>,
1636		rng: &mut impl CryptoRng,
1637	) -> Self {
1638		self.secrets = Some((DecryptionKey::generate(rng), protection));
1639		self
1640	}
1641
1642	/// Whether it asks for the secrets.
1643	pub(crate) fn asks_for_secrets(&self) -> bool {
1644		self.secrets.is_some()
1645	}
1646
1647	/// Seals the compartment that receives the secrets, if it asks for them, before the
1648	/// sponsor is found: the person may turn a keystore's prompt down, which then spends no
1649	/// code, or take longer than the sponsor waits.
1650	///
1651	/// # Errors
1652	///
1653	/// Returns an error if the passphrase cannot be used or the keystore fails.
1654	pub(crate) fn seal_secrets(&mut self, rng: &mut impl CryptoRng) -> Result<(), NodeError> {
1655		if self.sealed.is_some() {
1656			return Ok(());
1657		}
1658		let Some((decryption, protection)) = &self.secrets else {
1659			return Ok(());
1660		};
1661		let keys = SecretsKeys {
1662			spaces: SpaceKeyMap::new(),
1663			decryption: decryption.clone(),
1664		};
1665		self.sealed = Some(SealedSecrets::seal(&keys, protection, rng)?);
1666		Ok(())
1667	}
1668
1669	/// Refuses the library's own passphrase for the secrets, before the code is spent.
1670	pub(crate) fn check_secrets_protection(
1671		&self,
1672		protection: &NewProtection<'_>,
1673	) -> Result<(), NodeError> {
1674		if let (
1675			Some((_, NewProtection::Passphrase(secrets, _))),
1676			NewProtection::Passphrase(library, _),
1677		) = (&self.secrets, protection)
1678			&& secrets == library
1679		{
1680			return Err(NodeError::LibraryPassphrase);
1681		}
1682		Ok(())
1683	}
1684
1685	/// What it asks the sponsor for.
1686	#[must_use]
1687	pub fn request(&self) -> JoinRequest {
1688		JoinRequest {
1689			signing: self.signing.verifying_key(),
1690			encryption: self.decryption.encryption_key(),
1691			device: self.device.clone(),
1692			app: self.app.clone(),
1693			secrets: self
1694				.secrets
1695				.as_ref()
1696				.map(|(decryption, _)| decryption.encryption_key()),
1697		}
1698	}
1699
1700	/// The 32-byte secret of its endpoint key.
1701	pub(crate) fn endpoint_secret(&self) -> Key {
1702		endpoint_secret(&self.signing)
1703	}
1704
1705	/// Its keys and the names of its device and app, for a replica that lists itself, as a
1706	/// device that a recovery code brings back does; it asks nobody for the secrets, so a
1707	/// request for them is dropped.
1708	pub(crate) fn into_parts(self) -> (SigningKey, DecryptionKey, String, String) {
1709		(self.signing, self.decryption, self.device, self.app)
1710	}
1711
1712	/// Starts the new replica's endpoint, as [`Library::network`] does.
1713	///
1714	/// # Errors
1715	///
1716	/// Returns an error if networking cannot start.
1717	pub fn network(
1718		&self,
1719		options: nibkeep_net::Options,
1720	) -> Result<nibkeep_net::Network, NodeError> {
1721		crate::network::start_network(&self.endpoint_secret(), options)
1722	}
1723
1724	/// Makes the library in a directory that holds none, from what the sponsor granted:
1725	/// the new replica's keys, protected as `protection` says, with the space keys, and the
1726	/// library file. Its spaces are empty until it syncs. If making it fails, what was
1727	/// written is removed, keystore keys included.
1728	///
1729	/// # Errors
1730	///
1731	/// Returns an error if the directory holds a library already, the grant's keys do not
1732	/// open or lack the personal space, or the files cannot be written.
1733	pub fn make(
1734		mut self,
1735		directory: &Path,
1736		grant: &Grant,
1737		protection: &NewProtection<'_>,
1738		rng: &mut impl CryptoRng,
1739	) -> Result<Library, NodeError> {
1740		// Its records are derived from the personal space and its key, as its listing says.
1741		let own = self.signing.verifying_key();
1742		if grant.replica != nibkeep_governance::replica_record(grant.space, &own)
1743			|| grant.device != nibkeep_governance::device_record(grant.space, &own)
1744		{
1745			return Err(NodeError::Damaged(
1746				"the grant names records that are not this replica's".to_owned(),
1747			));
1748		}
1749		// Sealed already, unless it was made without [`join`](crate::join).
1750		self.seal_secrets(rng)?;
1751		let sealed = self.sealed.take();
1752		let spaces =
1753			nibkeep_governance::open_space_keys(&self.decryption, grant.replica, &grant.keys)
1754				.map_err(|_| {
1755					NodeError::Damaged("the space keys of the grant do not open".to_owned())
1756				})?;
1757		if !spaces.contains_key(&grant.space) {
1758			return Err(NodeError::Damaged(
1759				"the grant lacks the keys of the personal space".to_owned(),
1760			));
1761		}
1762		let folder = new_replica_folder(directory, super::wall_clock(), rng)?;
1763		let in_use = super::in_use::InUse::take(&folder)?;
1764		let directory = folder.as_path();
1765		let keys_path = directory.join(KEYS);
1766		let replica = ReplicaKeys {
1767			signing: self.signing,
1768			decryption: self.decryption,
1769			storage: Key::generate(rng),
1770			spaces,
1771		};
1772		let info = Info {
1773			user: grant.user,
1774			device: grant.device,
1775			replica: grant.replica,
1776			personal: grant.space,
1777		};
1778		let (mut key_file, compartment) = match KeyFile::create(&replica, protection, rng) {
1779			Ok(created) => created,
1780			Err(error) => {
1781				drop(in_use);
1782				let _ = fs::remove_dir_all(directory);
1783				return Err(error.into());
1784			}
1785		};
1786		// The compartment that receives the secrets, if it asks for them, is written with the
1787		// rest of the library, so that the key it asked with is never only in memory.
1788		let secrets_compartment = sealed.map(|(sealed, key)| {
1789			key_file.put_secrets(sealed);
1790			key
1791		});
1792		let made = (|| {
1793			key_file.write(&keys_path)?;
1794			let code_types = code_types();
1795			let mut spaces = std::collections::BTreeMap::new();
1796			for (&id, epochs) in &replica.spaces {
1797				let log = log_path(directory, id);
1798				spaces.insert(
1799					id,
1800					Space::open(&log, id, epochs, &replica.storage, &code_types)?,
1801				);
1802			}
1803			info.write(&directory.join(INFO))?;
1804			Ok::<_, NodeError>((code_types, spaces))
1805		})();
1806		match made {
1807			Ok((code_types, spaces)) => {
1808				let mut library = Library {
1809					directory: directory.to_owned(),
1810					key_file,
1811					compartment,
1812					secrets_compartment,
1813					replica,
1814					info,
1815					spaces,
1816					chosen: None,
1817					code_types,
1818					languages: nibkeep_model::Languages::default(),
1819					language_statements: std::collections::BTreeSet::new(),
1820					in_use,
1821					wall: std::cell::Cell::new(super::wall_clock()),
1822					accounts_refreshed: std::cell::RefCell::new(BTreeMap::new()),
1823					acting: None,
1824					thumbnailer: None,
1825				};
1826				library.refresh_languages()?;
1827				library.choose_writing_keys()?;
1828				Ok(library)
1829			}
1830			Err(error) => {
1831				drop(in_use);
1832				let _ = fs::remove_dir_all(directory);
1833				key_file.discard();
1834				Err(error)
1835			}
1836		}
1837	}
1838}
1839
1840impl Library {
1841	/// Removes a library that a new replica made, keystore keys included, after its first
1842	/// sync failed: the pairing failed, and the sponsor deletes the replica's records.
1843	pub(crate) fn remove_unsynced(self) {
1844		let directory = self.directory.clone();
1845		let key_file = self.key_file.clone();
1846		drop(self);
1847		// The folder is this replica's own, made as it joined.
1848		let _ = fs::remove_dir_all(directory);
1849		key_file.discard();
1850	}
1851}
1852
1853#[cfg(test)]
1854mod tests {
1855	use super::{MIN_FREE_BYTES, leaves_room};
1856
1857	#[test]
1858	fn a_blob_is_taken_only_if_a_gibibyte_stays_free() {
1859		assert!(leaves_room(MIN_FREE_BYTES + 10, 10));
1860		assert!(!leaves_room(MIN_FREE_BYTES + 10, 11));
1861		assert!(!leaves_room(5, 10), "a blob larger than the free space");
1862		assert!(leaves_room(u64::MAX, u64::MAX - MIN_FREE_BYTES));
1863	}
1864}