Skip to main content

nibkeep_sync/
lib.rs

1//! How NibKeep replicas pair and sync their spaces: the messages they send, reconciling
2//! what two replicas hold with negentropy, and the exchanges of pairing and syncing, which
3//! run over any [`Transport`] and work on the replica's data through the traits
4//! [`Holder`] and [`Sponsoring`]. The crate does no I/O of its own, so that the simulation
5//! can run many replicas in one process.
6//!
7//! The protocol is specified in `docs/spec/sync.md`, and the reasons for it are in
8//! `docs/Technical-design.md`, section 10.
9
10mod error;
11mod invite;
12mod message;
13mod pack;
14mod pair;
15mod proof;
16mod reconcile;
17mod session;
18mod transport;
19
20pub use error::{Reason, SyncError};
21pub use invite::{Accepting, Invitation, Inviting, accept, invite};
22pub use pack::{MOST_PACK_BLOB, PACK_SIZE, PackItem, PackReader, pack_header, pack_item};
23pub use pair::{Joined, Sponsored, Sponsoring, join, joined, refuse, sponsor};
24pub use proof::{
25	CHALLENGES_AT_ONCE, Challenge, MOST_RANGE_LEN, MOST_RANGES, RANGE_LEN, RANGES, Range,
26};
27pub use reconcile::{Holding, item_id};
28pub use session::{BlobBytes, Counts, Holder, SpaceSynced, Synced, initiate, respond};
29pub use transport::{MAX_MESSAGE_LEN, Transport, TransportError};
30
31/// How many listings by a recovery code an initiator's hello carries at most: one for each
32/// space or group that lists it by a code ([Sync](../../../docs/spec/sync.md#3-syncing)).
33pub const MOST_INTRODUCTIONS: usize = 1024;
34
35/// What the fuzz targets reach: reading the messages that other devices send.
36#[doc(hidden)]
37pub mod fuzzing {
38	use nibkeep_base::{Hash, SpaceId};
39
40	use crate::message::{InviteMessage, Item, PairMessage, SyncMessage};
41	use crate::reconcile::Reconciling;
42	use crate::{Holding, Reason};
43
44	/// Reads a message of pairing, and writes it out again, if it is one.
45	#[must_use]
46	pub fn pair_message(bytes: &[u8]) -> Option<Vec<u8>> {
47		PairMessage::decode(bytes)
48			.ok()
49			.map(|message| message.encode())
50	}
51
52	/// Reads a message of an invitation, and writes it out again, if it is one.
53	#[must_use]
54	pub fn invite_message(bytes: &[u8]) -> Option<Vec<u8>> {
55		InviteMessage::decode(bytes)
56			.ok()
57			.map(|message| message.encode())
58	}
59
60	/// Reads a message of syncing, and writes it out again, if it is one.
61	#[must_use]
62	pub fn sync_message(bytes: &[u8]) -> Option<Vec<u8>> {
63		SyncMessage::decode(bytes)
64			.ok()
65			.map(|message| message.encode())
66	}
67
68	/// Reads a pack to its end, and checks that each item writes out again as it reads;
69	/// `None` if it is no pack, or holds what a pack does not.
70	#[must_use]
71	pub fn pack(bytes: &[u8]) -> Option<()> {
72		let mut reader = crate::PackReader::new(bytes).ok()?;
73		let space = reader.space();
74		while let Some((item, start, length)) = reader.next_item().ok()? {
75			let written = crate::pack_item(space, &item);
76			assert!(
77				bytes.get(start..start + length) == Some(written.as_slice()),
78				"an item of a pack writes out as it was read"
79			);
80			assert!(
81				crate::PackReader::item_at(space, &written).ok().as_ref() == Some(&item),
82				"an item reads alone as in its pack"
83			);
84		}
85		Some(())
86	}
87
88	/// Answers a message of negentropy as each side, over a few items.
89	pub fn negentropy(bytes: &[u8]) {
90		let holdings = || {
91			(0..40_u8)
92				.map(|byte| Holding::Account {
93					id: Hash::of(&[byte]),
94					issued: u64::from(byte),
95				})
96				.collect()
97		};
98		if let Ok(mut responder) = Reconciling::new(holdings()) {
99			let _ = responder.respond(bytes);
100		}
101		if let Ok(mut initiator) = Reconciling::new(holdings())
102			&& initiator.initiate().is_ok()
103		{
104			let _ = initiator.answer(bytes, &mut Vec::new(), &mut Vec::new());
105		}
106	}
107
108	/// The first message of negentropy over a few items, as a seed.
109	///
110	/// # Panics
111	///
112	/// Never: the items are few and well formed.
113	#[must_use]
114	pub fn negentropy_sample() -> Vec<u8> {
115		let mut initiator = Reconciling::new(
116			(0..3_u8)
117				.map(|byte| Holding::Account {
118					id: Hash::of(&[byte]),
119					issued: u64::from(byte),
120				})
121				.collect(),
122		)
123		.expect("a set");
124		initiator.initiate().expect("a message")
125	}
126
127	/// Messages, each with its name.
128	pub type Named = Vec<(&'static str, Vec<u8>)>;
129
130	/// Messages of an invitation, as seeds for the fuzz targets.
131	#[must_use]
132	pub fn invitation_samples() -> Named {
133		vec![
134			("end", InviteMessage::End(Reason::Declined).encode()),
135			("pake", InviteMessage::Pake(vec![0x41; 33], None).encode()),
136			(
137				"pake-proven",
138				InviteMessage::Pake(vec![0x41; 33], Some([3; 32])).encode(),
139			),
140			(
141				"listing",
142				InviteMessage::Listing("bGlzdGluZw".to_owned(), [3; 32]).encode(),
143			),
144			("joined", InviteMessage::Joined.encode()),
145		]
146	}
147
148	/// Messages of each kind, as seeds for the fuzz targets: pairing's first, then
149	/// syncing's.
150	#[must_use]
151	pub fn samples() -> (Named, Named) {
152		let space = SpaceId::from_bytes([5; 16]);
153		let pairing = vec![
154			("end", PairMessage::End(Reason::WrongCode).encode()),
155			("pake", PairMessage::Pake(vec![0x41; 33], None).encode()),
156			(
157				"pake-proven",
158				PairMessage::Pake(vec![0x41; 33], Some([3; 32])).encode(),
159			),
160			("joined", PairMessage::Joined(Vec::new()).encode()),
161			(
162				"joined-listing",
163				PairMessage::Joined(vec!["bGlzdGluZw".to_owned()]).encode(),
164			),
165		];
166		let first = negentropy_sample();
167		let signing = nibkeep_crypto::SigningKey::from_bytes(&[6; 32]);
168		let code = nibkeep_crypto::SigningKey::from_bytes(&[8; 32]);
169		let listing = nibkeep_governance::RecoveryListing {
170			space,
171			record: nibkeep_base::EntityId::from_bytes([1; 16]),
172			owner: nibkeep_base::EntityId::from_bytes([2; 16]),
173			encryption: Hash::of(b"encryption key"),
174			key: signing.verifying_key(),
175			recovery_key: code.verifying_key(),
176			signature: code.sign("sample", b"listing"),
177		};
178		let hello = |listings| {
179			SyncMessage::Hello(
180				signing.verifying_key(),
181				signing.sign("sample", b"hello"),
182				listings,
183			)
184			.encode()
185		};
186		let syncing = vec![
187			("end", SyncMessage::End(Reason::Busy).encode()),
188			("hello", hello(Vec::new())),
189			("hello-listings", hello(vec![listing])),
190			("spaces", SyncMessage::Spaces(vec![space]).encode()),
191			("reconcile", SyncMessage::Reconcile(space, first).encode()),
192			(
193				"blob",
194				SyncMessage::Item(space, Item::Blob(Hash::of(b"sealed"), 7)).encode(),
195			),
196			("wanted", SyncMessage::Wanted(space, vec![[9; 32]]).encode()),
197			("sent", SyncMessage::Sent(space).encode()),
198			("bytes", SyncMessage::Bytes(b"sealed!".to_vec()).encode()),
199			("done", SyncMessage::Done.encode()),
200			(
201				"asked",
202				SyncMessage::Asked(space, vec![Hash::of(b"sealed")]).encode(),
203			),
204			("your-asks", SyncMessage::YourAsks(space).encode()),
205			(
206				"prove",
207				SyncMessage::Prove(
208					space,
209					vec![crate::Challenge {
210						sealed: Hash::of(b"sealed"),
211						key: [3; 32],
212						ranges: vec![crate::Range { offset: 0, len: 7 }],
213						plain: true,
214					}],
215				)
216				.encode(),
217			),
218			(
219				"proofs",
220				SyncMessage::Proofs(space, vec![Some([4; 32]), None]).encode(),
221			),
222		];
223		(pairing, syncing)
224	}
225}