From a363c9958788dc648828410126f0f93c0c9bee5f Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 04:34:59 +0000 Subject: wire: version 53, what is the document's as bytes, and the kind in handshakes Spoken beside 52 (OLDEST), so a swarm upgrades node by node: a node writes each peer the newest version both speak. From 53 on (wire::KINDS, wire::kinds), what is a document's kind's goes as bytes the wire carries and doesn't read: a SYNC's body, with whether it is taken as delivered, and what vouches for what it carries; where a STATUS says its sender stands; what a BLOB request asks for in bulk; a BLOB is of a unit or of what is offered in bulk, by their names. Automerge's bytes are what 52 carries in the messages' own fields. HELLO and HELLO_REPLY say the kind of the sender's document (document::KIND, automerge) from 53 on; one in 52 says none and is of that kind. A peer whose document is of another kind is refused in the handshake, saying so. The bytes of 52 stay as golden_bytes has them; golden_bytes_of_kinds has those of 53. scripts/wire-check v0.0.1: its nodes and this tree's talk. --- CHANGELOG.md | 8 + docs/document.md | 41 ++-- docs/operations.md | 4 +- src/document/mod.rs | 4 + src/simtest/timing.rs | 2 + src/swarm/peer/handshake.rs | 2 + src/swarm/peer/inbound.rs | 14 ++ src/transport/mod.rs | 15 ++ src/transport/wire.rs | 586 +++++++++++++++++++++++++++++++++++++++++--- 9 files changed, 622 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8955431..2f363c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ it from the release before ([`docs/operations.md`](docs/operations.md), ## Unreleased +* Wire version 53, spoken beside 52, so a swarm upgrades node by node: what is the + document's of a message (a SYNC's body and what vouches for it, where a STATUS says the + sender stands, what a BLOB request asks for in bulk) goes as bytes the wire carries + without reading, and a handshake says the kind of the sender's document, of which there + is one, `automerge`; nodes of different kinds refuse each other there + ([`docs/document.md`](docs/document.md), [Passing on](docs/document.md#passing-on); + [`src/transport/wire.rs`](src/transport/wire.rs)). + * `+raw` (`file+raw:PATH`, `cmd+raw:COMMAND`, `env+raw:NAME`; `format = "raw"` in a file) imports a value as it is, the line breaks at its end kept ([`docs/configuration.md`](docs/configuration.md), diff --git a/docs/document.md b/docs/document.md index 77fa0bd..addc396 100644 --- a/docs/document.md +++ b/docs/document.md @@ -4,12 +4,14 @@ A design, built stage by stage ([Stages](#stages), below). So far: what is writt the node as it is; and of the second stage, what was the engine's in other modules on the engine's side (`document::own`, `dropping`, `screen`), the rules judging a unit at the state its writer saw (`access::rules::judge_seen`), values read and written -through a view any kind gives (`document::view`, `AppState::mutate_doc`), and what goes -to a peer next and what is made of what it sent on the document's side, as the wire -carries it now (`document::passing`). The node's document is an Automerge document, and -that is all it can be; this says what the rest of the node asks of it, which of that is -Automerge's shape and which is continuum's, and where the seam goes behind which a -swarm's document may be of another kind (a *kind* of document, a kind for short). +through a view any kind gives (`document::view`, `AppState::mutate_doc`), what goes to a +peer next and what is made of what it sent on the document's side +(`document::passing`), and a wire version in which what is a kind's is bytes, with the +kind said in handshakes (`transport::wire`, 53). The node's document is an Automerge +document, and that is all it can be; this says what the rest of the node asks of it, +which of that is Automerge's shape and which is continuum's, and where the seam goes +behind which a swarm's document may be of another kind (a *kind* of document, a kind for +short). Why: every write to an Automerge document is a change kept forever, and what Automerge does grows with their number, so a swarm takes no frequent writing; only a remake, which @@ -243,7 +245,10 @@ named where nodes meet, and nodes of different kinds refuse each other saying so ## Passing on -Not built: how a document of any kind is passed on, and what the wire carries of it. +How a document of any kind is passed on, and what the wire carries of it. Built: the +node asking Automerge's side for it (`document::passing`), and the wire version below. +Not built: the names above the seam as a kind's own in the node's memory, where a stamp, +a message's body and an offer in bulk are still Automerge's types. ### Whose it is @@ -292,25 +297,26 @@ rules (`access::rules::judge_seen`). ### On the wire -A wire version beside the one spoken now, in which what is a kind's is bytes: +Wire version 53, beside 52, in which what is a kind's is bytes (`transport::wire`, +`kinds`): -| Message | Now | Then | +| Message | In 52 | In 53 | |---|---|---| | SYNC | an Automerge sync message, or changes with heads, or a delta's heads; signatures of changes; `delivered` | the kind's bytes; what vouches, the kind's bytes | | STATUS | heads, or a digest and some of them | a stamp, the kind's bytes, no more than a keepalive may carry | | BLOB | a change by its hash, a delta by its heads, content by its hash | a unit by its name, something offered in bulk by its name with what the kind says of it, content by its hash | -| REFUSALS | changes by their hashes | units by their names | -| HELLO | the root's hash | the same, and the kind | +| REFUSALS | changes by their hashes | units by their names: the same bytes | +| HELLO | the root's hash | the same, and the kind (`document::KIND`) | What stays as it is: the epoch in every message, `ready`, the writer a push is along whose tree, when a message was sent, PRUNE and GRAFT, and everything that is no document's. -Automerge's bytes are what the version spoken now carries, so a node speaks both to its -peers as each can (`transport::wire`, versions side by side): a swarm of Automerge -documents upgrades node by node. A node that speaks the older version alone is of that -kind, and one of another kind tells it so, by the release that knows it, and syncs -nothing. +Automerge's bytes are what 52 carries in its messages' own fields, so a node speaks both +to its peers as each can (versions side by side): a swarm of Automerge documents +upgrades node by node. A node that speaks 52 alone says no kind, and is of the kind +there was then; nodes of different kinds refuse each other in the handshake, saying so, +and sync nothing. ### As merged state without a history would give it @@ -336,7 +342,8 @@ To see that what is asked isn't Automerge's in other words: a document or a transaction take a view to read or to write; passing on is asked of a kind ([Passing on](#passing-on)), first in the node, then on the wire; remakes become something a kind can do. Each step leaves the tests as they are. -3. **The kind named** where nodes meet, with one kind to name. +3. **The kind named** where nodes meet, with one kind to name: built, with the wire + version (`HelloRequest::kind`). 4. **Merged state without a history**, as a second kind, with what is written often as its test. 5. **A WireGuard mesh** as its first use: each node's key and where it is reached, diff --git a/docs/operations.md b/docs/operations.md index 027cb64..e99a914 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -120,7 +120,7 @@ too: each peer's, as far as the node heard, is its `knows` in `GET /peers`. ```sh continuum --version # continuum 0.0.1 -# wire versions 52 to 52 +# wire versions 52 to 53 # federation 1: the base revision, revision 1 (merge-events) # automerge 0.12.0 ``` @@ -141,7 +141,7 @@ A node upgrades by restarting with its files. What to know: Nodes sharing no version don't talk: the swarm is split until every node is upgraded, both sides go on writing, and they merge then. Each logs it, at warn, once per peer, naming both versions and the node to upgrade (`Peer speaks another wire version: a - newer build (wire version 54; this one speaks 52): upgrade this node to talk with it; + newer build (wire version 54; this one speaks 52 to 53): upgrade this node to talk with it; ignoring its messages`, or of an older build, `upgrade that node`). 0.0.1 logs `Peer speaks another wire version (another build); ignoring its messages`, with the peer's version and its own (`ours`): upgrade the node whose version is the lower. A 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, + /// 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>, /// As `HelloRequest::party`. pub(crate) party: Option, + /// 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 { /// 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, 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, 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, WireError> { Ok(payload) } +/// The payload of `message`, in the newest wire version. +#[cfg(test)] +pub(crate) fn encode(message: &ParsedMessage) -> Result, 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, + sent: UnixMillis, + #[serde(with = "serde_bytes")] + vouchers: &'a [u8], + } + + #[derive(Deserialize)] + struct SyncIn { + epoch: EpochTag, + epoch_seq: u32, + body: ByteBuf, + ready: bool, + writer: Option, + 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>, + #[serde(with = "serde_bytes")] + round_trips: &'a Option>, + } + + #[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>, + #[serde(with = "serde_bytes")] + round_trips: Option>, + } + + /// Where an Automerge document stands, as its bytes have it. + struct StampOut<'a>(&'a HeadsSummary); + + impl Serialize for StampOut<'_> { + fn serialize(&self, s: S) -> Result { + 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, + spec: Option, + }, + 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, message: &ParsedMessage) -> Result { + 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 { + 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 { + 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 { + 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 { + 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 { + 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::(&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 { 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 { 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 { 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" + ); + } } -- cgit v1.3.1