Skip to main content

nibkeep_sync/
session.rs

1//! A sync between two replicas, over a transport: who they are, which spaces they share,
2//! and for each space, what one holds and the other lacks ([Sync](../../../docs/spec/sync.md#3-syncing)).
3
4use std::collections::BTreeSet;
5use std::io::{self, Read};
6
7use nibkeep_base::cbor::{self, Value};
8use nibkeep_base::{Hash, SpaceId, StatementId};
9use nibkeep_crypto::{Signature, VerifyingKey};
10use nibkeep_governance::RecoveryListing;
11use nibkeep_log::{ChangeId, Parcel, WrappedBlobKey, WrappedKey};
12
13use crate::message::{Item, SyncMessage};
14use crate::reconcile::Reconciling;
15use crate::{CHALLENGES_AT_ONCE, Challenge, Holding, SyncError, Transport};
16
17/// The context of the signature that proves who a side is.
18const HELLO: &str = "nibkeep sync hello";
19
20/// How many items one message asks for: their IDs take 2 MiB.
21const WANTED_AT_ONCE: usize = 65_536;
22
23/// How many bytes of a blob one message carries.
24const BLOB_CHUNK: usize = 1024 * 1024;
25
26/// The bytes of a sealed blob, as a replica reads them.
27pub type BlobBytes<'a> = Box<dyn Read + 'a>;
28
29/// A replica's data, as a sync reads and changes it. Each method works on one space.
30pub trait Holder {
31	/// Why reading or writing the data failed.
32	type Error: std::error::Error + Send + Sync + 'static;
33
34	/// The replica's verifying key.
35	fn verifying_key(&self) -> VerifyingKey;
36
37	/// Signs a message with the replica's signing key.
38	fn sign(&self, context: &'static str, message: &[u8]) -> Signature;
39
40	/// The spaces the replica holds in which `peer` is a replica that it syncs with, sorted
41	/// by ID: also those in which [`Holder::introduced`] took a listing of `peer`'s.
42	///
43	/// # Errors
44	///
45	/// Returns an error if the data cannot be read.
46	fn spaces_with(&self, peer: &VerifyingKey) -> Result<Vec<SpaceId>, Self::Error>;
47
48	/// The listings of the replica's own key by a recovery code, which it sends in its hello
49	/// as the initiator, so that a peer that does not know its key yet syncs with it: for the
50	/// replica whose endpoint ID is `peer`, which it connected to, one for each space or group
51	/// that lists it so and that it shares with that replica, which holds those IDs already;
52	/// at most [`crate::MOST_INTRODUCTIONS`]. None by default.
53	///
54	/// # Errors
55	///
56	/// Returns an error if the data cannot be read.
57	fn introductions(&self, peer: &[u8; 32]) -> Result<Vec<RecoveryListing>, Self::Error> {
58		let _ = peer;
59		Ok(Vec::new())
60	}
61
62	/// Takes the listings by a recovery code that `peer` sent in its hello, none if it sent
63	/// none, before [`Holder::spaces_with`], for this sync alone: a space or group for which
64	/// the replica holds a code that counts, which signed the listing of `peer`'s key there,
65	/// it syncs with `peer` as with its replicas, which brings the change that lists `peer`.
66	/// Takes none by default.
67	///
68	/// # Errors
69	///
70	/// Returns an error if the data cannot be read.
71	fn introduced(
72		&mut self,
73		peer: &VerifyingKey,
74		listings: &[RecoveryListing],
75	) -> Result<(), Self::Error> {
76		let _ = (peer, listings);
77		Ok(())
78	}
79
80	/// Readies a space for its sync, before [`Holder::holdings`]: a replica brings its own
81	/// account of what it holds up to date here. One that keeps no account has nothing to do.
82	///
83	/// # Errors
84	///
85	/// Returns an error if the data cannot be read or written.
86	fn prepare(&mut self, space: SpaceId) -> Result<(), Self::Error> {
87		let _ = space;
88		Ok(())
89	}
90
91	/// Everything a space holds, for reconciling.
92	///
93	/// # Errors
94	///
95	/// Returns an error if the data cannot be read.
96	fn holdings(&self, space: SpaceId) -> Result<Vec<Holding>, Self::Error>;
97
98	/// Whether to send `peer` an item of a space that it lacks: every item, but to a peer that
99	/// the space no longer gives what is added, as a member's replica that was removed, only
100	/// what it may still get. What is not sent is still reconciled, so that neither side asks
101	/// for what the other holds already.
102	///
103	/// # Errors
104	///
105	/// Returns an error if the data cannot be read.
106	fn sends(
107		&self,
108		space: SpaceId,
109		peer: &VerifyingKey,
110		holding: &Holding,
111	) -> Result<bool, Self::Error> {
112		let _ = (space, peer, holding);
113		Ok(true)
114	}
115
116	/// The sealed blobs of a space that the replica asks `peer` for, at most `most` of them:
117	/// those it keeps and lacks, of which `peer`'s account lists a copy, or all of them if it
118	/// keeps no account of `peer` in the space; none of `asked`, which it asked `peer` for
119	/// before in this sync of the space. Asked once what came of the space is saved.
120	///
121	/// # Errors
122	///
123	/// Returns an error if the data cannot be read.
124	fn wanted_blobs(
125		&mut self,
126		space: SpaceId,
127		peer: &VerifyingKey,
128		asked: &BTreeSet<Hash>,
129		most: usize,
130	) -> Result<Vec<Hash>, Self::Error>;
131
132	/// Whether to send `peer` the sealed blobs of a space that it asks for: every one, but
133	/// none to a peer that the space no longer gives what is added.
134	///
135	/// # Errors
136	///
137	/// Returns an error if the data cannot be read.
138	fn sends_blobs(&self, space: SpaceId, peer: &VerifyingKey) -> Result<bool, Self::Error> {
139		let _ = (space, peer);
140		Ok(true)
141	}
142
143	/// The challenges to put to `peer` of a space's sealed blobs, which it is to prove that it
144	/// holds now: of the copies that this replica is about to remove, for which a copy on the
145	/// peer's disk is to stand, at most [`CHALLENGES_AT_ONCE`], as a sync puts no more to it
146	/// in a space. None by default. Asked as the initiator, once the blobs asked for came.
147	///
148	/// # Errors
149	///
150	/// Returns an error if the data cannot be read.
151	fn challenges(
152		&mut self,
153		space: SpaceId,
154		peer: &VerifyingKey,
155	) -> Result<Vec<Challenge>, Self::Error> {
156		let _ = (space, peer);
157		Ok(Vec::new())
158	}
159
160	/// Takes `peer`'s answers to the challenges put to it, in their order: `None` for a
161	/// blob that it did not prove.
162	///
163	/// # Errors
164	///
165	/// Returns an error if the data cannot be read or written.
166	fn proved(
167		&mut self,
168		space: SpaceId,
169		peer: &VerifyingKey,
170		challenges: &[Challenge],
171		answers: &[Option<[u8; 32]>],
172	) -> Result<(), Self::Error> {
173		let _ = (space, peer, challenges, answers);
174		Ok(())
175	}
176
177	/// Answers the challenges that `peer` puts to this replica, in their order: for each
178	/// sealed blob of the space that it holds and is not removing, once it has recorded that
179	/// it holds the blob for a while, the answer that [`Challenge::answer`] gives from its
180	/// bytes; `None` for the others. Answers none by default.
181	///
182	/// # Errors
183	///
184	/// Returns an error if the data cannot be read or written.
185	fn prove(
186		&mut self,
187		space: SpaceId,
188		peer: &VerifyingKey,
189		challenges: &[Challenge],
190	) -> Result<Vec<Option<[u8; 32]>>, Self::Error> {
191		let _ = (space, peer);
192		Ok(vec![None; challenges.len()])
193	}
194
195	/// An accepted change with its sealed payload and wrapped keys, as far as the replica
196	/// has them.
197	///
198	/// # Errors
199	///
200	/// Returns an error if the data cannot be read.
201	fn parcel(&self, space: SpaceId, id: ChangeId) -> Result<Option<Parcel>, Self::Error>;
202
203	/// A sealed blob that the replica holds, with its size in bytes.
204	///
205	/// # Errors
206	///
207	/// Returns an error if the data cannot be read.
208	fn blob(
209		&self,
210		space: SpaceId,
211		sealed: &Hash,
212	) -> Result<Option<(u64, BlobBytes<'_>)>, Self::Error>;
213
214	/// Takes a change from the other replica, `peer`, and returns whether it kept anything of
215	/// it. One that the log rejects, or has already, or that the replica takes nothing like
216	/// from that peer, is dropped, and is no error.
217	///
218	/// # Errors
219	///
220	/// Returns an error if the data cannot be written.
221	fn receive_change(
222		&mut self,
223		space: SpaceId,
224		peer: &VerifyingKey,
225		parcel: Parcel,
226	) -> Result<bool, Self::Error>;
227
228	/// Takes a wrapped record key from the other replica, and returns whether it kept it.
229	///
230	/// # Errors
231	///
232	/// Returns an error if the data cannot be written.
233	fn receive_record_key(
234		&mut self,
235		space: SpaceId,
236		statement: StatementId,
237		key: WrappedKey,
238	) -> Result<bool, Self::Error>;
239
240	/// Takes a wrapped blob key from the other replica, and returns whether it kept it.
241	///
242	/// # Errors
243	///
244	/// Returns an error if the data cannot be written.
245	fn receive_blob_key(
246		&mut self,
247		space: SpaceId,
248		sealed: Hash,
249		key: WrappedBlobKey,
250	) -> Result<bool, Self::Error>;
251
252	/// Takes a sealed blob of `size` bytes from the other replica, and returns whether it
253	/// kept it: only if its bytes have the sealed hash, and the replica wants it, such as
254	/// one whose key it holds. It need not read all of `bytes`, and should read none of a
255	/// blob it does not want.
256	///
257	/// # Errors
258	///
259	/// Returns an error if the data cannot be written, or reading `bytes` fails.
260	fn receive_blob(
261		&mut self,
262		space: SpaceId,
263		sealed: Hash,
264		size: u64,
265		bytes: &mut dyn Read,
266	) -> Result<bool, Self::Error>;
267
268	/// The encoding of a page of an account that the replica keeps, by the hash of its
269	/// encoding; `None` if it no longer keeps it.
270	///
271	/// # Errors
272	///
273	/// Returns an error if the data cannot be read.
274	fn account(&self, space: SpaceId, id: &Hash) -> Result<Option<Vec<u8>>, Self::Error> {
275		let _ = (space, id);
276		Ok(None)
277	}
278
279	/// Takes a page of an account from the other replica, and returns whether it kept it:
280	/// only a page that its author signed, of a replica of the space, and later than the
281	/// one of that page that it keeps.
282	///
283	/// # Errors
284	///
285	/// Returns an error if the data cannot be written.
286	fn receive_account(&mut self, space: SpaceId, page: Vec<u8>) -> Result<bool, Self::Error> {
287		let _ = (space, page);
288		Ok(false)
289	}
290
291	/// Saves what was received of a space, after its last item.
292	///
293	/// # Errors
294	///
295	/// Returns an error if the data cannot be written.
296	fn finish_space(&mut self, space: SpaceId) -> Result<(), Self::Error>;
297
298	/// Saves what it holds unsaved of what it received, as the sync is about to wait for the
299	/// other replica, or to send it items: a replica that saves received items together
300	/// does not keep them waiting on the network. One that saves each item as it comes has
301	/// nothing to do.
302	///
303	/// # Errors
304	///
305	/// Returns an error if the data cannot be written.
306	fn pause(&mut self) -> Result<(), Self::Error> {
307		Ok(())
308	}
309}
310
311/// How many things of a space went one way.
312#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
313pub struct Counts {
314	/// Changes, with their payloads and keys.
315	pub changes: usize,
316	/// Wrapped record keys and wrapped blob keys.
317	pub keys: usize,
318	/// Sealed blobs.
319	pub blobs: usize,
320	/// The bytes of the sealed blobs.
321	pub blob_bytes: u64,
322}
323
324impl Counts {
325	/// Whether nothing went.
326	#[must_use]
327	pub fn is_empty(&self) -> bool {
328		*self == Self::default()
329	}
330}
331
332/// What a space's sync sent and received.
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub struct SpaceSynced {
335	/// The space.
336	pub space: SpaceId,
337	/// What this side sent.
338	pub sent: Counts,
339	/// What this side received.
340	pub received: Counts,
341}
342
343/// What a sync did.
344#[derive(Clone, Debug, PartialEq, Eq)]
345pub struct Synced {
346	/// The other replica's verifying key.
347	pub peer: VerifyingKey,
348	/// The spaces synced, in order.
349	pub spaces: Vec<SpaceSynced>,
350}
351
352/// Syncs with the replica at the other end of `transport`, as the side that connected.
353///
354/// # Errors
355///
356/// Returns an error if the connection fails, the other side breaks the protocol or ends
357/// the connection, is no replica that this one syncs with, or the data cannot be read or
358/// written. What was received of a space before is kept.
359pub fn initiate<T: Transport, H: Holder>(
360	transport: &mut T,
361	holder: &mut H,
362) -> Result<Synced, SyncError> {
363	let result = initiate_with(transport, holder);
364	if let Err(error) = &result {
365		end(transport, error);
366	}
367	result
368}
369
370/// Syncs with the replica at the other end of `transport`, as the side that was connected
371/// to.
372///
373/// # Errors
374///
375/// As [`initiate`].
376pub fn respond<T: Transport, H: Holder>(
377	transport: &mut T,
378	holder: &mut H,
379) -> Result<Synced, SyncError> {
380	let result = respond_with(transport, holder);
381	if let Err(error) = &result {
382		end(transport, error);
383	}
384	result
385}
386
387/// Tells the other side why this side ends the connection, unless the other side ended it
388/// or the connection failed.
389fn end(transport: &mut impl Transport, error: &SyncError) {
390	if let Some(reason) = error.reason() {
391		let _ = SyncMessage::End(reason).send(transport);
392	}
393}
394
395/// What a side signs to prove who it is: `[binding, own endpoint, peer's endpoint]`.
396fn hello_message(binding: &[u8; 32], own: &[u8; 32], peer: &[u8; 32]) -> Vec<u8> {
397	cbor::encode(&Value::Array(vec![
398		Value::Bytes(binding.to_vec()),
399		Value::Bytes(own.to_vec()),
400		Value::Bytes(peer.to_vec()),
401	]))
402}
403
404/// Sends this side's hello, with `listings`, the initiator's listings by a recovery code.
405fn send_hello(
406	transport: &mut impl Transport,
407	holder: &impl Holder,
408	listings: Vec<RecoveryListing>,
409) -> Result<(), SyncError> {
410	let message = hello_message(
411		&transport.binding(),
412		&transport.own_endpoint(),
413		&transport.peer_endpoint(),
414	);
415	SyncMessage::Hello(
416		holder.verifying_key(),
417		holder.sign(HELLO, &message),
418		listings,
419	)
420	.send(transport)
421}
422
423/// Waits for the other side's hello, and returns its key if its signature checks, with the
424/// listings by a recovery code that it carries.
425fn receive_hello(
426	transport: &mut impl Transport,
427) -> Result<(VerifyingKey, Vec<RecoveryListing>), SyncError> {
428	let SyncMessage::Hello(key, signature, listings) = SyncMessage::receive(transport)? else {
429		return Err(SyncError::protocol("expected a hello"));
430	};
431	let message = hello_message(
432		&transport.binding(),
433		&transport.peer_endpoint(),
434		&transport.own_endpoint(),
435	);
436	key.verify(HELLO, &message, &signature)
437		.map_err(|_| SyncError::protocol("a hello whose signature does not check"))?;
438	Ok((key, listings))
439}
440
441fn initiate_with<T: Transport, H: Holder>(
442	transport: &mut T,
443	holder: &mut H,
444) -> Result<Synced, SyncError> {
445	let mut introductions = holder
446		.introductions(&transport.peer_endpoint())
447		.map_err(SyncError::holder)?;
448	introductions.truncate(crate::MOST_INTRODUCTIONS);
449	send_hello(transport, holder, introductions)?;
450	let (peer, listings) = receive_hello(transport)?;
451	// The responder knows the initiator by then, as it would not answer otherwise.
452	if !listings.is_empty() {
453		return Err(SyncError::protocol("a responder's hello with listings"));
454	}
455	let offered = holder.spaces_with(&peer).map_err(SyncError::holder)?;
456	if offered.is_empty() {
457		return Err(SyncError::NotAReplica);
458	}
459	SyncMessage::Spaces(offered.clone()).send(transport)?;
460	let SyncMessage::Spaces(agreed) = SyncMessage::receive(transport)? else {
461		return Err(SyncError::protocol("expected the spaces"));
462	};
463	let offered: BTreeSet<SpaceId> = offered.into_iter().collect();
464	if !agreed.iter().all(|space| offered.contains(space))
465		|| !agreed.windows(2).all(|pair| pair[0] < pair[1])
466	{
467		return Err(SyncError::protocol("spaces that were not offered"));
468	}
469	let mut spaces = Vec::new();
470	for space in agreed {
471		spaces.push(sync_space(transport, holder, (space, &peer))?);
472	}
473	SyncMessage::Done.send(transport)?;
474	match SyncMessage::receive(transport)? {
475		SyncMessage::Done => Ok(Synced { peer, spaces }),
476		_ => Err(SyncError::protocol("expected the end")),
477	}
478}
479
480/// Syncs one space as the initiator.
481fn sync_space<T: Transport, H: Holder>(
482	transport: &mut T,
483	holder: &mut H,
484	(space, peer): (SpaceId, &VerifyingKey),
485) -> Result<SpaceSynced, SyncError> {
486	holder.prepare(space).map_err(SyncError::holder)?;
487	let mut reconciling = Reconciling::new(holder.holdings(space).map_err(SyncError::holder)?)?;
488	SyncMessage::Reconcile(space, reconciling.initiate()?).send(transport)?;
489	let (mut have, mut need) = (Vec::new(), Vec::new());
490	loop {
491		let SyncMessage::Reconcile(answered, message) = SyncMessage::receive(transport)? else {
492			return Err(SyncError::protocol("expected a message of negentropy"));
493		};
494		if answered != space {
495			return Err(SyncError::protocol(
496				"a message of negentropy of another space",
497			));
498		}
499		match reconciling.answer(&message, &mut have, &mut need)? {
500			Some(next) => SyncMessage::Reconcile(space, next).send(transport)?,
501			None => break,
502		}
503	}
504	let mut synced = SpaceSynced {
505		space,
506		sent: Counts::default(),
507		received: Counts::default(),
508	};
509	for holding in reconciling.in_order(&have) {
510		send_item(transport, holder, (space, peer), &holding, &mut synced.sent)?;
511	}
512	let none = BTreeSet::new();
513	for wanted in need.chunks(WANTED_AT_ONCE) {
514		// What came of the chunk before is saved before the other side sends more.
515		holder.pause().map_err(SyncError::holder)?;
516		SyncMessage::Wanted(space, wanted.to_vec()).send(transport)?;
517		receive_until_sent(
518			transport,
519			holder,
520			(space, peer),
521			&none,
522			&mut synced.received,
523		)?;
524	}
525	// The initiator asks for the blobs it keeps, once what came is saved, so that it knows
526	// what the space's files are now; then the responder asks.
527	let mut asked = BTreeSet::new();
528	loop {
529		holder.pause().map_err(SyncError::holder)?;
530		let wanted = holder
531			.wanted_blobs(space, peer, &asked, WANTED_AT_ONCE)
532			.map_err(SyncError::holder)?;
533		if wanted.is_empty() {
534			break;
535		}
536		let more = wanted.len() >= WANTED_AT_ONCE;
537		asked.extend(wanted.iter().copied());
538		SyncMessage::Asked(space, wanted).send(transport)?;
539		receive_until_sent(
540			transport,
541			holder,
542			(space, peer),
543			&asked,
544			&mut synced.received,
545		)?;
546		if !more {
547			break;
548		}
549	}
550	loop {
551		SyncMessage::YourAsks(space).send(transport)?;
552		let SyncMessage::Asked(of, wanted) = next_message(transport, holder)? else {
553			return Err(SyncError::protocol("expected the blobs asked for"));
554		};
555		if of != space || wanted.len() > WANTED_AT_ONCE {
556			return Err(SyncError::protocol("blobs asked for out of turn"));
557		}
558		send_blobs(transport, holder, (space, peer), &wanted, &mut synced.sent)?;
559		SyncMessage::Sent(space).send(transport)?;
560		if wanted.len() < WANTED_AT_ONCE {
561			break;
562		}
563	}
564	// Last, the responder proves the blobs that this side asks it to, as this side is about
565	// to remove its own copies.
566	let mut challenges = holder.challenges(space, peer).map_err(SyncError::holder)?;
567	// One message of them in a space's sync, as the responder answers once.
568	challenges.truncate(CHALLENGES_AT_ONCE);
569	if !challenges.is_empty() {
570		SyncMessage::Prove(space, challenges.clone()).send(transport)?;
571		let SyncMessage::Proofs(of, answers) = next_message(transport, holder)? else {
572			return Err(SyncError::protocol("expected the proofs"));
573		};
574		if of != space || answers.len() != challenges.len() {
575			return Err(SyncError::protocol("proofs out of turn"));
576		}
577		holder
578			.proved(space, peer, &challenges, &answers)
579			.map_err(SyncError::holder)?;
580	}
581	holder.finish_space(space).map_err(SyncError::holder)?;
582	Ok(synced)
583}
584
585/// Takes the items that the other side sends of a space until it says it sent what was
586/// asked for. A blob is kept only if it is among `asked`.
587fn receive_until_sent<T: Transport, H: Holder>(
588	transport: &mut T,
589	holder: &mut H,
590	(space, peer): (SpaceId, &VerifyingKey),
591	asked: &BTreeSet<Hash>,
592	received: &mut Counts,
593) -> Result<(), SyncError> {
594	loop {
595		match next_message(transport, holder)? {
596			SyncMessage::Item(of, item) if of == space => {
597				receive_item(transport, holder, (space, peer), item, asked, received)?;
598			}
599			SyncMessage::Sent(of) if of == space => return Ok(()),
600			_ => return Err(SyncError::protocol("expected an item or the end of them")),
601		}
602	}
603}
604
605/// Sends the sealed blobs of a space that the other side asked for, those that this side
606/// holds, unless it sends that peer no blobs.
607fn send_blobs<T: Transport, H: Holder>(
608	transport: &mut T,
609	holder: &H,
610	(space, peer): (SpaceId, &VerifyingKey),
611	wanted: &[Hash],
612	sent: &mut Counts,
613) -> Result<(), SyncError> {
614	if !holder.sends_blobs(space, peer).map_err(SyncError::holder)? {
615		return Ok(());
616	}
617	let mut seen = BTreeSet::new();
618	for sealed in wanted {
619		if seen.insert(*sealed) {
620			send_blob(transport, holder, space, sealed, sent)?;
621		}
622	}
623	Ok(())
624}
625
626/// Sends a sealed blob that this side holds, with its bytes; one that it no longer holds is
627/// left out.
628fn send_blob<T: Transport, H: Holder>(
629	transport: &mut T,
630	holder: &H,
631	space: SpaceId,
632	sealed: &Hash,
633	sent: &mut Counts,
634) -> Result<(), SyncError> {
635	let Some((size, mut reader)) = holder.blob(space, sealed).map_err(SyncError::holder)? else {
636		return Ok(());
637	};
638	SyncMessage::Item(space, Item::Blob(*sealed, size)).send(transport)?;
639	let mut left = size;
640	let mut chunk = vec![0; BLOB_CHUNK];
641	while left > 0 {
642		let want = usize::try_from(left).map_or(BLOB_CHUNK, |left| left.min(BLOB_CHUNK));
643		reader
644			.read_exact(&mut chunk[..want])
645			.map_err(SyncError::holder)?;
646		transport.send(&crate::message::bytes_message(&chunk[..want]))?;
647		left -= want as u64;
648	}
649	sent.blobs += 1;
650	sent.blob_bytes += size;
651	Ok(())
652}
653
654/// The space a responder is syncing.
655struct Current {
656	reconciling: Reconciling,
657	synced: SpaceSynced,
658	/// The sealed blobs it asked for in this sync of the space.
659	asked: BTreeSet<Hash>,
660	/// Whether it asked for blobs that the initiator has yet to say it sent.
661	awaiting: bool,
662	/// Whether it asked for all it lacks: fewer blobs than one message holds.
663	asks_done: bool,
664	/// Whether the initiator asked it for proofs, which it does once in a space's sync.
665	proved: bool,
666}
667
668fn respond_with<T: Transport, H: Holder>(
669	transport: &mut T,
670	holder: &mut H,
671) -> Result<Synced, SyncError> {
672	let (peer, listings) = receive_hello(transport)?;
673	holder
674		.introduced(&peer, &listings)
675		.map_err(SyncError::holder)?;
676	let shared: BTreeSet<SpaceId> = holder
677		.spaces_with(&peer)
678		.map_err(SyncError::holder)?
679		.into_iter()
680		.collect();
681	// A peer that is no replica learns nothing, not even who this replica is.
682	if shared.is_empty() {
683		return Err(SyncError::NotAReplica);
684	}
685	send_hello(transport, holder, Vec::new())?;
686	let SyncMessage::Spaces(offered) = SyncMessage::receive(transport)? else {
687		return Err(SyncError::protocol("expected the spaces"));
688	};
689	let agreed: BTreeSet<SpaceId> = offered
690		.into_iter()
691		.filter(|space| shared.contains(space))
692		.collect();
693	SyncMessage::Spaces(agreed.iter().copied().collect()).send(transport)?;
694	let mut synced = Synced {
695		peer,
696		spaces: Vec::new(),
697	};
698	let mut current: Option<Current> = None;
699	let mut started: BTreeSet<SpaceId> = BTreeSet::new();
700	loop {
701		match next_message(transport, holder)? {
702			SyncMessage::Reconcile(space, message) => {
703				if current.as_ref().is_none_or(|now| now.synced.space != space) {
704					if !agreed.contains(&space) || !started.insert(space) {
705						return Err(SyncError::protocol("a space out of turn"));
706					}
707					finish(holder, current.take(), &mut synced)?;
708					current = Some(begin_space(holder, space)?);
709				}
710				let now = current
711					.as_mut()
712					.unwrap_or_else(|| unreachable!("set above"));
713				let answer = now.reconciling.respond(&message)?;
714				SyncMessage::Reconcile(space, answer).send(transport)?;
715			}
716			SyncMessage::Item(space, item) => {
717				let now = of_space(&mut current, space, "an item of a space out of turn")?;
718				receive_item(
719					transport,
720					holder,
721					(space, &peer),
722					item,
723					&now.asked,
724					&mut now.synced.received,
725				)?;
726			}
727			SyncMessage::Wanted(space, ids) => {
728				let now = of_space(&mut current, space, "wanted items of a space out of turn")?;
729				send_wanted(transport, holder, (now, &peer), &ids)?;
730			}
731			SyncMessage::Asked(space, wanted) => {
732				let now = of_space(
733					&mut current,
734					space,
735					"blobs asked for of a space out of turn",
736				)?;
737				answer_asked(transport, holder, (now, &peer), &wanted)?;
738			}
739			SyncMessage::YourAsks(space) => {
740				let now = of_space(&mut current, space, "asks of a space out of turn")?;
741				ask_as_responder(transport, holder, (now, &peer))?;
742			}
743			SyncMessage::Prove(space, challenges) => {
744				// Only once both sides asked for their blobs, and once in a space's sync, so
745				// that a peer makes this side read at most 64 MiB for each space.
746				let Some(now) = current.as_mut().filter(|now| {
747					now.synced.space == space && now.asks_done && !now.awaiting && !now.proved
748				}) else {
749					return Err(SyncError::protocol("proofs asked for out of turn"));
750				};
751				now.proved = true;
752				answer_challenges(transport, holder, (space, &peer), &challenges)?;
753			}
754			// The initiator sent the blobs that this side asked for.
755			SyncMessage::Sent(space)
756				if current
757					.as_ref()
758					.is_some_and(|now| now.synced.space == space && now.awaiting) =>
759			{
760				if let Some(now) = current.as_mut() {
761					now.awaiting = false;
762				}
763			}
764			SyncMessage::Done => {
765				finish(holder, current.take(), &mut synced)?;
766				SyncMessage::Done.send(transport)?;
767				return Ok(synced);
768			}
769			_ => return Err(SyncError::protocol("a message out of turn")),
770		}
771	}
772}
773
774/// The space that a responder syncs, if a message of `space` is of it; else the protocol
775/// is broken, as `what` says.
776fn of_space<'c>(
777	current: &'c mut Option<Current>,
778	space: SpaceId,
779	what: &'static str,
780) -> Result<&'c mut Current, SyncError> {
781	current
782		.as_mut()
783		.filter(|now| now.synced.space == space)
784		.ok_or_else(|| SyncError::protocol(what))
785}
786
787/// Readies a space for its sync as the responder: the replica's own account brought up to
788/// date, and what the space holds put into negentropy's set.
789fn begin_space<H: Holder>(holder: &mut H, space: SpaceId) -> Result<Current, SyncError> {
790	holder.prepare(space).map_err(SyncError::holder)?;
791	let holdings = holder.holdings(space).map_err(SyncError::holder)?;
792	Ok(Current {
793		reconciling: Reconciling::new(holdings)?,
794		synced: SpaceSynced {
795			space,
796			sent: Counts::default(),
797			received: Counts::default(),
798		},
799		asked: BTreeSet::new(),
800		awaiting: false,
801		asks_done: false,
802		proved: false,
803	})
804}
805
806/// Sends the items that the initiator asked a responder for, those it holds, then says it
807/// sent them.
808fn send_wanted<T: Transport, H: Holder>(
809	transport: &mut T,
810	holder: &mut H,
811	(now, peer): (&mut Current, &VerifyingKey),
812	ids: &[[u8; 32]],
813) -> Result<(), SyncError> {
814	let space = now.synced.space;
815	// Sending may take long, and what came before is not to wait meanwhile.
816	holder.pause().map_err(SyncError::holder)?;
817	for holding in now.reconciling.in_order(ids) {
818		send_item(
819			transport,
820			holder,
821			(space, peer),
822			&holding,
823			&mut now.synced.sent,
824		)?;
825	}
826	SyncMessage::Sent(space).send(transport)
827}
828
829/// Sends the sealed blobs that the initiator asked a responder for, those it holds, then
830/// says it sent them.
831fn answer_asked<T: Transport, H: Holder>(
832	transport: &mut T,
833	holder: &mut H,
834	(now, peer): (&mut Current, &VerifyingKey),
835	wanted: &[Hash],
836) -> Result<(), SyncError> {
837	if wanted.len() > WANTED_AT_ONCE {
838		return Err(SyncError::protocol("too many blobs asked for at once"));
839	}
840	let space = now.synced.space;
841	holder.pause().map_err(SyncError::holder)?;
842	send_blobs(
843		transport,
844		holder,
845		(space, peer),
846		wanted,
847		&mut now.synced.sent,
848	)?;
849	SyncMessage::Sent(space).send(transport)
850}
851
852/// Answers, as the responder, the challenges that the initiator put to it, once what came is
853/// saved: one answer for each, in their order.
854fn answer_challenges<T: Transport, H: Holder>(
855	transport: &mut T,
856	holder: &mut H,
857	(space, peer): (SpaceId, &VerifyingKey),
858	challenges: &[Challenge],
859) -> Result<(), SyncError> {
860	holder.pause().map_err(SyncError::holder)?;
861	let mut answers = holder
862		.prove(space, peer, challenges)
863		.map_err(SyncError::holder)?;
864	answers.resize(challenges.len(), None);
865	SyncMessage::Proofs(space, answers).send(transport)
866}
867
868/// Asks, as the responder, for the sealed blobs of the space that it keeps and lacks, once
869/// what came is saved, so that it knows what the space's files are now.
870fn ask_as_responder<T: Transport, H: Holder>(
871	transport: &mut T,
872	holder: &mut H,
873	(now, peer): (&mut Current, &VerifyingKey),
874) -> Result<(), SyncError> {
875	// The initiator asks again only while the asks before filled a message.
876	if now.asks_done || now.awaiting {
877		return Err(SyncError::protocol("asks of a space out of turn"));
878	}
879	let space = now.synced.space;
880	holder.pause().map_err(SyncError::holder)?;
881	let wanted = holder
882		.wanted_blobs(space, peer, &now.asked, WANTED_AT_ONCE)
883		.map_err(SyncError::holder)?;
884	now.asked.extend(wanted.iter().copied());
885	now.asks_done = wanted.len() < WANTED_AT_ONCE;
886	now.awaiting = true;
887	SyncMessage::Asked(space, wanted).send(transport)
888}
889
890/// The next message, once the holder has saved what it received, if the message has not
891/// arrived yet.
892fn next_message<T: Transport, H: Holder>(
893	transport: &mut T,
894	holder: &mut H,
895) -> Result<SyncMessage, SyncError> {
896	if !transport.has_message() {
897		holder.pause().map_err(SyncError::holder)?;
898	}
899	SyncMessage::receive(transport)
900}
901
902/// Saves what a responder received of a space.
903fn finish(
904	holder: &mut impl Holder,
905	current: Option<Current>,
906	synced: &mut Synced,
907) -> Result<(), SyncError> {
908	if let Some(current) = current {
909		holder
910			.finish_space(current.synced.space)
911			.map_err(SyncError::holder)?;
912		synced.spaces.push(current.synced);
913	}
914	Ok(())
915}
916
917/// Sends an item that the other side lacks. One that this side no longer has, or does not
918/// send that peer, is left out.
919fn send_item<T: Transport, H: Holder>(
920	transport: &mut T,
921	holder: &H,
922	(space, peer): (SpaceId, &VerifyingKey),
923	holding: &Holding,
924	sent: &mut Counts,
925) -> Result<(), SyncError> {
926	if !holder
927		.sends(space, peer, holding)
928		.map_err(SyncError::holder)?
929	{
930		return Ok(());
931	}
932	match holding {
933		Holding::Change { id, .. } => {
934			if let Some(parcel) = holder.parcel(space, *id).map_err(SyncError::holder)? {
935				SyncMessage::Item(space, Item::Change(Box::new(parcel))).send(transport)?;
936				sent.changes += 1;
937			}
938		}
939		Holding::RecordKey { statement, key } => {
940			SyncMessage::Item(space, Item::RecordKey(*statement, key.clone())).send(transport)?;
941			sent.keys += 1;
942		}
943		Holding::BlobKey { sealed, key } => {
944			SyncMessage::Item(space, Item::BlobKey(*sealed, key.clone())).send(transport)?;
945			sent.keys += 1;
946		}
947		Holding::Account { id, .. } => {
948			if let Some(page) = holder.account(space, id).map_err(SyncError::holder)? {
949				SyncMessage::Item(space, Item::Account(page)).send(transport)?;
950			}
951		}
952	}
953	Ok(())
954}
955
956/// Takes an item from the other side; a sealed blob only if it is among `asked`.
957fn receive_item<T: Transport, H: Holder>(
958	transport: &mut T,
959	holder: &mut H,
960	(space, peer): (SpaceId, &VerifyingKey),
961	item: Item,
962	asked: &BTreeSet<Hash>,
963	received: &mut Counts,
964) -> Result<(), SyncError> {
965	match item {
966		Item::Change(parcel) => {
967			if holder
968				.receive_change(space, peer, *parcel)
969				.map_err(SyncError::holder)?
970			{
971				received.changes += 1;
972			}
973		}
974		Item::RecordKey(statement, key) => {
975			if holder
976				.receive_record_key(space, statement, key)
977				.map_err(SyncError::holder)?
978			{
979				received.keys += 1;
980			}
981		}
982		Item::BlobKey(sealed, key) => {
983			if holder
984				.receive_blob_key(space, sealed, key)
985				.map_err(SyncError::holder)?
986			{
987				received.keys += 1;
988			}
989		}
990		Item::Blob(sealed, size) => {
991			let mut incoming = Incoming {
992				transport,
993				left: size,
994				buffer: Vec::new(),
995				at: 0,
996				error: None,
997			};
998			// A blob that was not asked for is read past, and kept nowhere: a replica keeps only
999			// what it asks for.
1000			let kept = if asked.contains(&sealed) {
1001				holder.receive_blob(space, sealed, size, &mut incoming)
1002			} else {
1003				Ok(false)
1004			};
1005			// What the holder did not read is read all the same, to reach the next message.
1006			while incoming.error.is_none()
1007				&& (incoming.at < incoming.buffer.len() || incoming.left > 0)
1008			{
1009				incoming.at = incoming.buffer.len();
1010				let _ = incoming.fill();
1011			}
1012			if let Some(error) = incoming.error {
1013				return Err(error);
1014			}
1015			if kept.map_err(SyncError::holder)? {
1016				received.blobs += 1;
1017				received.blob_bytes += size;
1018			}
1019		}
1020		Item::Account(page) => {
1021			holder
1022				.receive_account(space, page)
1023				.map_err(SyncError::holder)?;
1024		}
1025	}
1026	Ok(())
1027}
1028
1029/// The bytes of a blob, as they come in messages.
1030struct Incoming<'t, T> {
1031	transport: &'t mut T,
1032	/// The bytes still to come in messages.
1033	left: u64,
1034	/// The bytes of the last message, and how many of them were read.
1035	buffer: Vec<u8>,
1036	at: usize,
1037	/// What went wrong with the connection, which ends the sync.
1038	error: Option<SyncError>,
1039}
1040
1041impl<T: Transport> Incoming<'_, T> {
1042	/// Waits for the next message of bytes, if more are to come.
1043	fn fill(&mut self) -> io::Result<()> {
1044		if self.left == 0 {
1045			return Ok(());
1046		}
1047		let received = SyncMessage::receive(self.transport).and_then(|message| match message {
1048			SyncMessage::Bytes(bytes) if !bytes.is_empty() && bytes.len() as u64 <= self.left => {
1049				Ok(bytes)
1050			}
1051			_ => Err(SyncError::protocol("expected a blob's bytes")),
1052		});
1053		match received {
1054			Ok(bytes) => {
1055				self.left -= bytes.len() as u64;
1056				self.buffer = bytes;
1057				self.at = 0;
1058				Ok(())
1059			}
1060			Err(error) => {
1061				self.error = Some(error);
1062				Err(io::Error::other("the connection failed"))
1063			}
1064		}
1065	}
1066}
1067
1068impl<T: Transport> Read for Incoming<'_, T> {
1069	fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
1070		if self.error.is_some() {
1071			return Err(io::Error::other("the connection failed"));
1072		}
1073		if self.at == self.buffer.len() {
1074			self.fill()?;
1075			if self.at == self.buffer.len() {
1076				return Ok(0);
1077			}
1078		}
1079		let count = out.len().min(self.buffer.len() - self.at);
1080		out[..count].copy_from_slice(&self.buffer[self.at..self.at + count]);
1081		self.at += count;
1082		Ok(count)
1083	}
1084}