aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/document/mod.rs4
-rw-r--r--src/simtest/timing.rs2
-rw-r--r--src/swarm/peer/handshake.rs2
-rw-r--r--src/swarm/peer/inbound.rs14
-rw-r--r--src/transport/mod.rs15
-rw-r--r--src/transport/wire.rs586
6 files changed, 588 insertions, 35 deletions
diff --git a/src/document/mod.rs b/src/document/mod.rs
index 2e65bee..e219ce4 100644
--- a/src/document/mod.rs
+++ b/src/document/mod.rs
@@ -46,6 +46,10 @@ impl std::fmt::Debug for UnitId {
}
}
+/// The kind of document this build holds, as nodes say it to each other in handshakes
+/// (`docs/document.md`): a swarm is of one kind.
+pub(crate) const KIND: &str = "automerge";
+
/// The version of Automerge this build makes documents with: a remake needs the same on
/// every node, and a federation the same encoding of a change (`remake::snapshot`).
pub(crate) fn engine_version() -> &'static str {
diff --git a/src/simtest/timing.rs b/src/simtest/timing.rs
index 3f03562..80353fb 100644
--- a/src/simtest/timing.rs
+++ b/src/simtest/timing.rs
@@ -284,6 +284,7 @@ async fn resent_hello_keeps_the_session() {
handshake,
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
})
};
for repeated in [handshake, handshake.saturating_sub(1)] {
@@ -329,6 +330,7 @@ async fn late_epoch_does_not_flip_a_peers_epoch() {
handshake: 1,
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
})
};
let status = |epoch: Epoch, epoch_seq: u32| {
diff --git a/src/swarm/peer/handshake.rs b/src/swarm/peer/handshake.rs
index d3f6b99..2e5a315 100644
--- a/src/swarm/peer/handshake.rs
+++ b/src/swarm/peer/handshake.rs
@@ -144,6 +144,7 @@ async fn transmit_hello(state: &AppState, peer: &str) -> Result<()> {
.await
.map(|root| root.0.to_vec()),
party: party(state),
+ kind: crate::document::KIND.to_owned(),
}),
)
.await;
@@ -254,6 +255,7 @@ pub(super) async fn send_hello_reply(
.await
.map(|root| root.0.to_vec()),
party: party(state),
+ kind: crate::document::KIND.to_owned(),
};
debug!(to = %peer, ready, "Sending HELLO_REPLY");
diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs
index e23ec14..a558ded 100644
--- a/src/swarm/peer/inbound.rs
+++ b/src/swarm/peer/inbound.rs
@@ -108,6 +108,20 @@ pub(crate) async fn handle_message(
return Ok(());
}
+ // Its document's kind: another than ours has nothing ours takes.
+ let kind = match &message {
+ ParsedMessage::Hello(hello) => Some(&hello.kind),
+ ParsedMessage::HelloReply(reply) => Some(&reply.kind),
+ _ => None,
+ };
+ if let Some(theirs) = kind.filter(|kind| *kind != crate::document::KIND) {
+ anyhow::bail!(
+ "{peer} holds a document of another kind ({theirs}; this node's is {}): they sync \
+ nothing; a release that knows the kind does",
+ crate::document::KIND
+ );
+ }
+
// The root its document starts from: another than ours, of our epoch, is another
// history; what a joiner takes as its root follows those named (`swarm::roots`).
match &message {
diff --git a/src/transport/mod.rs b/src/transport/mod.rs
index 4fa3ec3..61abe9c 100644
--- a/src/transport/mod.rs
+++ b/src/transport/mod.rs
@@ -587,6 +587,18 @@ pub(crate) struct HelloRequest {
/// The party the sender is of, in a swarm holding a store (`--store-party`): nodes of
/// one sync with the nodes its parties list, each as its party's. None elsewhere.
pub(crate) party: Option<String>,
+ /// The kind of the sender's document (`document::KIND`): nodes whose documents are of
+ /// different kinds don't sync. Said from the wire version on that carries what is a
+ /// kind's as bytes (`wire::KINDS`); a build speaking none says none, and is of the
+ /// kind there was then.
+ #[serde(skip, default = "unsaid_kind")]
+ pub(crate) kind: String,
+}
+
+/// The kind of a document whose node says none (`HelloRequest::kind`): Automerge's, the
+/// only one there was before kinds were said.
+fn unsaid_kind() -> String {
+ crate::document::KIND.to_owned()
}
/// A peer a HELLO_REPLY lists: who it is, and where the sender reaches it.
@@ -677,6 +689,9 @@ pub(crate) struct HelloReply {
pub(crate) root: Option<Vec<u8>>,
/// As `HelloRequest::party`.
pub(crate) party: Option<String>,
+ /// The kind of the sender's document, as `HelloRequest::kind` has it.
+ #[serde(skip, default = "unsaid_kind")]
+ pub(crate) kind: String,
}
/// Bytes shown as lowercase hex, e.g. run IDs in logs.
diff --git a/src/transport/wire.rs b/src/transport/wire.rs
index 56883e8..79532fb 100644
--- a/src/transport/wire.rs
+++ b/src/transport/wire.rs
@@ -30,11 +30,15 @@ use super::{EncodedMessage, MessageKind, ParsedMessage};
/// The wire format's version, the first byte of every payload. Bump it with every change
/// to a message type or a codec (`golden_bytes` fails then).
-pub(crate) const VERSION: u8 = 52;
+pub(crate) const VERSION: u8 = 53;
/// The oldest version this build speaks: the messages of every version from it to
/// `VERSION` it reads. Its SPEAKS says so.
-pub(crate) const OLDEST: u8 = VERSION;
+pub(crate) const OLDEST: u8 = 52;
+
+/// The first version in which what is a document's kind's goes as bytes the wire doesn't
+/// read (`kinds`), and a handshake says the kind.
+pub(crate) const KINDS: u8 = 53;
/// The first byte of a SPEAKS, which no version is. Its layout, never to change: that
/// byte, the oldest version the sender speaks, the newest, then the 32 bytes of the ID
@@ -125,27 +129,22 @@ pub(crate) fn choose(oldest: u8, newest: u8) -> Option<u8> {
/// as a build speaking only that one reads it. A SPEAKS is laid out alike in every one,
/// and so are WHO and ME (`PROOFS`), but for the version they say.
pub(crate) fn encode_in(message: &ParsedMessage, version: u8) -> Result<Vec<u8>, WireError> {
- if matches!(message, ParsedMessage::Who(_) | ParsedMessage::Me(_)) && version >= PROOFS {
- let mut payload = encode(message)?;
- payload[0] = version;
+ if let ParsedMessage::Speaks(speaks) = message {
+ let mut payload = vec![SPEAKS, speaks.oldest, speaks.newest];
+ payload.extend(speaks.revision.iter().flatten());
return Ok(payload);
}
- // Each older version this build still speaks is encoded here, from its own types,
- // once its messages differ from the newest's; this build's are the newest's alone.
- if version != VERSION && !matches!(message, ParsedMessage::Speaks(_)) {
+ let proof =
+ matches!(message, ParsedMessage::Who(_) | ParsedMessage::Me(_)) && version >= PROOFS;
+ if !(OLDEST..=VERSION).contains(&version) && !proof {
return Err(WireError::Version(version));
}
- encode(message)
-}
-
-/// The payload of `message`, in the newest wire version.
-pub(crate) fn encode(message: &ParsedMessage) -> Result<Vec<u8>, WireError> {
- if let ParsedMessage::Speaks(speaks) = message {
- let mut payload = vec![SPEAKS, speaks.oldest, speaks.newest];
- payload.extend(speaks.revision.iter().flatten());
+ let mut payload = vec![version, tag(message.kind())];
+ // From `KINDS` on, what is a document's kind's goes as bytes (`kinds`); before, as
+ // the messages' own types have it, which are Automerge's.
+ if version >= KINDS && kinds::write(&mut payload, message)? {
return Ok(payload);
}
- let mut payload = vec![VERSION, tag(message.kind())];
match message {
ParsedMessage::Hello(hello) => rmp_serde::encode::write(&mut payload, hello)?,
ParsedMessage::HelloReply(reply) => rmp_serde::encode::write(&mut payload, reply)?,
@@ -174,6 +173,322 @@ pub(crate) fn encode(message: &ParsedMessage) -> Result<Vec<u8>, WireError> {
Ok(payload)
}
+/// The payload of `message`, in the newest wire version.
+#[cfg(test)]
+pub(crate) fn encode(message: &ParsedMessage) -> Result<Vec<u8>, WireError> {
+ encode_in(message, VERSION)
+}
+
+/// The messages that carry what is a document's kind's (`docs/document.md`, Passing on),
+/// as the versions from `KINDS` on lay them out: what is the kind's is bytes, which the
+/// wire carries and doesn't read. Automerge's bytes are what the version before carried
+/// in the messages' own fields, in MessagePack as there.
+///
+/// * HELLO, HELLO_REPLY: the message as before, then the kind (`document::KIND`).
+/// * SYNC: its body, with whether the sender takes it as delivered, as bytes; and what
+/// vouches for what it carries, as bytes (the signatures, as before).
+/// * STATUS, STATUS_REPLY: where the sender's document stands, as bytes.
+/// * BLOB: a request's account of what it asks for in bulk (a delta's heads), as bytes.
+mod kinds {
+ use serde::{Deserialize, Serialize};
+ use serde_bytes::ByteBuf;
+
+ use super::{ParsedMessage, WireError, codec};
+ use crate::clock::UnixMillis;
+ use crate::document::replica::Epoch;
+ use crate::transport::{
+ BlobBody, BlobId, BlobMessage, DeltaSpec, EpochTag, HeadsSummary, Status, SyncBody,
+ SyncEnvelope,
+ };
+
+ #[derive(Serialize)]
+ struct SyncOut<'a> {
+ epoch: EpochTag,
+ epoch_seq: u32,
+ #[serde(with = "serde_bytes")]
+ body: &'a [u8],
+ ready: bool,
+ writer: Option<u64>,
+ sent: UnixMillis,
+ #[serde(with = "serde_bytes")]
+ vouchers: &'a [u8],
+ }
+
+ #[derive(Deserialize)]
+ struct SyncIn {
+ epoch: EpochTag,
+ epoch_seq: u32,
+ body: ByteBuf,
+ ready: bool,
+ writer: Option<u64>,
+ sent: UnixMillis,
+ vouchers: ByteBuf,
+ }
+
+ #[derive(Serialize)]
+ struct StatusOut<'a> {
+ #[serde(with = "serde_bytes")]
+ stamp: &'a [u8],
+ #[serde(with = "codec::epoch")]
+ epoch: Epoch,
+ epoch_seq: u32,
+ ready: bool,
+ syncs_with_you: bool,
+ leaving: bool,
+ announcing: bool,
+ reaches: &'a Option<Vec<u64>>,
+ #[serde(with = "serde_bytes")]
+ round_trips: &'a Option<Vec<u8>>,
+ }
+
+ #[derive(Deserialize)]
+ struct StatusIn {
+ stamp: ByteBuf,
+ #[serde(with = "codec::epoch")]
+ epoch: Epoch,
+ epoch_seq: u32,
+ ready: bool,
+ syncs_with_you: bool,
+ leaving: bool,
+ announcing: bool,
+ reaches: Option<Vec<u64>>,
+ #[serde(with = "serde_bytes")]
+ round_trips: Option<Vec<u8>>,
+ }
+
+ /// Where an Automerge document stands, as its bytes have it.
+ struct StampOut<'a>(&'a HeadsSummary);
+
+ impl Serialize for StampOut<'_> {
+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
+ codec::heads::serialize(self.0, s)
+ }
+ }
+
+ #[derive(Deserialize)]
+ struct StampIn(#[serde(with = "codec::heads")] HeadsSummary);
+
+ #[derive(Serialize, Deserialize)]
+ struct Blob {
+ #[serde(with = "codec::epoch")]
+ epoch: Epoch,
+ epoch_seq: u32,
+ id: Id,
+ body: Body,
+ sent: UnixMillis,
+ }
+
+ /// What a blob is of: a unit by its name, content by its hash, or what a kind offers
+ /// in bulk by its name for it.
+ #[derive(Serialize, Deserialize)]
+ enum Id {
+ Unit(#[serde(with = "codec::bytes32")] [u8; 32]),
+ Content(#[serde(with = "codec::bytes32")] [u8; 32]),
+ Bulk(#[serde(with = "codec::bytes32")] [u8; 32]),
+ }
+
+ /// `BlobBody`, a request saying what it asks for in bulk as bytes.
+ #[derive(Serialize, Deserialize)]
+ enum Body {
+ Request {
+ chunks: Vec<u32>,
+ spec: Option<ByteBuf>,
+ },
+ Manifest {
+ size: u64,
+ chunk_size: u32,
+ #[serde(with = "codec::hashes32")]
+ hashes: Vec<[u8; 32]>,
+ },
+ Chunk {
+ index: u32,
+ #[serde(with = "codec::shared_bytes")]
+ data: bytes::Bytes,
+ },
+ Missing,
+ DeflatedChunk {
+ index: u32,
+ #[serde(with = "codec::shared_bytes")]
+ data: bytes::Bytes,
+ },
+ }
+
+ /// Writes `message` after `payload`, where its layout is this module's: whether it is.
+ pub(super) fn write(payload: &mut Vec<u8>, message: &ParsedMessage) -> Result<bool, WireError> {
+ match message {
+ ParsedMessage::Hello(hello) => {
+ rmp_serde::encode::write(payload, &(hello, hello.kind.as_str()))?
+ }
+ ParsedMessage::HelloReply(reply) => {
+ rmp_serde::encode::write(payload, &(reply, reply.kind.as_str()))?
+ }
+ ParsedMessage::Sync(envelope) => {
+ let body = rmp_serde::to_vec(&(&envelope.body, envelope.delivered))?;
+ rmp_serde::encode::write(
+ payload,
+ &SyncOut {
+ epoch: envelope.epoch,
+ epoch_seq: envelope.epoch_seq,
+ body: &body,
+ ready: envelope.ready,
+ writer: envelope.writer,
+ sent: envelope.sent,
+ vouchers: &envelope.signatures,
+ },
+ )?
+ }
+ ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => {
+ let stamp = rmp_serde::to_vec(&StampOut(&status.heads))?;
+ rmp_serde::encode::write(
+ payload,
+ &StatusOut {
+ stamp: &stamp,
+ epoch: status.epoch,
+ epoch_seq: status.epoch_seq,
+ ready: status.ready,
+ syncs_with_you: status.syncs_with_you,
+ leaving: status.leaving,
+ announcing: status.announcing,
+ reaches: &status.reaches,
+ round_trips: &status.round_trips,
+ },
+ )?
+ }
+ ParsedMessage::Blob(blob) => {
+ let body = match &blob.body {
+ BlobBody::Request { chunks, delta } => Body::Request {
+ chunks: chunks.clone(),
+ spec: match delta {
+ Some(spec) => Some(ByteBuf::from(rmp_serde::to_vec(spec)?)),
+ None => None,
+ },
+ },
+ BlobBody::Manifest {
+ size,
+ chunk_size,
+ hashes,
+ } => Body::Manifest {
+ size: *size,
+ chunk_size: *chunk_size,
+ hashes: hashes.clone(),
+ },
+ BlobBody::Chunk { index, data } => Body::Chunk {
+ index: *index,
+ data: data.clone(),
+ },
+ BlobBody::Missing => Body::Missing,
+ BlobBody::DeflatedChunk { index, data } => Body::DeflatedChunk {
+ index: *index,
+ data: data.clone(),
+ },
+ };
+ rmp_serde::encode::write(
+ payload,
+ &Blob {
+ epoch: blob.epoch,
+ epoch_seq: blob.epoch_seq,
+ id: match blob.id {
+ BlobId::Change(hash) => Id::Unit(hash.0),
+ BlobId::Content(hash) => Id::Content(hash),
+ BlobId::Delta(id) => Id::Bulk(id),
+ },
+ body,
+ sent: blob.sent,
+ },
+ )?
+ }
+ _ => return Ok(false),
+ }
+ Ok(true)
+ }
+
+ /// The HELLO in `body`.
+ pub(super) fn hello(body: &[u8]) -> Result<ParsedMessage, WireError> {
+ let (mut hello, kind): (crate::transport::HelloRequest, String) =
+ rmp_serde::from_slice(body)?;
+ hello.kind = kind;
+ Ok(ParsedMessage::Hello(hello))
+ }
+
+ /// The HELLO_REPLY in `body`.
+ pub(super) fn hello_reply(body: &[u8]) -> Result<ParsedMessage, WireError> {
+ let (mut reply, kind): (crate::transport::HelloReply, String) =
+ rmp_serde::from_slice(body)?;
+ reply.kind = kind;
+ Ok(ParsedMessage::HelloReply(reply))
+ }
+
+ /// The SYNC in `body`.
+ pub(super) fn sync(body: &[u8]) -> Result<ParsedMessage, WireError> {
+ let sync: SyncIn = rmp_serde::from_slice(body)?;
+ let (body, delivered): (SyncBody, bool) = rmp_serde::from_slice(&sync.body)?;
+ Ok(ParsedMessage::Sync(SyncEnvelope {
+ epoch: sync.epoch,
+ epoch_seq: sync.epoch_seq,
+ body,
+ ready: sync.ready,
+ writer: sync.writer,
+ delivered,
+ sent: sync.sent,
+ signatures: sync.vouchers,
+ }))
+ }
+
+ /// The STATUS, or the STATUS_REPLY, in `body`.
+ pub(super) fn status(body: &[u8]) -> Result<Status, WireError> {
+ let status: StatusIn = rmp_serde::from_slice(body)?;
+ let StampIn(heads) = rmp_serde::from_slice(&status.stamp)?;
+ Ok(Status {
+ heads,
+ epoch: status.epoch,
+ epoch_seq: status.epoch_seq,
+ ready: status.ready,
+ syncs_with_you: status.syncs_with_you,
+ leaving: status.leaving,
+ announcing: status.announcing,
+ reaches: status.reaches,
+ round_trips: status.round_trips,
+ })
+ }
+
+ /// The BLOB in `body`.
+ pub(super) fn blob(body: &[u8]) -> Result<ParsedMessage, WireError> {
+ let blob: Blob = rmp_serde::from_slice(body)?;
+ let body = match blob.body {
+ Body::Request { chunks, spec } => BlobBody::Request {
+ chunks,
+ delta: match spec {
+ Some(spec) => Some(rmp_serde::from_slice::<DeltaSpec>(&spec)?),
+ None => None,
+ },
+ },
+ Body::Manifest {
+ size,
+ chunk_size,
+ hashes,
+ } => BlobBody::Manifest {
+ size,
+ chunk_size,
+ hashes,
+ },
+ Body::Chunk { index, data } => BlobBody::Chunk { index, data },
+ Body::Missing => BlobBody::Missing,
+ Body::DeflatedChunk { index, data } => BlobBody::DeflatedChunk { index, data },
+ };
+ Ok(ParsedMessage::Blob(BlobMessage {
+ epoch: blob.epoch,
+ epoch_seq: blob.epoch_seq,
+ id: match blob.id {
+ Id::Unit(name) => BlobId::Change(crate::document::ChangeHash(name)),
+ Id::Content(hash) => BlobId::Content(hash),
+ Id::Bulk(name) => BlobId::Delta(name),
+ },
+ body,
+ sent: blob.sent,
+ }))
+ }
+}
+
/// The message in `payload` (as made by [`encode`]).
/// How many senders on another wire version are remembered as already logged
/// (`OtherVersions`).
@@ -267,11 +582,26 @@ pub(crate) fn decode(payload: &[u8]) -> Result<ParsedMessage, WireError> {
let (&kind, body) = payload.split_first().ok_or(WireError::Empty)?;
let is = |wanted: MessageKind| kind == tag(wanted);
let proof = version >= PROOFS && (is(MessageKind::Who) || is(MessageKind::Me));
- // Each older version this build still speaks is decoded here, into its own types,
- // once its messages differ from the newest's; this build's are the newest's alone.
+ // Each version this build speaks is decoded here: from `KINDS` on, the messages
+ // carrying what is a document's kind's as that version lays them out (`kinds`).
if !(OLDEST..=VERSION).contains(&version) && !proof {
return Err(WireError::Version(version));
}
+ if (KINDS..=VERSION).contains(&version) {
+ if is(MessageKind::Hello) {
+ return kinds::hello(body);
+ } else if is(MessageKind::HelloReply) {
+ return kinds::hello_reply(body);
+ } else if is(MessageKind::Sync) {
+ return kinds::sync(body);
+ } else if is(MessageKind::Status) {
+ return Ok(ParsedMessage::Status(kinds::status(body)?));
+ } else if is(MessageKind::StatusReply) {
+ return Ok(ParsedMessage::StatusReply(kinds::status(body)?));
+ } else if is(MessageKind::Blob) {
+ return kinds::blob(body);
+ }
+ }
Ok(if is(MessageKind::Hello) {
ParsedMessage::Hello(rmp_serde::from_slice(body)?)
} else if is(MessageKind::HelloReply) {
@@ -588,6 +918,7 @@ pub(crate) fn samples() -> Vec<ParsedMessage> {
handshake: 7,
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
}),
ParsedMessage::HelloReply(HelloReply {
swarm_id: "swarm".into(),
@@ -604,6 +935,7 @@ pub(crate) fn samples() -> Vec<ParsedMessage> {
sender_run_id: [6; 16],
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
}),
ParsedMessage::Sync(SyncEnvelope {
epoch: crate::transport::EpochTag::of(epoch),
@@ -771,7 +1103,10 @@ mod tests {
newer.contains(&format!("wire version {}", VERSION + 1)),
"{newer}"
);
- assert!(newer.contains(&format!("speaks {VERSION}")), "{newer}");
+ assert!(
+ newer.contains(&format!("speaks {OLDEST} to {VERSION}")),
+ "{newer}"
+ );
let older = other_build(OLDEST - 1, OLDEST - 1);
assert!(older.contains("upgrade that node"), "{older}");
let newer = other_build(VERSION + 1, VERSION + 3);
@@ -781,19 +1116,99 @@ mod tests {
);
}
- /// Every kind decodes to what was encoded: re-encoded, the same bytes.
+ /// Every kind decodes to what was encoded, in every version this build speaks:
+ /// re-encoded, the same bytes. And what one version carries, another carries too:
+ /// read from either, a message is written alike.
#[test]
fn every_kind_round_trips() {
let samples = samples();
assert_eq!(samples.len(), 18, "a kind is missing from `samples`");
for message in samples {
- let bytes = encode(&message).unwrap();
- let decoded = decode(&bytes).unwrap();
- assert_eq!(decoded.kind(), message.kind());
- assert_eq!(encode(&decoded).unwrap(), bytes, "{message:?}");
+ for version in OLDEST..=VERSION {
+ let bytes = encode_in(&message, version).unwrap();
+ let decoded = decode(&bytes).unwrap();
+ assert_eq!(decoded.kind(), message.kind());
+ assert_eq!(
+ encode_in(&decoded, version).unwrap(),
+ bytes,
+ "{version}: {message:?}"
+ );
+ for other in OLDEST..=VERSION {
+ assert_eq!(
+ encode_in(&decoded, other).unwrap(),
+ encode_in(&message, other).unwrap(),
+ "read in {version}, written in {other}: {message:?}"
+ );
+ }
+ }
}
}
+ /// A request for a blob of changes says which, in every version: as bytes from
+ /// `KINDS` on.
+ #[test]
+ fn a_blob_request_says_what_it_asks_for() {
+ let spec =
+ crate::transport::DeltaSpec::new(vec![ChangeHash([1; 32])], vec![ChangeHash([2; 32])]);
+ let request = ParsedMessage::Blob(BlobMessage {
+ epoch: Epoch::GENESIS,
+ epoch_seq: 0,
+ id: BlobId::Delta(spec.id()),
+ body: BlobBody::Request {
+ chunks: vec![0, 2],
+ delta: Some(spec.clone()),
+ },
+ sent: crate::clock::UnixMillis(2),
+ });
+ for version in OLDEST..=VERSION {
+ let decoded = decode(&encode_in(&request, version).unwrap()).unwrap();
+ let ParsedMessage::Blob(BlobMessage {
+ body: BlobBody::Request { chunks, delta },
+ ..
+ }) = decoded
+ else {
+ panic!("not a request");
+ };
+ assert_eq!(chunks, [0, 2]);
+ let delta = delta.expect("its spec");
+ assert_eq!((delta.from, delta.to), (spec.from.clone(), spec.to.clone()));
+ }
+ }
+
+ /// A handshake says its document's kind from `KINDS` on; one in an older version
+ /// says none, and is read as of the kind there was then.
+ #[test]
+ fn a_handshake_says_its_kind() {
+ let hello = |kind: &str| {
+ ParsedMessage::Hello(HelloRequest {
+ swarm_id: None,
+ epoch: Epoch::GENESIS,
+ epoch_seq: 0,
+ auth: Vec::new(),
+ ready: true,
+ run_id: [4; 16],
+ handshake: 1,
+ root: None,
+ party: None,
+ kind: kind.to_owned(),
+ })
+ };
+ let read = |message: &ParsedMessage, version: u8| match decode(
+ &encode_in(message, version).unwrap(),
+ )
+ .unwrap()
+ {
+ ParsedMessage::Hello(hello) => hello.kind,
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(read(&hello("another"), KINDS), "another");
+ assert_eq!(read(&hello("another"), KINDS - 1), crate::document::KIND);
+ assert_eq!(
+ read(&hello(crate::document::KIND), VERSION),
+ crate::document::KIND
+ );
+ }
+
#[test]
fn handshakes_round_trip() {
let epoch = Epoch {
@@ -810,6 +1225,7 @@ mod tests {
handshake: 7,
root: None,
party: Some("tv".into()),
+ kind: crate::document::KIND.to_owned(),
});
let ParsedMessage::Hello(decoded) = decode(&encode(&hello).unwrap()).unwrap() else {
panic!("not a HELLO");
@@ -836,6 +1252,7 @@ mod tests {
sender_run_id: [6; 16],
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
});
let ParsedMessage::HelloReply(decoded) = decode(&encode(&reply).unwrap()).unwrap() else {
panic!("not a HELLO_REPLY");
@@ -963,12 +1380,12 @@ mod tests {
assert!(decode(&[0, 50]).is_err());
}
- /// The exact bytes of a few messages. If this fails after a change to a message type
- /// or a codec, the change is a new wire format: bump `VERSION` and take the new bytes.
+ /// The exact bytes of a few messages, in the version before what is a kind's went
+ /// as bytes: as builds speaking it alone read and write them.
#[test]
fn golden_bytes() {
- // The version byte follows `VERSION`: bumped for a change to other messages.
- let v = format!("{VERSION:02x}");
+ // Of version 52, which this build still speaks: never to change.
+ let v = "34";
let epoch = Epoch {
generation: 2,
id: [3; 32],
@@ -986,9 +1403,10 @@ mod tests {
handshake: 7,
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
});
assert_eq!(
- hex(&encode(&hello).unwrap()),
+ hex(&encode_in(&hello, 52).unwrap()),
format!(
"{v}0099a5737761726d{epoch_hex}01c403010203c3{}07c0c0",
run("04")
@@ -1010,9 +1428,10 @@ mod tests {
sender_run_id: [6; 16],
root: None,
party: None,
+ kind: crate::document::KIND.to_owned(),
});
assert_eq!(
- hex(&encode(&reply).unwrap()),
+ hex(&encode_in(&reply, 52).unwrap()),
format!(
"{v}019ba5737761726d9192a17091a161{epoch_hex}01c400c2{}05{}c0c0",
run("04"),
@@ -1032,7 +1451,7 @@ mod tests {
round_trips: None,
});
assert_eq!(
- hex(&encode(&status).unwrap()),
+ hex(&encode_in(&status, 52).unwrap()),
format!("{v}03999290c400{epoch_hex}01c3c2c2c3c0c0")
);
@@ -1041,7 +1460,7 @@ mod tests {
signature: [9; 64],
});
assert_eq!(
- hex(&encode(&who).unwrap()),
+ hex(&encode_in(&who, 52).unwrap()),
format!("{v}0692c420{}c440{}", "08".repeat(32), "09".repeat(64))
);
let ParsedMessage::Me(proof) = decode(
@@ -1057,7 +1476,7 @@ mod tests {
assert_eq!((proof.key, proof.signature), ([8; 32], [9; 64]));
assert_eq!(
- hex(&encode(&ParsedMessage::Ping(7)).unwrap()),
+ hex(&encode_in(&ParsedMessage::Ping(7), 52).unwrap()),
format!("{v}0807")
);
let pong = ParsedMessage::Pong {
@@ -1065,7 +1484,7 @@ mod tests {
at: crate::clock::UnixMillis(5),
};
assert_eq!(
- hex(&encode(&pong).unwrap()),
+ hex(&encode_in(&pong, 52).unwrap()),
format!("{v}0992cfffffffffffffffff05")
);
let ParsedMessage::Pong { nonce, at } = decode(&[VERSION, 9, 0x92, 0x2a, 0x07]).unwrap()
@@ -1074,4 +1493,101 @@ mod tests {
};
assert_eq!((nonce, at.as_u64()), (42, 7));
}
+
+ /// The exact bytes of the messages that carry what is a document's kind's, from
+ /// `KINDS` on (`kinds`). If this fails after a change to a message type or a codec,
+ /// the change is a new wire format: bump `VERSION` and take the new bytes.
+ #[test]
+ fn golden_bytes_of_kinds() {
+ let epoch = Epoch {
+ generation: 2,
+ id: [3; 32],
+ };
+ let epoch_hex = format!("9202c420{}", "03".repeat(32));
+ let run = |byte: &str| format!("c410{}", byte.repeat(16));
+ let written = |message: &ParsedMessage| hex(&encode_in(message, KINDS).unwrap());
+
+ let hello = ParsedMessage::Hello(HelloRequest {
+ swarm_id: Some("swarm".into()),
+ epoch,
+ epoch_seq: 1,
+ auth: vec![1, 2, 3],
+ ready: true,
+ run_id: [4; 16],
+ handshake: 7,
+ root: None,
+ party: None,
+ kind: crate::document::KIND.to_owned(),
+ });
+ // The message as before, then the kind.
+ assert_eq!(
+ written(&hello),
+ format!(
+ "35009299a5737761726d{epoch_hex}01c403010203c3{}07c0c0a96175746f6d65726765",
+ run("04")
+ )
+ );
+
+ let status = ParsedMessage::Status(Status {
+ heads: HeadsSummary::Heads(vec![ChangeHash([1; 32])]),
+ epoch,
+ epoch_seq: 1,
+ ready: true,
+ syncs_with_you: false,
+ leaving: false,
+ announcing: true,
+ reaches: None,
+ round_trips: None,
+ });
+ // Where it stands as bytes: the heads listed, no digest.
+ assert_eq!(
+ written(&status),
+ format!(
+ "350399c4269291c420{}c400{epoch_hex}01c3c2c2c3c0c0",
+ "01".repeat(32)
+ )
+ );
+
+ let sync = ParsedMessage::Sync(crate::transport::SyncEnvelope {
+ epoch: crate::transport::EpochTag::of(epoch),
+ epoch_seq: 1,
+ body: crate::transport::SyncBody::Changes {
+ heads: vec![ChangeHash([2; 32])],
+ changes: vec![serde_bytes::ByteBuf::from(vec![5, 6])],
+ },
+ ready: true,
+ writer: Some(7),
+ delivered: true,
+ sent: crate::clock::UnixMillis(8),
+ signatures: serde_bytes::ByteBuf::from(vec![9; 3]),
+ });
+ assert_eq!(
+ written(&sync),
+ "3502979202c408030303030303030301c4349281a74368616e6765739291c420020202020202020202020202020202020202020202020202020202020202020291c4020506c3c30708c403090909"
+ );
+ assert_eq!(
+ hex(&encode_in(&sync, 52).unwrap()),
+ "3402989202c40803030303030303030181a74368616e6765739291c420020202020202020202020202020202020202020202020202020202020202020291c4020506c307c308c403090909"
+ );
+
+ let spec = crate::transport::DeltaSpec::new(Vec::new(), vec![ChangeHash([2; 32])]);
+ let request = ParsedMessage::Blob(BlobMessage {
+ epoch,
+ epoch_seq: 1,
+ id: BlobId::Delta([5; 32]),
+ body: BlobBody::Request {
+ chunks: vec![0],
+ delta: Some(spec),
+ },
+ sent: crate::clock::UnixMillis(9),
+ });
+ assert_eq!(
+ written(&request),
+ "3505959202c42003030303030303030303030303030303030303030303030303030303030303030181a442756c6bc420050505050505050505050505050505050505050505050505050505050505050581a752657175657374929100c426939091c4200202020202020202020202020202020202020202020202020202020202020202c009"
+ );
+ assert_eq!(
+ hex(&encode_in(&request, 52).unwrap()),
+ "3405959202c42003030303030303030303030303030303030303030303030303030303030303030181a544656c7461c420050505050505050505050505050505050505050505050505050505050505050581a752657175657374929100939091c4200202020202020202020202020202020202020202020202020202020202020202c009"
+ );
+ }
}