From fa21ea768825ee20eaa1fd35a2cbf13a0049ba65 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:13:51 +0200 Subject: [PATCH] Add horizon-protocol: the 26.3 network protocol (version 777) Primitive codecs (VarInt/VarLong, strings, positions, LpVec3, BitSets), VarInt21 framing, zlib threshold compression, AES/CFB8 encryption, MD5 offline UUIDs, network NBT via horizon-world, item stacks with data component patches, chunk and light payloads with paletted containers, synched entity data, and typed packets for every connection state in both directions with round-trip tests. Packet ids are generated from the data generator's packets report. The probe example logs into a vanilla 26.3 server and decoded ~8000 packets (329 chunks) without errors. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 9 + Cargo.toml | 2 +- crates/horizon-protocol/Cargo.toml | 12 + crates/horizon-protocol/examples/probe.rs | 218 ++++ crates/horizon-protocol/src/buf.rs | 686 ++++++++++ crates/horizon-protocol/src/chunk.rs | 391 ++++++ crates/horizon-protocol/src/connection.rs | 183 +++ crates/horizon-protocol/src/crypto.rs | 275 ++++ crates/horizon-protocol/src/entity_data.rs | 189 +++ crates/horizon-protocol/src/frame.rs | 155 +++ crates/horizon-protocol/src/ids.rs | 590 +++++++++ crates/horizon-protocol/src/item.rs | 337 +++++ crates/horizon-protocol/src/lib.rs | 58 + .../src/packets/configuration.rs | 226 ++++ .../horizon-protocol/src/packets/handshake.rs | 39 + crates/horizon-protocol/src/packets/login.rs | 134 ++ crates/horizon-protocol/src/packets/mod.rs | 86 ++ crates/horizon-protocol/src/packets/play.rs | 1136 +++++++++++++++++ crates/horizon-protocol/src/packets/status.rs | 50 + crates/horizon-protocol/src/registry.rs | 221 ++++ crates/horizon-protocol/src/servers.rs | 149 +++ crates/horizon-protocol/src/text.rs | 190 +++ tools/generate_packet_ids.py | 70 + 23 files changed, 5405 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-protocol/Cargo.toml create mode 100644 crates/horizon-protocol/examples/probe.rs create mode 100644 crates/horizon-protocol/src/buf.rs create mode 100644 crates/horizon-protocol/src/chunk.rs create mode 100644 crates/horizon-protocol/src/connection.rs create mode 100644 crates/horizon-protocol/src/crypto.rs create mode 100644 crates/horizon-protocol/src/entity_data.rs create mode 100644 crates/horizon-protocol/src/frame.rs create mode 100644 crates/horizon-protocol/src/ids.rs create mode 100644 crates/horizon-protocol/src/item.rs create mode 100644 crates/horizon-protocol/src/lib.rs create mode 100644 crates/horizon-protocol/src/packets/configuration.rs create mode 100644 crates/horizon-protocol/src/packets/handshake.rs create mode 100644 crates/horizon-protocol/src/packets/login.rs create mode 100644 crates/horizon-protocol/src/packets/mod.rs create mode 100644 crates/horizon-protocol/src/packets/play.rs create mode 100644 crates/horizon-protocol/src/packets/status.rs create mode 100644 crates/horizon-protocol/src/registry.rs create mode 100644 crates/horizon-protocol/src/servers.rs create mode 100644 crates/horizon-protocol/src/text.rs create mode 100644 tools/generate_packet_ids.py diff --git a/Cargo.lock b/Cargo.lock index 8eadbf02a..e797c77a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -698,6 +698,15 @@ dependencies = [ name = "horizon-core" version = "0.1.0" +[[package]] +name = "horizon-protocol" +version = "0.1.0" +dependencies = [ + "flate2", + "horizon-world", + "serde_json", +] + [[package]] name = "horizon-world" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index aca7bb21d..e58b4f001 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets"] +members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol"] resolver = "2" [workspace.package] diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml new file mode 100644 index 000000000..0875a7bc4 --- /dev/null +++ b/crates/horizon-protocol/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "horizon-protocol" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 777)" + +[dependencies] +horizon-world = { path = "../horizon-world" } +flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +serde_json = "1.0.151" diff --git a/crates/horizon-protocol/examples/probe.rs b/crates/horizon-protocol/examples/probe.rs new file mode 100644 index 000000000..241e3affe --- /dev/null +++ b/crates/horizon-protocol/examples/probe.rs @@ -0,0 +1,218 @@ +//! Log into a server in offline mode and decode everything it sends for a few +//! seconds, reporting packet counts and any decode failures. A differential +//! check of the codecs against a real vanilla server: +//! +//! cargo run -p horizon-protocol --example probe -- 127.0.0.1:25565 [seconds] [registries.json] +use horizon_protocol::{ + PROTOCOL_VERSION, State, + connection::Connection, + ids, + packets::{Empty, configuration as cfg, handshake, login, play}, + registry::{Builtin, Dynamic, ceil_log2}, + servers::parse_address, +}; +use std::{ + collections::BTreeMap, + time::{Duration, Instant}, +}; + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let (host, port) = + parse_address(args.get(1).map_or("127.0.0.1", String::as_str)).ok_or("bad address")?; + let seconds: u64 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(10); + let builtin = args + .get(3) + .map(|p| Builtin::load(std::path::Path::new(p))) + .transpose()?; + let mut c = Connection::connect(&host, port, Duration::from_secs(5))?; + c.send( + &handshake::Serverbound::Intention(handshake::Intention { + protocol: PROTOCOL_VERSION, + host: host.clone(), + port, + intent: handshake::LOGIN, + }) + .encode(), + )?; + let name = "HorizonProbe"; + c.send( + &login::Serverbound::Hello(login::ServerHello { + name: name.into(), + uuid: horizon_protocol::crypto::offline_uuid(name), + }) + .encode(), + )?; + loop { + let (id, payload) = c.recv()?; + match login::Clientbound::decode(id, &payload)? { + login::Clientbound::Compression(p) => c.set_compression(p.threshold), + login::Clientbound::LoginFinished(p) => { + println!( + "logged in as {} {}", + p.profile.name, + horizon_protocol::crypto::uuid_string(p.profile.uuid) + ); + c.send(&login::Serverbound::LoginAcknowledged(Empty).encode())?; + break; + } + login::Clientbound::Disconnect(p) => return Err(p.reason_json.into()), + other => println!("login: {other:?}"), + } + } + c.send(&cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(8)).encode())?; + let mut registries = Dynamic::default(); + loop { + let (id, payload) = c.recv()?; + match cfg::Clientbound::decode(id, &payload) { + Ok(cfg::Clientbound::SelectKnownPacks(p)) => { + println!("known packs offered: {:?}", p.packs); + c.send( + &cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: vec![] }) + .encode(), + )?; + } + Ok(cfg::Clientbound::RegistryData(p)) => { + println!("registry {} ({} entries)", p.registry, p.entries.len()); + registries.add(p); + } + Ok(cfg::Clientbound::KeepAlive(p)) => { + c.send(&cfg::Serverbound::KeepAlive(p).encode())? + } + Ok(cfg::Clientbound::Ping(p)) => c.send(&cfg::Serverbound::Pong(p).encode())?, + Ok(cfg::Clientbound::CodeOfConduct(_)) => { + c.send(&cfg::Serverbound::AcceptCodeOfConduct(Empty).encode())? + } + Ok(cfg::Clientbound::FinishConfiguration(_)) => { + c.send(&cfg::Serverbound::FinishConfiguration(Empty).encode())?; + break; + } + Ok(cfg::Clientbound::Disconnect(p)) => return Err(format!("{:?}", p.reason).into()), + Ok(cfg::Clientbound::UpdateTags(p)) => { + println!("tags for {} registries", p.registries.len()) + } + Ok(other) => println!( + "configuration: {}", + ids::name( + State::Configuration, + horizon_protocol::Direction::Clientbound, + other.id() + ) + .unwrap_or("?") + ), + Err(e) => println!("configuration decode error in {id}: {e}"), + } + } + let biome_bits = ceil_log2(registries.len("minecraft:worldgen/biome")); + let mut counts: BTreeMap<&str, (u32, u32)> = BTreeMap::new(); + let mut dimension = registries.dimension(0); + let start = Instant::now(); + c.reader + .set_read_timeout(Some(Duration::from_millis(500)))?; + let mut ticks = 0; + while start.elapsed() < Duration::from_secs(seconds) { + let (id, payload) = match c.recv() { + Ok(p) => p, + Err(e) if e.0.contains("timed out") || e.0.contains("temporarily unavailable") => { + continue; + } + Err(e) => return Err(e.into()), + }; + let name = + ids::name(State::Play, horizon_protocol::Direction::Clientbound, id).unwrap_or("?"); + let entry = counts.entry(name).or_default(); + entry.0 += 1; + match play::Clientbound::decode(id, &payload) { + Ok(packet) => match packet { + play::Clientbound::Login(p) => { + dimension = registries.dimension(p.spawn.dimension_type); + println!( + "login: entity {} in {} ({:?})", + p.player_id, p.spawn.dimension, dimension + ); + c.send(&play::Serverbound::PlayerLoaded(Empty).encode())?; + } + play::Clientbound::KeepAlive(p) => { + c.send(&play::Serverbound::KeepAlive(p).encode())? + } + play::Clientbound::Ping(p) => c.send(&play::Serverbound::Pong(p).encode())?, + play::Clientbound::PlayerPosition(p) => { + println!("position {:?} teleport {}", p.position, p.teleport); + let [x, y, z] = p.position; + c.send( + &play::Serverbound::AcceptTeleportation(play::AcceptTeleportation { + id: p.teleport, + x, + y, + z, + yaw: p.yaw, + pitch: p.pitch, + }) + .encode(), + )?; + c.send( + &play::Serverbound::MovePlayerPosRot(play::MovePlayerPosRot { + x, + y, + z, + yaw: p.yaw, + pitch: p.pitch, + flags: 0, + }) + .encode(), + )?; + } + play::Clientbound::ChunkBatchFinished(_) => { + c.send( + &play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: 50.0, + }) + .encode(), + )?; + ticks += 1; + } + play::Clientbound::LevelChunkWithLight(p) => { + if let Err(e) = p.chunk.sections(dimension.sections(), 16, biome_bits) { + println!("chunk {} {} sections: {e}", p.x, p.z); + entry.1 += 1; + } + } + play::Clientbound::AddEntity(p) => { + let kind = builtin + .as_ref() + .and_then(|b| b.get("minecraft:entity_type")?.name(p.kind)) + .unwrap_or("?"); + if counts.get("add_entity").is_some_and(|c| c.0 < 4) { + println!("entity {} {kind} at {:?}", p.id, p.position); + } + } + play::Clientbound::SystemChat(p) => println!( + "chat: {}", + horizon_protocol::text::plain(&p.content, &Default::default()) + ), + play::Clientbound::Disconnect(p) => { + return Err(format!("disconnected: {:?}", p.reason).into()); + } + _ => {} + }, + Err(e) => { + entry.1 += 1; + if entry.1 <= 2 { + println!("decode error in {name} ({} bytes): {e}", payload.len()); + } + } + } + } + println!("{ticks} chunk batches"); + for (name, (n, errors)) in counts { + println!( + "{name:32} {n:6} {}", + if errors > 0 { + format!("{errors} ERRORS") + } else { + String::new() + } + ); + } + Ok(()) +} diff --git a/crates/horizon-protocol/src/buf.rs b/crates/horizon-protocol/src/buf.rs new file mode 100644 index 000000000..d937ff8b9 --- /dev/null +++ b/crates/horizon-protocol/src/buf.rs @@ -0,0 +1,686 @@ +//! Byte buffers with vanilla's primitive encodings (FriendlyByteBuf, VarInt, +//! VarLong, ByteBufCodecs) and the `Codec` building blocks packets are +//! composed from, mirroring `StreamCodec.composite`. +use crate::{Error, Result}; +use horizon_world::nbt::{self, Tag}; +use std::marker::PhantomData; + +/// Vanilla's default NBT quota for network tags (NbtAccounter.defaultQuota). +pub const NBT_QUOTA: usize = 2_097_152; + +/// A cursor over a received packet body. +pub struct Reader<'a> { + data: &'a [u8], + pos: usize, +} +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + pub fn remaining(&self) -> usize { + self.data.len() - self.pos + } + pub fn position(&self) -> usize { + self.pos + } + pub fn rest(&mut self) -> &'a [u8] { + let rest = &self.data[self.pos..]; + self.pos = self.data.len(); + rest + } + pub fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { + if self.remaining() < n { + return Err(Error::new(format!( + "needed {n} bytes, {} left", + self.remaining() + ))); + } + let out = &self.data[self.pos..self.pos + n]; + self.pos += n; + Ok(out) + } + fn array(&mut self) -> Result<[u8; N]> { + Ok(self.bytes(N)?.try_into().expect("length checked")) + } + pub fn u8(&mut self) -> Result { + Ok(self.array::<1>()?[0]) + } + pub fn i8(&mut self) -> Result { + Ok(self.u8()? as i8) + } + pub fn bool(&mut self) -> Result { + Ok(self.u8()? != 0) + } + pub fn i16(&mut self) -> Result { + Ok(i16::from_be_bytes(self.array()?)) + } + pub fn u16(&mut self) -> Result { + Ok(u16::from_be_bytes(self.array()?)) + } + pub fn i32(&mut self) -> Result { + Ok(i32::from_be_bytes(self.array()?)) + } + pub fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes(self.array()?)) + } + pub fn i64(&mut self) -> Result { + Ok(i64::from_be_bytes(self.array()?)) + } + pub fn f32(&mut self) -> Result { + Ok(f32::from_be_bytes(self.array()?)) + } + pub fn f64(&mut self) -> Result { + Ok(f64::from_be_bytes(self.array()?)) + } + /// VarInt.read: at most five 7-bit groups, least significant first. + pub fn varint(&mut self) -> Result { + let mut value = 0u32; + for i in 0..5 { + let b = self.u8()?; + value |= u32::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + return Ok(value as i32); + } + } + Err(Error::new("VarInt too big")) + } + /// VarLong.read: at most ten 7-bit groups. + pub fn varlong(&mut self) -> Result { + let mut value = 0u64; + for i in 0..10 { + let b = self.u8()?; + value |= u64::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + return Ok(value as i64); + } + } + Err(Error::new("VarLong too big")) + } + /// A VarInt count that must fit in what is left (ByteBufCodecs.readCount). + pub fn count(&mut self, max: usize) -> Result { + let n = self.varint()?; + let n = usize::try_from(n).map_err(|_| Error::new(format!("negative count {n}")))?; + if n > max { + return Err(Error::new(format!( + "{n} elements is more than allowed {max}" + ))); + } + Ok(n) + } + /// Utf8String.read: VarInt byte length, UTF-8, at most `max` chars. + pub fn string(&mut self, max: usize) -> Result { + let len = self.count(max.saturating_mul(3))?; + let s = std::str::from_utf8(self.bytes(len)?) + .map_err(|e| Error::new(format!("bad UTF-8: {e}")))?; + if s.chars().count() > max { + return Err(Error::new(format!("string longer than {max} chars"))); + } + Ok(s.to_owned()) + } + pub fn byte_array(&mut self, max: usize) -> Result> { + let len = self.count(max)?; + Ok(self.bytes(len)?.to_vec()) + } + pub fn uuid(&mut self) -> Result { + Ok(u128::from_be_bytes(self.array()?)) + } + /// A network NBT tag (NbtIo.readAnyTag without a root name); `End` means none. + pub fn nbt(&mut self) -> Result { + let limits = nbt::Limits { + max_bytes: NBT_QUOTA, + ..nbt::Limits::default() + }; + let (tag, used) = nbt::read_network(&self.data[self.pos..], limits) + .map_err(|e| Error::new(format!("NBT: {e}")))?; + self.pos += used; + Ok(tag) + } + pub fn long_array(&mut self) -> Result> { + let n = self.count(self.remaining() / 8)?; + (0..n).map(|_| self.i64()).collect() + } + pub fn fixed_longs(&mut self, n: usize) -> Result> { + if self.remaining() < n * 8 { + return Err(Error::new("fixed long array past the end")); + } + (0..n).map(|_| self.i64()).collect() + } +} + +/// An outgoing packet body. +#[derive(Default)] +pub struct Writer { + pub data: Vec, +} +impl Writer { + pub fn new() -> Self { + Self::default() + } + pub fn u8(&mut self, v: u8) { + self.data.push(v); + } + pub fn i8(&mut self, v: i8) { + self.data.push(v as u8); + } + pub fn bool(&mut self, v: bool) { + self.data.push(u8::from(v)); + } + pub fn i16(&mut self, v: i16) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn u16(&mut self, v: u16) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn i32(&mut self, v: i32) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn u32(&mut self, v: u32) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn i64(&mut self, v: i64) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn f32(&mut self, v: f32) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn f64(&mut self, v: f64) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn varint(&mut self, v: i32) { + write_varint(&mut self.data, v); + } + pub fn varlong(&mut self, v: i64) { + let mut v = v as u64; + loop { + if v & !0x7F == 0 { + self.data.push(v as u8); + return; + } + self.data.push((v as u8 & 0x7F) | 0x80); + v >>= 7; + } + } + pub fn string(&mut self, s: &str) { + self.varint(s.len() as i32); + self.data.extend_from_slice(s.as_bytes()); + } + pub fn byte_array(&mut self, b: &[u8]) { + self.varint(b.len() as i32); + self.data.extend_from_slice(b); + } + pub fn bytes(&mut self, b: &[u8]) { + self.data.extend_from_slice(b); + } + pub fn uuid(&mut self, v: u128) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn nbt(&mut self, tag: &Tag) { + match nbt::write_network(tag, nbt::Limits::default()) { + Ok(bytes) => self.data.extend_from_slice(&bytes), + // Unencodable tags (too deep) are sent as "no tag". + Err(_) => self.data.push(0), + } + } + pub fn long_array(&mut self, v: &[i64]) { + self.varint(v.len() as i32); + for &l in v { + self.i64(l); + } + } +} +pub fn write_varint(out: &mut Vec, v: i32) { + let mut v = v as u32; + loop { + if v & !0x7F == 0 { + out.push(v as u8); + return; + } + out.push((v as u8 & 0x7F) | 0x80); + v >>= 7; + } +} +pub fn varint_size(v: i32) -> usize { + let v = v as u32; + (1..5).find(|i| v >> (7 * i) == 0).unwrap_or(5) +} + +/// A wire encoding for values of type `T` (vanilla's StreamCodec). +pub trait Codec { + fn read(r: &mut Reader) -> Result; + fn write(v: &T, w: &mut Writer); +} +macro_rules! primitive { + ($name:ident, $ty:ty, $read:ident, $write:ident) => { + pub struct $name; + impl Codec<$ty> for $name { + fn read(r: &mut Reader) -> Result<$ty> { + r.$read() + } + fn write(v: &$ty, w: &mut Writer) { + w.$write(*v) + } + } + }; +} +primitive!(Bool, bool, bool, bool); +primitive!(Byte, i8, i8, i8); +primitive!(UByte, u8, u8, u8); +primitive!(Short, i16, i16, i16); +primitive!(UShort, u16, u16, u16); +primitive!(Int, i32, i32, i32); +primitive!(Long, i64, i64, i64); +primitive!(Float, f32, f32, f32); +primitive!(Double, f64, f64, f64); +primitive!(VarInt, i32, varint, varint); +primitive!(VarLong, i64, varlong, varlong); +primitive!(Uuid, u128, uuid, uuid); + +/// ByteBufCodecs.STRING_UTF8 (32767 chars). +pub struct Str; +impl Codec for Str { + fn read(r: &mut Reader) -> Result { + r.string(32767) + } + fn write(v: &String, w: &mut Writer) { + w.string(v) + } +} +/// A string with a smaller vanilla limit, e.g. player names (16). +pub struct StrN; +impl Codec for StrN { + fn read(r: &mut Reader) -> Result { + r.string(N) + } + fn write(v: &String, w: &mut Writer) { + w.string(v) + } +} +/// Identifier.STREAM_CODEC: a resource location string. +pub type Ident = StrN<32767>; +/// VarInt-prefixed bytes. +pub struct Bytes; +impl Codec> for Bytes { + fn read(r: &mut Reader) -> Result> { + r.byte_array(r.remaining()) + } + fn write(v: &Vec, w: &mut Writer) { + w.byte_array(v) + } +} +/// Everything left in the packet (custom payloads). +pub struct Rest; +impl Codec> for Rest { + fn read(r: &mut Reader) -> Result> { + Ok(r.rest().to_vec()) + } + fn write(v: &Vec, w: &mut Writer) { + w.bytes(v) + } +} +/// Any network NBT tag (`Tag::End` when absent). +pub struct Nbt; +impl Codec for Nbt { + fn read(r: &mut Reader) -> Result { + r.nbt() + } + fn write(v: &Tag, w: &mut Writer) { + w.nbt(v) + } +} +/// ByteBufCodecs.LONG_ARRAY. +pub struct Longs; +impl Codec> for Longs { + fn read(r: &mut Reader) -> Result> { + r.long_array() + } + fn write(v: &Vec, w: &mut Writer) { + w.long_array(v) + } +} +/// ByteBufCodecs.list(): VarInt count then elements. +pub struct List(PhantomData); +impl> Codec> for List { + fn read(r: &mut Reader) -> Result> { + let n = r.count(r.remaining())?; + (0..n).map(|_| C::read(r)).collect() + } + fn write(v: &Vec, w: &mut Writer) { + w.varint(v.len() as i32); + for e in v { + C::write(e, w); + } + } +} +/// ByteBufCodecs.optional(): a boolean presence flag. +pub struct Opt(PhantomData); +impl> Codec> for Opt { + fn read(r: &mut Reader) -> Result> { + if r.bool()? { + Ok(Some(C::read(r)?)) + } else { + Ok(None) + } + } + fn write(v: &Option, w: &mut Writer) { + w.bool(v.is_some()); + if let Some(v) = v { + C::write(v, w); + } + } +} +/// ByteBufCodecs.OPTIONAL_VAR_INT: 0 = empty, otherwise value + 1. +pub struct OptVarInt; +impl Codec> for OptVarInt { + fn read(r: &mut Reader) -> Result> { + let v = r.varint()?; + Ok(if v == 0 { None } else { Some(v - 1) }) + } + fn write(v: &Option, w: &mut Writer) { + w.varint(v.map_or(0, |v| v + 1)) + } +} +/// Vec3.STREAM_CODEC: three doubles. +pub struct Vec3d; +impl Codec<[f64; 3]> for Vec3d { + fn read(r: &mut Reader) -> Result<[f64; 3]> { + Ok([r.f64()?, r.f64()?, r.f64()?]) + } + fn write(v: &[f64; 3], w: &mut Writer) { + for c in v { + w.f64(*c); + } + } +} +/// BlockPos.STREAM_CODEC: x (26 bits), z (26 bits), y (12 bits) in one long. +pub struct Pos; +impl Codec<[i32; 3]> for Pos { + fn read(r: &mut Reader) -> Result<[i32; 3]> { + Ok(unpack_block_pos(r.i64()?)) + } + fn write(v: &[i32; 3], w: &mut Writer) { + w.i64(pack_block_pos(*v)) + } +} +pub fn pack_block_pos(p: [i32; 3]) -> i64 { + ((i64::from(p[0]) & 0x3FF_FFFF) << 38) + | ((i64::from(p[2]) & 0x3FF_FFFF) << 12) + | (i64::from(p[1]) & 0xFFF) +} +pub fn unpack_block_pos(v: i64) -> [i32; 3] { + [ + (v >> 38) as i32, + (v << 52 >> 52) as i32, + (v << 26 >> 38) as i32, + ] +} +/// ChunkPos packed as x in the low and z in the high 32 bits. +pub struct ChunkPos; +impl Codec<[i32; 2]> for ChunkPos { + fn read(r: &mut Reader) -> Result<[i32; 2]> { + let v = r.i64()?; + Ok([v as i32, (v >> 32) as i32]) + } + fn write(v: &[i32; 2], w: &mut Writer) { + w.i64((i64::from(v[0]) & 0xFFFF_FFFF) | (i64::from(v[1]) << 32)) + } +} +/// SectionPos: x (22 bits), z (22 bits), y (20 bits). +pub struct SectionPos; +impl Codec<[i32; 3]> for SectionPos { + fn read(r: &mut Reader) -> Result<[i32; 3]> { + let v = r.i64()?; + Ok([ + (v >> 42) as i32, + (v << 44 >> 44) as i32, + (v << 22 >> 42) as i32, + ]) + } + fn write(v: &[i32; 3], w: &mut Writer) { + w.i64( + ((i64::from(v[0]) & 0x3F_FFFF) << 42) + | ((i64::from(v[2]) & 0x3F_FFFF) << 20) + | (i64::from(v[1]) & 0xF_FFFF), + ) + } +} +/// ByteBufCodecs.BIT_SET: java.util.BitSet as a VarInt-prefixed byte array. +pub struct BitSet; +impl Codec> for BitSet { + fn read(r: &mut Reader) -> Result> { + r.byte_array(r.remaining()) + } + fn write(v: &Vec, w: &mut Writer) { + // BitSet.toByteArray drops trailing zero bytes. + let len = v.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + w.byte_array(&v[..len]) + } +} +pub fn bit(set: &[u8], i: usize) -> bool { + set.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0) +} +pub fn set_bit(set: &mut Vec, i: usize) { + if set.len() <= i / 8 { + set.resize(i / 8 + 1, 0); + } + set[i / 8] |= 1 << (i % 8); +} +/// LpVec3: a low-precision velocity (Vec3.LP_STREAM_CODEC). +pub struct LpVec3; +impl LpVec3 { + fn unpack(v: u64) -> f64 { + ((v & 32767) as f64).min(32766.0) * 2.0 / 32766.0 - 1.0 + } + fn pack(v: f64) -> u64 { + ((v * 0.5 + 0.5) * 32766.0).round() as u64 + } + fn sanitize(v: f64) -> f64 { + if v.is_nan() { + 0.0 + } else { + v.clamp(-1.717_986_918_3e10, 1.717_986_918_3e10) + } + } +} +impl Codec<[f64; 3]> for LpVec3 { + fn read(r: &mut Reader) -> Result<[f64; 3]> { + let lowest = u64::from(r.u8()?); + if lowest == 0 { + return Ok([0.0; 3]); + } + let middle = u64::from(r.u8()?); + let highest = u64::from(r.u32()?); + let buffer = highest << 16 | middle << 8 | lowest; + let mut scale = lowest & 3; + if lowest & 4 == 4 { + scale |= (u64::from(r.varint()? as u32)) << 2; + } + let s = scale as f64; + Ok([ + Self::unpack(buffer >> 3) * s, + Self::unpack(buffer >> 18) * s, + Self::unpack(buffer >> 33) * s, + ]) + } + fn write(v: &[f64; 3], w: &mut Writer) { + let [x, y, z] = v.map(Self::sanitize); + let length = x.abs().max(y.abs()).max(z.abs()); + if length < 3.051_944_088_384_301e-5 { + w.u8(0); + return; + } + let scale = length.ceil() as u64; + let partial = scale & 3 != scale; + let markers = if partial { scale & 3 | 4 } else { scale }; + let s = scale as f64; + let buffer = + markers | Self::pack(x / s) << 3 | Self::pack(y / s) << 18 | Self::pack(z / s) << 33; + w.u8(buffer as u8); + w.u8((buffer >> 8) as u8); + w.i32((buffer >> 16) as i32); + if partial { + w.varint((scale >> 2) as i32); + } + } +} +/// A degree angle sent as a byte (Mth.packDegrees / unpackDegrees). +pub fn pack_degrees(deg: f32) -> i8 { + (deg * 256.0 / 360.0).floor() as i32 as i8 +} +pub fn unpack_degrees(b: i8) -> f32 { + f32::from(b) * 360.0 / 256.0 +} + +/// Define a packet struct and its codec from (field: type => codec) triples, +/// like vanilla's `StreamCodec.composite`. +#[macro_export] +macro_rules! packet { + ($(#[$meta:meta])* $name:ident { $($field:ident : $ty:ty => $codec:ty),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name { + $(pub $field: $ty),* + } + impl $crate::buf::Codec<$name> for $name { + #[allow(unused_variables)] + fn read(r: &mut $crate::buf::Reader) -> $crate::Result<$name> { + Ok($name { $($field: <$codec as $crate::buf::Codec<$ty>>::read(r)?),* }) + } + #[allow(unused_variables)] + fn write(v: &$name, w: &mut $crate::buf::Writer) { + $(<$codec as $crate::buf::Codec<$ty>>::write(&v.$field, w);)* + } + } + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + fn round>(v: T) -> Vec { + let mut w = Writer::new(); + C::write(&v, &mut w); + let mut r = Reader::new(&w.data); + assert_eq!(C::read(&mut r).unwrap(), v); + assert_eq!(r.remaining(), 0); + w.data + } + + #[test] + fn varint_matches_vanilla_examples() { + // wiki.vg / VarInt.java examples. + assert_eq!(round::(0), [0x00]); + assert_eq!(round::(1), [0x01]); + assert_eq!(round::(127), [0x7f]); + assert_eq!(round::(128), [0x80, 0x01]); + assert_eq!(round::(255), [0xff, 0x01]); + assert_eq!(round::(25565), [0xdd, 0xc7, 0x01]); + assert_eq!(round::(2097151), [0xff, 0xff, 0x7f]); + assert_eq!( + round::(i32::MAX), + [0xff, 0xff, 0xff, 0xff, 0x07] + ); + assert_eq!(round::(-1), [0xff, 0xff, 0xff, 0xff, 0x0f]); + assert_eq!( + round::(i32::MIN), + [0x80, 0x80, 0x80, 0x80, 0x08] + ); + for v in [0, 1, 127, 128, 16383, 16384, 2097151, 2097152, i32::MAX, -1] { + assert_eq!(varint_size(v), round::(v).len()); + } + assert!(Reader::new(&[0xff; 6]).varint().is_err()); + } + + #[test] + fn varlong_matches_vanilla_examples() { + assert_eq!(round::(0), [0x00]); + assert_eq!( + round::(2147483647), + [0xff, 0xff, 0xff, 0xff, 0x07] + ); + assert_eq!( + round::(i64::MAX), + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f] + ); + assert_eq!( + round::(-1), + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01] + ); + assert_eq!( + round::(i64::MIN), + [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01] + ); + } + + #[test] + fn strings_positions_and_options() { + assert_eq!(round::("héllo".into()), b"\x06h\xc3\xa9llo"); + let mut w = Writer::new(); + w.string("seventeen chars!!"); + assert!(Reader::new(&w.data).string(16).is_err()); + for p in [ + [0, 0, 0], + [-1, -64, -1], + [33_554_431, 2047, -33_554_432], + [123, -2048, -456], + ] { + round::<[i32; 3], Pos>(p); + assert_eq!(unpack_block_pos(pack_block_pos(p)), p); + } + // BlockPos.asLong(1, 2, 3) + assert_eq!(pack_block_pos([1, 2, 3]), (1 << 38) | (3 << 12) | 2); + round::<[i32; 3], SectionPos>([-5, -4, 1_000]); + round::<[i32; 2], ChunkPos>([-7, 12]); + round::, Opt>(Some("x".into())); + round::, Opt>(None); + round::, OptVarInt>(Some(0)); + round::, List>(vec![1, 300, -1]); + round::(0x0123_4567_89ab_cdef_0011_2233_4455_6677); + } + + #[test] + fn bitset_drops_trailing_zero_bytes() { + let mut set = vec![0u8; 4]; + set_bit(&mut set, 3); + set_bit(&mut set, 9); + let mut w = Writer::new(); + BitSet::write(&set, &mut w); + assert_eq!(w.data, [2, 0b1000, 0b10]); + let read = BitSet::read(&mut Reader::new(&w.data)).unwrap(); + assert!(bit(&read, 3) && bit(&read, 9) && !bit(&read, 4) && !bit(&read, 100)); + } + + #[test] + fn lp_vec3_round_trips_within_precision() { + for v in [ + [0.0, 0.0, 0.0], + [0.1, -0.2, 0.3], + [1.5, -3.25, 0.0], + [12.0, 0.0, -40.5], + [0.0, -3.92, 0.0], + ] { + let mut w = Writer::new(); + LpVec3::write(&v, &mut w); + let back = LpVec3::read(&mut Reader::new(&w.data)).unwrap(); + let scale = v.iter().fold(0.0f64, |m, c| m.max(c.abs())).ceil().max(1.0); + for i in 0..3 { + assert!( + (back[i] - v[i]).abs() <= scale / 32766.0 * 1.01, + "{v:?} -> {back:?}" + ); + } + } + // Zero is a single byte. + let mut w = Writer::new(); + LpVec3::write(&[0.0, 1e-9, 0.0], &mut w); + assert_eq!(w.data, [0]); + } + + #[test] + fn angles_pack_like_mth() { + assert_eq!(pack_degrees(90.0), 64); + assert_eq!(pack_degrees(-90.0), -64); + assert_eq!(pack_degrees(180.0), -128); + assert_eq!(unpack_degrees(64), 90.0); + } +} diff --git a/crates/horizon-protocol/src/chunk.rs b/crates/horizon-protocol/src/chunk.rs new file mode 100644 index 000000000..343f7c7aa --- /dev/null +++ b/crates/horizon-protocol/src/chunk.rs @@ -0,0 +1,391 @@ +//! Chunk column payloads: ClientboundLevelChunkPacketData (heightmaps, the +//! serialized LevelChunkSections with their PalettedContainers, block +//! entities) and ClientboundLightUpdatePacketData (sky/block DataLayers). +use crate::{ + Result, + buf::{BitSet, Bytes, Codec, Longs, Reader, VarInt, Writer}, + packet, +}; +use horizon_world::nbt::Tag; + +/// Blocks: 16^3 entries; biomes: 4^3 entries per section. +pub const BLOCKS: usize = 4096; +pub const BIOMES: usize = 64; + +/// Which palette Strategy a container uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Strategy { + /// Strategy.createForBlockStates. + Blocks, + /// Strategy.createForBiomes. + Biomes, +} +impl Strategy { + fn entries(self) -> usize { + match self { + Self::Blocks => BLOCKS, + Self::Biomes => BIOMES, + } + } + /// getConfigurationForBitCount: (uses a palette, bits in storage). + fn configuration(self, bits: u8, global_bits: u8) -> (bool, u8) { + match (self, bits) { + (_, 0) => (true, 0), + (Self::Blocks, 1..=4) => (true, 4), + (Self::Blocks, 5..=8) => (true, bits), + (Self::Biomes, 1..=3) => (true, bits), + _ => (false, global_bits.max(bits)), + } + } +} + +/// SimpleBitStorage: `64 / bits` values per long, never spanning longs. +pub fn storage_get(data: &[i64], bits: u8, i: usize) -> u32 { + if bits == 0 { + return 0; + } + let per = 64 / bits as usize; + let (cell, offset) = (i / per, (i % per) * bits as usize); + data.get(cell) + .map_or(0, |&l| ((l as u64 >> offset) & ((1u64 << bits) - 1)) as u32) +} +pub fn storage_len(bits: u8, entries: usize) -> usize { + if bits == 0 { + 0 + } else { + entries.div_ceil(64 / bits as usize) + } +} + +/// One PalettedContainer as sent. +#[derive(Clone, Debug, PartialEq)] +pub struct Paletted { + /// Bits per entry as written (Data.storage.getBits()). + pub bits: u8, + /// Palette entries (registry ids); empty for the global palette. + pub palette: Vec, + pub data: Vec, +} +impl Paletted { + pub fn read(r: &mut Reader, strategy: Strategy, global_bits: u8) -> Result { + let wire = r.u8()?; + let (has_palette, bits) = strategy.configuration(wire, global_bits); + let palette = if !has_palette { + Vec::new() + } else if bits == 0 { + vec![r.varint()?] + } else { + let n = r.count(1 << bits)?; + (0..n).map(|_| r.varint()).collect::>()? + }; + let data = r.fixed_longs(storage_len(bits, strategy.entries()))?; + Ok(Self { + bits, + palette, + data, + }) + } + pub fn write(&self, w: &mut Writer) { + w.u8(self.bits); + if !self.palette.is_empty() { + if self.bits != 0 { + w.varint(self.palette.len() as i32); + } + for &p in &self.palette { + w.varint(p); + } + } + for &l in &self.data { + w.i64(l); + } + } + /// The registry id at entry `i` ((y * 16 + z) * 16 + x for blocks). + pub fn get(&self, i: usize) -> i32 { + if self.bits == 0 { + return self.palette.first().copied().unwrap_or(0); + } + let v = storage_get(&self.data, self.bits, i); + if self.palette.is_empty() { + v as i32 + } else { + self.palette.get(v as usize).copied().unwrap_or(0) + } + } + /// Pack values the way the server's container would have grown: + /// the smallest configuration for the number of distinct values. + pub fn from_values(values: &[i32], strategy: Strategy, global_bits: u8) -> Self { + let mut palette: Vec = Vec::new(); + for &v in values { + if !palette.contains(&v) { + palette.push(v); + } + } + let needed = if palette.len() <= 1 { + 0 + } else { + (usize::BITS - (palette.len() - 1).leading_zeros()) as u8 + }; + let (has_palette, bits) = strategy.configuration(needed, global_bits); + if bits == 0 { + return Self { + bits: 0, + palette: vec![palette.first().copied().unwrap_or(0)], + data: Vec::new(), + }; + } + let mut data = vec![0i64; storage_len(bits, values.len())]; + let per = 64 / bits as usize; + for (i, &v) in values.iter().enumerate() { + let id = if has_palette { + palette.iter().position(|&p| p == v).unwrap_or(0) as u64 + } else { + v as u64 + }; + data[i / per] |= (id << ((i % per) * bits as usize)) as i64; + } + Self { + bits, + palette: if has_palette { palette } else { Vec::new() }, + data, + } + } +} + +/// LevelChunkSection.write. +#[derive(Clone, Debug, PartialEq)] +pub struct Section { + pub non_empty: i16, + pub fluids: i16, + pub states: Paletted, + pub biomes: Paletted, +} +impl Section { + pub fn read(r: &mut Reader, block_bits: u8, biome_bits: u8) -> Result { + Ok(Self { + non_empty: r.i16()?, + fluids: r.i16()?, + states: Paletted::read(r, Strategy::Blocks, block_bits)?, + biomes: Paletted::read(r, Strategy::Biomes, biome_bits)?, + }) + } + pub fn write(&self, w: &mut Writer) { + w.i16(self.non_empty); + w.i16(self.fluids); + self.states.write(w); + self.biomes.write(w); + } +} + +packet!( + /// ClientboundLevelChunkPacketData.BlockEntityInfo. + BlockEntityInfo { + packed_xz: i8 => crate::buf::Byte, + y: i16 => crate::buf::Short, + kind: i32 => VarInt, + tag: Tag => crate::buf::Nbt, + } +); +/// Heightmap type id with its packed long array. +pub struct Heightmaps; +impl Codec)>> for Heightmaps { + fn read(r: &mut Reader) -> Result)>> { + let n = r.count(16)?; + (0..n).map(|_| Ok((r.varint()?, r.long_array()?))).collect() + } + fn write(v: &Vec<(i32, Vec)>, w: &mut Writer) { + w.varint(v.len() as i32); + for (kind, data) in v { + w.varint(*kind); + Longs::write(data, w); + } + } +} +packet!( + /// ClientboundLevelChunkPacketData. + ChunkData { + heightmaps: Vec<(i32, Vec)> => Heightmaps, + buffer: Vec => Bytes, + block_entities: Vec => crate::buf::List, + } +); +impl ChunkData { + /// Decode `count` sections from the buffer. + pub fn sections(&self, count: usize, block_bits: u8, biome_bits: u8) -> Result> { + let mut r = Reader::new(&self.buffer); + (0..count) + .map(|_| Section::read(&mut r, block_bits, biome_bits)) + .collect() + } + pub fn from_sections(sections: &[Section]) -> Vec { + let mut w = Writer::new(); + for s in sections { + s.write(&mut w); + } + w.data + } +} +/// ByteBufCodecs.byteArray(2048) per DataLayer. +pub struct Layers; +impl Codec>> for Layers { + fn read(r: &mut Reader) -> Result>> { + let n = r.count(r.remaining())?; + (0..n).map(|_| r.byte_array(2048)).collect() + } + fn write(v: &Vec>, w: &mut Writer) { + w.varint(v.len() as i32); + for l in v { + w.byte_array(l); + } + } +} +packet!( + /// ClientboundLightUpdatePacketData. Bit `i` of a mask is light section + /// `minLightSection + i` (one below the lowest block section). + LightData { + sky_mask: Vec => BitSet, + block_mask: Vec => BitSet, + empty_sky_mask: Vec => BitSet, + empty_block_mask: Vec => BitSet, + sky: Vec> => Layers, + block: Vec> => Layers, + } +); +impl LightData { + /// Per light section: the sky and block DataLayers (None = absent/unchanged, + /// Some(zeroed) when marked empty). + pub fn layers(&self, light_sections: usize) -> Vec<(Option>, Option>)> { + use crate::buf::bit; + let (mut sky, mut block) = (self.sky.iter(), self.block.iter()); + (0..light_sections) + .map(|i| { + let s = if bit(&self.sky_mask, i) { + sky.next().cloned() + } else if bit(&self.empty_sky_mask, i) { + Some(vec![0; 2048]) + } else { + None + }; + let b = if bit(&self.block_mask, i) { + block.next().cloned() + } else if bit(&self.empty_block_mask, i) { + Some(vec![0; 2048]) + } else { + None + }; + (s, b) + }) + .collect() + } +} +/// DataLayer.get: the nibble at (y << 8 | z << 4 | x), low nibble first. +pub fn nibble(layer: &[u8], i: usize) -> u8 { + layer + .get(i >> 1) + .map_or(0, |b| if i & 1 == 0 { b & 15 } else { b >> 4 }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bit_storage_matches_simple_bit_storage() { + // 5 bits: 12 values per long, the top 4 bits of each long unused. + let values: Vec = (0..BLOCKS as i32).map(|i| i % 20).collect(); + let p = Paletted::from_values(&values, Strategy::Blocks, 16); + assert_eq!(p.bits, 5); + assert_eq!(p.data.len(), 4096usize.div_ceil(12)); + for i in [0, 11, 12, 13, 4095] { + assert_eq!(p.get(i), values[i]); + } + } + + #[test] + fn palettes_follow_the_strategies() { + let single = Paletted::from_values(&[7; BLOCKS], Strategy::Blocks, 16); + assert_eq!( + (single.bits, single.palette.clone(), single.data.len()), + (0, vec![7], 0) + ); + // Two distinct block states still use the four-bit linear palette. + let mut two = vec![0; BLOCKS]; + two[100] = 9; + let p = Paletted::from_values(&two, Strategy::Blocks, 16); + assert_eq!((p.bits, p.data.len()), (4, 256)); + // Biomes with two values use one bit; more than eight use the global palette. + let mut biomes = vec![3; BIOMES]; + biomes[5] = 4; + assert_eq!(Paletted::from_values(&biomes, Strategy::Biomes, 7).bits, 1); + let many: Vec = (0..BIOMES as i32).map(|i| i % 9).collect(); + let g = Paletted::from_values(&many, Strategy::Biomes, 7); + assert!(g.palette.is_empty() && g.bits == 7); + assert_eq!(g.get(10), 1); + // Over 256 block states: global palette with the registry's bit width. + let wide: Vec = (0..BLOCKS as i32).map(|i| i * 7).collect(); + let g = Paletted::from_values(&wide, Strategy::Blocks, 16); + assert!(g.palette.is_empty() && g.bits == 16); + assert_eq!(g.get(4095), 4095 * 7); + } + + #[test] + fn chunk_data_round_trips() { + let mut states = vec![0; BLOCKS]; + for (i, s) in states.iter_mut().enumerate().take(256) { + *s = (i % 3) as i32 + 1; + } + let section = Section { + non_empty: 256, + fluids: 0, + states: Paletted::from_values(&states, Strategy::Blocks, 16), + biomes: Paletted::from_values(&[2; BIOMES], Strategy::Biomes, 7), + }; + let empty = Section { + non_empty: 0, + fluids: 0, + states: Paletted::from_values(&[0; BLOCKS], Strategy::Blocks, 16), + biomes: Paletted::from_values(&[2; BIOMES], Strategy::Biomes, 7), + }; + let data = ChunkData { + heightmaps: vec![(1, vec![1, 2, 3]), (4, vec![5])], + buffer: ChunkData::from_sections(&[section.clone(), empty.clone()]), + block_entities: vec![BlockEntityInfo { + packed_xz: 0x3f, + y: -60, + kind: 2, + tag: Tag::End, + }], + }; + let mut w = Writer::new(); + ChunkData::write(&data, &mut w); + let back = ChunkData::read(&mut Reader::new(&w.data)).unwrap(); + assert_eq!(back, data); + let sections = back.sections(2, 16, 7).unwrap(); + assert_eq!(sections, vec![section, empty]); + assert_eq!(sections[0].states.get(4), 2); + assert_eq!(sections[1].states.get(4), 0); + } + + #[test] + fn light_layers_follow_masks() { + let mut light = LightData { + sky_mask: vec![], + block_mask: vec![], + empty_sky_mask: vec![], + empty_block_mask: vec![], + sky: vec![vec![0xF0; 2048]], + block: vec![], + }; + crate::buf::set_bit(&mut light.sky_mask, 3); + crate::buf::set_bit(&mut light.empty_block_mask, 1); + let mut w = Writer::new(); + LightData::write(&light, &mut w); + let back = LightData::read(&mut Reader::new(&w.data)).unwrap(); + assert_eq!(back, light); + let layers = back.layers(26); + assert_eq!(layers.len(), 26); + assert_eq!(nibble(layers[3].0.as_ref().unwrap(), 1), 15); + assert_eq!(nibble(layers[3].0.as_ref().unwrap(), 0), 0); + assert_eq!(layers[1].1.as_deref(), Some(&[0u8; 2048][..])); + assert!(layers[0].0.is_none() && layers[0].1.is_none()); + } +} diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs new file mode 100644 index 000000000..5c0bba188 --- /dev/null +++ b/crates/horizon-protocol/src/connection.rs @@ -0,0 +1,183 @@ +//! A blocking TCP connection with vanilla's pipeline: optional AES/CFB8 +//! encryption, VarInt21 framing and threshold compression. After login it +//! splits into a reader (for a receive thread) and a shareable writer. +use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame}; +use std::{ + io::{Read, Write}, + net::{Shutdown, TcpStream, ToSocketAddrs}, + sync::{ + Arc, + atomic::{AtomicI64, Ordering}, + }, + time::Duration, +}; + +/// Packets received/sent and bytes in/out, for the debug screen. +#[derive(Debug, Default)] +pub struct Counters { + pub received: AtomicI64, + pub sent: AtomicI64, + pub bytes_in: AtomicI64, + pub bytes_out: AtomicI64, +} + +pub struct ConnReader { + stream: TcpStream, + buffer: Vec, + decrypt: Option, + pub threshold: Option, + pub counters: Arc, +} +pub struct ConnWriter { + stream: TcpStream, + encrypt: Option, + pub threshold: Option, + counters: Arc, +} +/// Both halves before the split. +pub struct Connection { + pub reader: ConnReader, + pub writer: ConnWriter, +} +impl Connection { + pub fn connect(host: &str, port: u16, timeout: Duration) -> Result { + let addrs: Vec<_> = (host, port) + .to_socket_addrs() + .map_err(|e| Error::new(format!("Unknown host {host}: {e}")))? + .collect(); + let mut last = Error::new(format!("Unknown host {host}")); + for addr in addrs { + match TcpStream::connect_timeout(&addr, timeout) { + Ok(stream) => return Self::from_stream(stream), + Err(e) => last = Error::new(format!("Connection refused: {e}")), + } + } + Err(last) + } + pub fn from_stream(stream: TcpStream) -> Result { + stream.set_nodelay(true)?; + let counters = Arc::new(Counters::default()); + let write = stream.try_clone()?; + Ok(Self { + reader: ConnReader { + stream, + buffer: Vec::new(), + decrypt: None, + threshold: None, + counters: counters.clone(), + }, + writer: ConnWriter { + stream: write, + encrypt: None, + threshold: None, + counters, + }, + }) + } + /// ClientboundLoginCompressionPacket: negative thresholds disable compression. + pub fn set_compression(&mut self, threshold: i32) { + let t = usize::try_from(threshold).ok(); + self.reader.threshold = t; + self.writer.threshold = t; + } + /// Connection.setEncryptionKey: both directions keyed with the shared secret. + pub fn enable_encryption(&mut self, secret: &[u8; 16]) { + self.reader.decrypt = Some(Cfb8::new(secret, secret)); + self.writer.encrypt = Some(Cfb8::new(secret, secret)); + } + pub fn send(&mut self, body: &[u8]) -> Result<()> { + self.writer.send(body) + } + pub fn recv(&mut self) -> Result<(i32, Vec)> { + self.reader.recv() + } + pub fn split(self) -> (ConnReader, ConnWriter) { + (self.reader, self.writer) + } +} +impl ConnReader { + /// Block until a whole packet arrives: (id, payload). + pub fn recv(&mut self) -> Result<(i32, Vec)> { + loop { + if let Some(frame) = frame::split(&mut self.buffer)? { + let body = frame::decompress(frame, self.threshold)?; + let mut r = Reader::new(&body); + let id = r.varint()?; + let start = r.position(); + self.counters.received.fetch_add(1, Ordering::Relaxed); + return Ok((id, body[start..].to_vec())); + } + let mut chunk = [0u8; 16384]; + let n = self.stream.read(&mut chunk)?; + if n == 0 { + return Err(Error::new("Connection closed by the server")); + } + self.counters + .bytes_in + .fetch_add(n as i64, Ordering::Relaxed); + let data = &mut chunk[..n]; + if let Some(c) = &mut self.decrypt { + c.decrypt(data); + } + self.buffer.extend_from_slice(data); + } + } + pub fn set_read_timeout(&self, timeout: Option) -> Result<()> { + Ok(self.stream.set_read_timeout(timeout)?) + } +} +impl ConnWriter { + /// Send one packet body (VarInt id + payload). + pub fn send(&mut self, body: &[u8]) -> Result<()> { + let mut framed = frame::encode(body, self.threshold)?; + if let Some(c) = &mut self.encrypt { + c.encrypt(&mut framed); + } + self.stream.write_all(&framed)?; + self.counters.sent.fetch_add(1, Ordering::Relaxed); + self.counters + .bytes_out + .fetch_add(framed.len() as i64, Ordering::Relaxed); + Ok(()) + } + pub fn shutdown(&self) { + let _ = self.stream.shutdown(Shutdown::Both); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::TcpListener; + + #[test] + fn loopback_with_compression_and_encryption() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut c = Connection::from_stream(stream).unwrap(); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.as_slice()), (0, &b"plain"[..])); + c.enable_encryption(&[7; 16]); + c.set_compression(64); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.len()), (5, 1000)); + let mut body = vec![9]; + body.extend_from_slice(b"reply"); + c.send(&body).unwrap(); + }); + let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).unwrap(); + let mut body = vec![0]; + body.extend_from_slice(b"plain"); + c.send(&body).unwrap(); + c.enable_encryption(&[7; 16]); + c.set_compression(64); + let mut big = vec![5]; + big.extend(std::iter::repeat_n(3u8, 1000)); + c.send(&big).unwrap(); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.as_slice()), (9, &b"reply"[..])); + server.join().unwrap(); + } +} diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs new file mode 100644 index 000000000..c55b003b5 --- /dev/null +++ b/crates/horizon-protocol/src/crypto.rs @@ -0,0 +1,275 @@ +//! Connection encryption (Crypt.getCipher: AES/CFB8/NoPadding with the shared +//! secret as key and IV) and MD5 name-based UUIDs for offline-mode profiles +//! (UUIDUtil.createOfflinePlayerUUID). Only the AES forward cipher is needed: +//! CFB8 encrypts the shift register in both directions. + +const SBOX: [u8; 256] = { + // Generated from the AES field inverse and affine transform at compile time. + let mut sbox = [0u8; 256]; + let mut p: u8 = 1; + let mut q: u8 = 1; + loop { + // p *= 3 + p = p ^ (p << 1) ^ if p & 0x80 != 0 { 0x1B } else { 0 }; + // q /= 3 + q ^= q << 1; + q ^= q << 2; + q ^= q << 4; + if q & 0x80 != 0 { + q ^= 0x09; + } + let x = q ^ q.rotate_left(1) ^ q.rotate_left(2) ^ q.rotate_left(3) ^ q.rotate_left(4); + sbox[p as usize] = x ^ 0x63; + if p == 1 { + break; + } + } + sbox[0] = 0x63; + sbox +}; + +fn xtime(b: u8) -> u8 { + (b << 1) ^ if b & 0x80 != 0 { 0x1B } else { 0 } +} + +/// AES-128 block encryption (FIPS-197). +#[derive(Clone)] +pub struct Aes128 { + round_keys: [[u8; 16]; 11], +} +impl Aes128 { + pub fn new(key: &[u8; 16]) -> Self { + let mut w = [[0u8; 4]; 44]; + for i in 0..4 { + w[i].copy_from_slice(&key[i * 4..i * 4 + 4]); + } + let mut rcon = 1u8; + for i in 4..44 { + let mut t = w[i - 1]; + if i % 4 == 0 { + t = [ + SBOX[t[1] as usize] ^ rcon, + SBOX[t[2] as usize], + SBOX[t[3] as usize], + SBOX[t[0] as usize], + ]; + rcon = xtime(rcon); + } + for j in 0..4 { + w[i][j] = w[i - 4][j] ^ t[j]; + } + } + let mut round_keys = [[0u8; 16]; 11]; + for (r, key) in round_keys.iter_mut().enumerate() { + for c in 0..4 { + key[c * 4..c * 4 + 4].copy_from_slice(&w[r * 4 + c]); + } + } + Self { round_keys } + } + pub fn encrypt_block(&self, block: &mut [u8; 16]) { + let add = |s: &mut [u8; 16], k: &[u8; 16]| s.iter_mut().zip(k).for_each(|(a, b)| *a ^= b); + add(block, &self.round_keys[0]); + for round in 1..=10 { + for b in block.iter_mut() { + *b = SBOX[*b as usize]; + } + // ShiftRows (column-major state: byte r + 4c). + let s = *block; + for c in 0..4 { + for r in 0..4 { + block[r + 4 * c] = s[r + 4 * ((c + r) % 4)]; + } + } + if round != 10 { + for c in 0..4 { + let col = [ + block[4 * c], + block[4 * c + 1], + block[4 * c + 2], + block[4 * c + 3], + ]; + let all = col[0] ^ col[1] ^ col[2] ^ col[3]; + for r in 0..4 { + block[4 * c + r] = col[r] ^ all ^ xtime(col[r] ^ col[(r + 1) % 4]); + } + } + } + add(block, &self.round_keys[round]); + } + } +} + +/// AES/CFB8 stream state for one direction of a connection. +#[derive(Clone)] +pub struct Cfb8 { + aes: Aes128, + register: [u8; 16], +} +impl Cfb8 { + /// Minecraft uses the 16-byte shared secret as both key and IV. + pub fn new(key: &[u8; 16], iv: &[u8; 16]) -> Self { + Self { + aes: Aes128::new(key), + register: *iv, + } + } + fn keystream(&self) -> u8 { + let mut block = self.register; + self.aes.encrypt_block(&mut block); + block[0] + } + fn shift(&mut self, cipher_byte: u8) { + self.register.copy_within(1.., 0); + self.register[15] = cipher_byte; + } + pub fn encrypt(&mut self, data: &mut [u8]) { + for b in data { + *b ^= self.keystream(); + self.shift(*b); + } + } + pub fn decrypt(&mut self, data: &mut [u8]) { + for b in data { + let c = *b; + *b ^= self.keystream(); + self.shift(c); + } + } +} + +/// MD5 (RFC 1321). +pub fn md5(input: &[u8]) -> [u8; 16] { + const S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, + 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, + 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ]; + let k: Vec = (0..64) + .map(|i| ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32) + .collect(); + let (mut a0, mut b0, mut c0, mut d0) = ( + 0x6745_2301u32, + 0xefcd_ab89u32, + 0x98ba_dcfeu32, + 0x1032_5476u32, + ); + let mut msg = input.to_vec(); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&((input.len() as u64).wrapping_mul(8)).to_le_bytes()); + for chunk in msg.chunks(64) { + let m: Vec = chunk + .chunks(4) + .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])) + .collect(); + let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0); + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]); + a = d; + d = c; + c = b; + b = b.wrapping_add(f.rotate_left(S[i])); + } + a0 = a0.wrapping_add(a); + b0 = b0.wrapping_add(b); + c0 = c0.wrapping_add(c); + d0 = d0.wrapping_add(d); + } + let mut out = [0u8; 16]; + for (i, v) in [a0, b0, c0, d0].iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + out +} + +/// UUID.nameUUIDFromBytes("OfflinePlayer:" + name): MD5, version 3, IETF variant. +pub fn offline_uuid(name: &str) -> u128 { + let mut h = md5(format!("OfflinePlayer:{name}").as_bytes()); + h[6] = (h[6] & 0x0f) | 0x30; + h[8] = (h[8] & 0x3f) | 0x80; + u128::from_be_bytes(h) +} +/// The canonical 8-4-4-4-12 form. +pub fn uuid_string(u: u128) -> String { + let h = format!("{u:032x}"); + format!( + "{}-{}-{}-{}-{}", + &h[..8], + &h[8..12], + &h[12..16], + &h[16..20], + &h[20..] + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() + } + + #[test] + fn sbox_spot_checks() { + assert_eq!(SBOX[0x00], 0x63); + assert_eq!(SBOX[0x01], 0x7c); + assert_eq!(SBOX[0x53], 0xed); + assert_eq!(SBOX[0xff], 0x16); + } + + #[test] + fn aes128_fips197_vector() { + let key: [u8; 16] = hex("000102030405060708090a0b0c0d0e0f").try_into().unwrap(); + let mut block: [u8; 16] = hex("00112233445566778899aabbccddeeff").try_into().unwrap(); + Aes128::new(&key).encrypt_block(&mut block); + assert_eq!(block.to_vec(), hex("69c4e0d86a7b0430d8cdb78070b4c55a")); + } + + #[test] + fn cfb8_nist_sp800_38a_vector() { + let key: [u8; 16] = hex("2b7e151628aed2a6abf7158809cf4f3c").try_into().unwrap(); + let iv: [u8; 16] = hex("000102030405060708090a0b0c0d0e0f").try_into().unwrap(); + let plain = hex("6bc1bee22e409f96e93d7e117393172aae2d"); + let expected = hex("3b79424c9c0dd436bace9e0ed4586a4f32b9"); + let mut data = plain.clone(); + // Split across calls: the stream state carries over. + let mut enc = Cfb8::new(&key, &iv); + let (a, b) = data.split_at_mut(5); + enc.encrypt(a); + enc.encrypt(b); + assert_eq!(data, expected); + let mut dec = Cfb8::new(&key, &iv); + dec.decrypt(&mut data); + assert_eq!(data, plain); + } + + #[test] + fn md5_and_offline_uuids() { + assert_eq!(md5(b"").to_vec(), hex("d41d8cd98f00b204e9800998ecf8427e")); + assert_eq!( + md5(b"abc").to_vec(), + hex("900150983cd24fb0d6963f7d28e17f72") + ); + assert_eq!( + md5(&[b'a'; 100]).to_vec(), + hex("36a92cc94a9e0fa21f625f8bfb007adf") + ); + assert_eq!( + uuid_string(offline_uuid("Notch")), + "b50ad385-829d-3141-a216-7e7d7539ba7f" + ); + } +} diff --git a/crates/horizon-protocol/src/entity_data.rs b/crates/horizon-protocol/src/entity_data.rs new file mode 100644 index 000000000..08872ed43 --- /dev/null +++ b/crates/horizon-protocol/src/entity_data.rs @@ -0,0 +1,189 @@ +//! SynchedEntityData values (ClientboundSetEntityDataPacket): an entry index, +//! the EntityDataSerializers id, and the serializer's value, ending with 0xFF. +//! Serializers Horizon cannot decode end the list early; the entries before +//! them are kept. +use crate::{ + Result, + buf::{Codec, Reader, Writer}, + item::{Slot, Stack}, +}; +use horizon_world::nbt::Tag; + +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + Byte(i8), + Int(i32), + Long(i64), + Float(f32), + String(String), + Text(Tag), + OptText(Option), + Item(Option), + Bool(bool), + Floats(Vec), + Pos([i32; 3]), + OptPos(Option<[i32; 3]>), + OptUuid(Option), + /// Any VarInt-valued serializer (direction, block state, pose, variants ...). + Id(i32), +} +/// Serializer ids in EntityDataSerializers registration order. +pub mod serializer { + pub const BYTE: i32 = 0; + pub const INT: i32 = 1; + pub const LONG: i32 = 2; + pub const FLOAT: i32 = 3; + pub const STRING: i32 = 4; + pub const COMPONENT: i32 = 5; + pub const OPTIONAL_COMPONENT: i32 = 6; + pub const ITEM_STACK: i32 = 7; + pub const BOOLEAN: i32 = 8; + pub const ROTATIONS: i32 = 9; + pub const BLOCK_POS: i32 = 10; + pub const OPTIONAL_BLOCK_POS: i32 = 11; + pub const DIRECTION: i32 = 12; + pub const OPTIONAL_LIVING_ENTITY_REFERENCE: i32 = 13; + pub const BLOCK_STATE: i32 = 14; + pub const OPTIONAL_BLOCK_STATE: i32 = 15; + pub const OPTIONAL_UNSIGNED_INT: i32 = 19; + pub const POSE: i32 = 20; + pub const VECTOR3: i32 = 40; + pub const QUATERNION: i32 = 41; + pub const HUMANOID_ARM: i32 = 43; + pub const DYE_COLOR: i32 = 44; +} +fn read_value(kind: i32, r: &mut Reader) -> Result> { + use serializer::*; + Ok(Some(match kind { + BYTE => Value::Byte(r.i8()?), + INT => Value::Int(r.varint()?), + LONG => Value::Long(r.varlong()?), + FLOAT => Value::Float(r.f32()?), + STRING => Value::String(r.string(32767)?), + COMPONENT => Value::Text(r.nbt()?), + OPTIONAL_COMPONENT => Value::OptText(if r.bool()? { Some(r.nbt()?) } else { None }), + ITEM_STACK => Value::Item(Slot::read(r)?), + BOOLEAN => Value::Bool(r.bool()?), + ROTATIONS | VECTOR3 => Value::Floats(vec![r.f32()?, r.f32()?, r.f32()?]), + QUATERNION => Value::Floats(vec![r.f32()?, r.f32()?, r.f32()?, r.f32()?]), + BLOCK_POS => Value::Pos(crate::buf::Pos::read(r)?), + OPTIONAL_BLOCK_POS => Value::OptPos(if r.bool()? { + Some(crate::buf::Pos::read(r)?) + } else { + None + }), + OPTIONAL_LIVING_ENTITY_REFERENCE => { + Value::OptUuid(if r.bool()? { Some(r.uuid()?) } else { None }) + } + // VarInt-encoded: direction, block states, optional ints, pose, the + // holder-registry variants (21..=33) and enum states (36..=39), arm, dye. + DIRECTION + | BLOCK_STATE + | OPTIONAL_BLOCK_STATE + | OPTIONAL_UNSIGNED_INT + | POSE + | 21..=33 + | 36..=39 + | HUMANOID_ARM + | DYE_COLOR => Value::Id(r.varint()?), + _ => return Ok(None), + })) +} +fn write_value(kind: i32, v: &Value, w: &mut Writer) { + match v { + Value::Byte(b) => w.i8(*b), + Value::Int(i) | Value::Id(i) => w.varint(*i), + Value::Long(l) => w.varlong(*l), + Value::Float(f) => w.f32(*f), + Value::String(s) => w.string(s), + Value::Text(t) => w.nbt(t), + Value::OptText(t) => { + w.bool(t.is_some()); + if let Some(t) = t { + w.nbt(t); + } + } + Value::Item(s) => Slot::write(s, w), + Value::Bool(b) => w.bool(*b), + Value::Floats(f) => f.iter().for_each(|f| w.f32(*f)), + Value::Pos(p) => crate::buf::Pos::write(p, w), + Value::OptPos(p) => { + w.bool(p.is_some()); + if let Some(p) = p { + crate::buf::Pos::write(p, w); + } + } + Value::OptUuid(u) => { + w.bool(u.is_some()); + if let Some(u) = u { + w.uuid(*u); + } + } + } + let _ = kind; +} + +/// (index, serializer id, value) entries. +pub struct EntityData; +impl Codec> for EntityData { + fn read(r: &mut Reader) -> Result> { + let mut out = Vec::new(); + loop { + let index = r.u8()?; + if index == 0xFF { + return Ok(out); + } + let kind = r.varint()?; + match read_value(kind, r)? { + Some(v) => out.push((index, kind, v)), + None => { + r.rest(); + return Ok(out); + } + } + } + } + fn write(v: &Vec<(u8, i32, Value)>, w: &mut Writer) { + for (index, kind, value) in v { + w.u8(*index); + w.varint(*kind); + write_value(*kind, value, w); + } + w.u8(0xFF); + } +} + +/// ItemEntity.DATA_ITEM (after the eight Entity data entries). +pub const ITEM_ENTITY_ITEM: u8 = 8; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_and_stops_at_unknown_serializers() { + let entries = vec![ + (0u8, serializer::BYTE, Value::Byte(0x02)), + (1, serializer::INT, Value::Int(300)), + (2, serializer::OPTIONAL_COMPONENT, Value::OptText(None)), + (6, serializer::POSE, Value::Id(5)), + ( + 8, + serializer::ITEM_STACK, + Value::Item(Some(Stack::new(3, 12))), + ), + ]; + let mut w = Writer::new(); + EntityData::write(&entries, &mut w); + assert_eq!(*w.data.last().unwrap(), 0xFF); + assert_eq!( + EntityData::read(&mut Reader::new(&w.data)).unwrap(), + entries + ); + // A particle (16) cannot be skipped: keep what came before. + let mut bytes = vec![0, 0, 7, 9, 16, 1, 2, 3]; + bytes.push(0xFF); + let read = EntityData::read(&mut Reader::new(&bytes)).unwrap(); + assert_eq!(read, vec![(0, 0, Value::Byte(7))]); + } +} diff --git a/crates/horizon-protocol/src/frame.rs b/crates/horizon-protocol/src/frame.rs new file mode 100644 index 000000000..9a1402e0b --- /dev/null +++ b/crates/horizon-protocol/src/frame.rs @@ -0,0 +1,155 @@ +//! Packet framing (Varint21FrameDecoder / Varint21LengthFieldPrepender) and +//! zlib compression above a threshold (CompressionEncoder / CompressionDecoder). +use crate::{ + Error, Result, + buf::{Reader, varint_size, write_varint}, +}; +use flate2::{Compression, read::ZlibDecoder, write::ZlibEncoder}; +use std::io::{Read, Write}; + +/// Frames are at most three VarInt bytes long (21 bits). +pub const MAX_FRAME: usize = (1 << 21) - 1; +/// CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH. +pub const MAX_UNCOMPRESSED: usize = 8_388_608; + +/// Build the frame for one packet body (`id` + payload already concatenated): +/// length prefix, and with compression enabled the uncompressed-length +/// field (0 when below the threshold). +pub fn encode(body: &[u8], threshold: Option) -> Result> { + let inner = match threshold { + None => body.to_vec(), + Some(t) if body.len() < t => { + let mut v = Vec::with_capacity(body.len() + 1); + v.push(0); + v.extend_from_slice(body); + v + } + Some(_) => { + let mut v = Vec::with_capacity(body.len() / 2 + 8); + write_varint(&mut v, body.len() as i32); + let mut z = ZlibEncoder::new(v, Compression::default()); + z.write_all(body)?; + z.finish()? + } + }; + if inner.len() > MAX_FRAME { + return Err(Error::new(format!( + "packet too large: {} bytes", + inner.len() + ))); + } + let mut out = Vec::with_capacity(inner.len() + 3); + write_varint(&mut out, inner.len() as i32); + out.extend_from_slice(&inner); + Ok(out) +} + +/// Split one complete frame off the front of `buffer`, if available. +/// Returns the frame contents (without the length prefix). +pub fn split(buffer: &mut Vec) -> Result>> { + let mut len = 0usize; + for i in 0..3 { + let Some(&b) = buffer.get(i) else { + return Ok(None); + }; + len |= usize::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + let start = i + 1; + if buffer.len() < start + len { + return Ok(None); + } + let frame = buffer[start..start + len].to_vec(); + buffer.drain(..start + len); + return Ok(Some(frame)); + } + } + Err(Error::new("length wider than 21 bits")) +} + +/// Undo compression on a frame, giving the packet body (id + payload). +pub fn decompress(frame: Vec, threshold: Option) -> Result> { + let Some(threshold) = threshold else { + return Ok(frame); + }; + let mut r = Reader::new(&frame); + let size = r.varint()?; + if size == 0 { + return Ok(frame[1..].to_vec()); + } + let size = usize::try_from(size).map_err(|_| Error::new("negative uncompressed length"))?; + if size < threshold { + return Err(Error::new(format!( + "Badly compressed packet - size of {size} is below server threshold of {threshold}" + ))); + } + if size > MAX_UNCOMPRESSED { + return Err(Error::new(format!( + "Badly compressed packet - size of {size} is larger than protocol maximum" + ))); + } + let start = varint_size(size as i32); + let mut out = Vec::with_capacity(size); + ZlibDecoder::new(&frame[start..]) + .take(size as u64 + 1) + .read_to_end(&mut out)?; + if out.len() != size { + return Err(Error::new(format!( + "Badly compressed packet - actual length {} does not match declared size {size}", + out.len() + ))); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uncompressed_frames_round_trip() { + let body = vec![0x00, 1, 2, 3]; + let framed = encode(&body, None).unwrap(); + assert_eq!(framed, [4, 0, 1, 2, 3]); + let mut buffer = framed.clone(); + buffer.extend_from_slice(&framed[..2]); + assert_eq!(split(&mut buffer).unwrap(), Some(body)); + assert_eq!(split(&mut buffer).unwrap(), None); + assert_eq!(buffer, [4, 0]); + } + + #[test] + fn compression_threshold_like_vanilla() { + // Below the threshold: a zero data length, then the raw body. + let small = vec![7u8; 10]; + let framed = encode(&small, Some(256)).unwrap(); + assert_eq!(&framed[..2], &[11, 0]); + let mut buffer = framed; + let frame = split(&mut buffer).unwrap().unwrap(); + assert_eq!(decompress(frame, Some(256)).unwrap(), small); + // At or above: the uncompressed size and a zlib stream. + let big: Vec = (0..5000u32).map(|i| (i % 7) as u8).collect(); + let framed = encode(&big, Some(256)).unwrap(); + assert!(framed.len() < big.len()); + let mut buffer = framed; + let frame = split(&mut buffer).unwrap().unwrap(); + assert_eq!(Reader::new(&frame).varint().unwrap(), 5000); + assert_eq!(decompress(frame, Some(256)).unwrap(), big); + } + + #[test] + fn rejects_bad_compressed_lengths() { + // Declared size below the threshold is a protocol error. + let mut frame = vec![10]; + let mut z = ZlibEncoder::new(Vec::new(), Compression::default()); + z.write_all(&[1; 10]).unwrap(); + frame.extend(z.finish().unwrap()); + assert!(decompress(frame, Some(256)).is_err()); + // Declared size that does not match the stream. + let mut frame = Vec::new(); + write_varint(&mut frame, 300); + let mut z = ZlibEncoder::new(Vec::new(), Compression::default()); + z.write_all(&[1; 299]).unwrap(); + frame.extend(z.finish().unwrap()); + assert!(decompress(frame, Some(256)).is_err()); + } +} diff --git a/crates/horizon-protocol/src/ids.rs b/crates/horizon-protocol/src/ids.rs new file mode 100644 index 000000000..892b6af9a --- /dev/null +++ b/crates/horizon-protocol/src/ids.rs @@ -0,0 +1,590 @@ +//! Packet ids per connection state and direction for protocol 777 (26.3). +//! Generated by tools/generate_packet_ids.py from the data generator's +//! packets report; do not edit by hand. +#![allow(missing_docs)] +use crate::{Direction, State}; + +pub mod handshake { + pub mod serverbound { + pub const INTENTION: i32 = 0; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &["intention"]; + } +} +pub mod status { + pub mod clientbound { + pub const STATUS_RESPONSE: i32 = 0; + pub const PONG_RESPONSE: i32 = 1; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &["status_response", "pong_response"]; + } + pub mod serverbound { + pub const STATUS_REQUEST: i32 = 0; + pub const PING_REQUEST: i32 = 1; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &["status_request", "ping_request"]; + } +} +pub mod login { + pub mod clientbound { + pub const LOGIN_DISCONNECT: i32 = 0; + pub const HELLO: i32 = 1; + pub const LOGIN_FINISHED: i32 = 2; + pub const LOGIN_COMPRESSION: i32 = 3; + pub const CUSTOM_QUERY: i32 = 4; + pub const COOKIE_REQUEST: i32 = 5; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "login_disconnect", + "hello", + "login_finished", + "login_compression", + "custom_query", + "cookie_request", + ]; + } + pub mod serverbound { + pub const HELLO: i32 = 0; + pub const KEY: i32 = 1; + pub const CUSTOM_QUERY_ANSWER: i32 = 2; + pub const LOGIN_ACKNOWLEDGED: i32 = 3; + pub const COOKIE_RESPONSE: i32 = 4; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "hello", + "key", + "custom_query_answer", + "login_acknowledged", + "cookie_response", + ]; + } +} +pub mod configuration { + pub mod clientbound { + pub const COOKIE_REQUEST: i32 = 0; + pub const CUSTOM_PAYLOAD: i32 = 1; + pub const DISCONNECT: i32 = 2; + pub const FINISH_CONFIGURATION: i32 = 3; + pub const KEEP_ALIVE: i32 = 4; + pub const PING: i32 = 5; + pub const RESET_CHAT: i32 = 6; + pub const REGISTRY_DATA: i32 = 7; + pub const RESOURCE_PACK_POP: i32 = 8; + pub const RESOURCE_PACK_PUSH: i32 = 9; + pub const POST_EFFECTS: i32 = 10; + pub const STORE_COOKIE: i32 = 11; + pub const TRANSFER: i32 = 12; + pub const UPDATE_ENABLED_FEATURES: i32 = 13; + pub const UPDATE_TAGS: i32 = 14; + pub const SELECT_KNOWN_PACKS: i32 = 15; + pub const CUSTOM_REPORT_DETAILS: i32 = 16; + pub const SERVER_LINKS: i32 = 17; + pub const CLEAR_DIALOG: i32 = 18; + pub const SHOW_DIALOG: i32 = 19; + pub const CODE_OF_CONDUCT: i32 = 20; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "cookie_request", + "custom_payload", + "disconnect", + "finish_configuration", + "keep_alive", + "ping", + "reset_chat", + "registry_data", + "resource_pack_pop", + "resource_pack_push", + "post_effects", + "store_cookie", + "transfer", + "update_enabled_features", + "update_tags", + "select_known_packs", + "custom_report_details", + "server_links", + "clear_dialog", + "show_dialog", + "code_of_conduct", + ]; + } + pub mod serverbound { + pub const CLIENT_INFORMATION: i32 = 0; + pub const COOKIE_RESPONSE: i32 = 1; + pub const CUSTOM_PAYLOAD: i32 = 2; + pub const FINISH_CONFIGURATION: i32 = 3; + pub const KEEP_ALIVE: i32 = 4; + pub const PONG: i32 = 5; + pub const RESOURCE_PACK: i32 = 6; + pub const SELECT_KNOWN_PACKS: i32 = 7; + pub const CUSTOM_CLICK_ACTION: i32 = 8; + pub const ACCEPT_CODE_OF_CONDUCT: i32 = 9; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "client_information", + "cookie_response", + "custom_payload", + "finish_configuration", + "keep_alive", + "pong", + "resource_pack", + "select_known_packs", + "custom_click_action", + "accept_code_of_conduct", + ]; + } +} +pub mod play { + pub mod clientbound { + pub const BUNDLE_DELIMITER: i32 = 0; + pub const ADD_ENTITY: i32 = 1; + pub const ANIMATE: i32 = 2; + pub const AWARD_STATS: i32 = 3; + pub const BLOCK_CHANGED_ACK: i32 = 4; + pub const BLOCK_DESTRUCTION: i32 = 5; + pub const BLOCK_ENTITY_DATA: i32 = 6; + pub const BLOCK_EVENT: i32 = 7; + pub const BLOCK_UPDATE: i32 = 8; + pub const BOSS_EVENT: i32 = 9; + pub const CHANGE_DIFFICULTY: i32 = 10; + pub const CHUNK_BATCH_FINISHED: i32 = 11; + pub const CHUNK_BATCH_START: i32 = 12; + pub const CHUNKS_BIOMES: i32 = 13; + pub const CLEAR_TITLES: i32 = 14; + pub const COMMAND_SUGGESTIONS: i32 = 15; + pub const COMMANDS: i32 = 16; + pub const CONTAINER_CLOSE: i32 = 17; + pub const CONTAINER_SET_CONTENT: i32 = 18; + pub const CONTAINER_SET_DATA: i32 = 19; + pub const CONTAINER_SET_SLOT: i32 = 20; + pub const COOKIE_REQUEST: i32 = 21; + pub const COOLDOWN: i32 = 22; + pub const CUSTOM_CHAT_COMPLETIONS: i32 = 23; + pub const CUSTOM_PAYLOAD: i32 = 24; + pub const DAMAGE_EVENT: i32 = 25; + pub const DEBUG_BLOCK_VALUE: i32 = 26; + pub const DEBUG_CHUNK_VALUE: i32 = 27; + pub const DEBUG_ENTITY_VALUE: i32 = 28; + pub const DEBUG_EVENT: i32 = 29; + pub const DEBUG_SAMPLE: i32 = 30; + pub const DELETE_CHAT: i32 = 31; + pub const DISCONNECT: i32 = 32; + pub const DISGUISED_CHAT: i32 = 33; + pub const ENTITY_EVENT: i32 = 34; + pub const ENTITY_POSITION_SYNC: i32 = 35; + pub const EXPLODE: i32 = 36; + pub const ADD_TRANSIENT_BLOCK: i32 = 37; + pub const FORGET_LEVEL_CHUNK: i32 = 38; + pub const GAME_EVENT: i32 = 39; + pub const GAME_RULE_VALUES: i32 = 40; + pub const GAME_TEST_HIGHLIGHT_POS: i32 = 41; + pub const MOUNT_SCREEN_OPEN: i32 = 42; + pub const HURT_ANIMATION: i32 = 43; + pub const INITIALIZE_BORDER: i32 = 44; + pub const KEEP_ALIVE: i32 = 45; + pub const LEVEL_CHUNK_WITH_LIGHT: i32 = 46; + pub const LEVEL_EVENT: i32 = 47; + pub const LEVEL_PARTICLES: i32 = 48; + pub const LIGHT_UPDATE: i32 = 49; + pub const LOGIN: i32 = 50; + pub const LOW_DISK_SPACE_WARNING: i32 = 51; + pub const MAP_ITEM_DATA: i32 = 52; + pub const MERCHANT_OFFERS: i32 = 53; + pub const MOVE_ENTITY_POS: i32 = 54; + pub const MOVE_ENTITY_POS_ROT: i32 = 55; + pub const MOVE_MINECART_ALONG_TRACK: i32 = 56; + pub const MOVE_ENTITY_ROT: i32 = 57; + pub const MOVE_VEHICLE: i32 = 58; + pub const OPEN_BOOK: i32 = 59; + pub const OPEN_SCREEN: i32 = 60; + pub const OPEN_SIGN_EDITOR: i32 = 61; + pub const PING: i32 = 62; + pub const PONG_RESPONSE: i32 = 63; + pub const PLACE_GHOST_RECIPE: i32 = 64; + pub const PLAYER_ABILITIES: i32 = 65; + pub const PLAYER_CHAT: i32 = 66; + pub const PLAYER_COMBAT_END: i32 = 67; + pub const PLAYER_COMBAT_ENTER: i32 = 68; + pub const PLAYER_COMBAT_KILL: i32 = 69; + pub const PLAYER_INFO_REMOVE: i32 = 70; + pub const PLAYER_INFO_UPDATE: i32 = 71; + pub const PLAYER_LOOK_AT: i32 = 72; + pub const PLAYER_POSITION: i32 = 73; + pub const PLAYER_ROTATION: i32 = 74; + pub const RECIPE_BOOK_ADD: i32 = 75; + pub const RECIPE_BOOK_REMOVE: i32 = 76; + pub const RECIPE_BOOK_SETTINGS: i32 = 77; + pub const REMOVE_ENTITIES: i32 = 78; + pub const REMOVE_MOB_EFFECT: i32 = 79; + pub const RESET_SCORE: i32 = 80; + pub const RESOURCE_PACK_POP: i32 = 81; + pub const RESOURCE_PACK_PUSH: i32 = 82; + pub const POST_EFFECTS: i32 = 83; + pub const RESPAWN: i32 = 84; + pub const ROTATE_HEAD: i32 = 85; + pub const SECTION_BLOCKS_UPDATE: i32 = 86; + pub const SELECT_ADVANCEMENTS_TAB: i32 = 87; + pub const SERVER_DATA: i32 = 88; + pub const SET_ACTION_BAR_TEXT: i32 = 89; + pub const SET_BORDER_CENTER: i32 = 90; + pub const SET_BORDER_LERP_SIZE: i32 = 91; + pub const SET_BORDER_SIZE: i32 = 92; + pub const SET_BORDER_WARNING_DELAY: i32 = 93; + pub const SET_BORDER_WARNING_DISTANCE: i32 = 94; + pub const SET_CAMERA: i32 = 95; + pub const SET_CHUNK_CACHE_CENTER: i32 = 96; + pub const SET_CHUNK_CACHE_RADIUS: i32 = 97; + pub const SET_CURSOR_ITEM: i32 = 98; + pub const SET_DEFAULT_SPAWN_POSITION: i32 = 99; + pub const SET_DISPLAY_OBJECTIVE: i32 = 100; + pub const SET_ENTITY_DATA: i32 = 101; + pub const SET_ENTITY_LINK: i32 = 102; + pub const SET_ENTITY_MOTION: i32 = 103; + pub const SET_EQUIPMENT: i32 = 104; + pub const SET_EXPERIENCE: i32 = 105; + pub const SET_HEALTH: i32 = 106; + pub const SET_HELD_SLOT: i32 = 107; + pub const SET_OBJECTIVE: i32 = 108; + pub const SET_PASSENGERS: i32 = 109; + pub const SET_PLAYER_INVENTORY: i32 = 110; + pub const SET_PLAYER_TEAM: i32 = 111; + pub const SET_SCORE: i32 = 112; + pub const SET_SIMULATION_DISTANCE: i32 = 113; + pub const SET_SUBTITLE_TEXT: i32 = 114; + pub const SET_TIME: i32 = 115; + pub const SET_TITLE_TEXT: i32 = 116; + pub const SET_TITLES_ANIMATION: i32 = 117; + pub const SOUND_ENTITY: i32 = 118; + pub const SOUND: i32 = 119; + pub const START_CONFIGURATION: i32 = 120; + pub const STOP_SOUND: i32 = 121; + pub const STORE_COOKIE: i32 = 122; + pub const SWING_ANIMATION: i32 = 123; + pub const SYSTEM_CHAT: i32 = 124; + pub const TAB_LIST: i32 = 125; + pub const TAG_QUERY: i32 = 126; + pub const TAKE_ITEM_ENTITY: i32 = 127; + pub const TELEPORT_ENTITY: i32 = 128; + pub const TEST_INSTANCE_BLOCK_STATUS: i32 = 129; + pub const TICKING_STATE: i32 = 130; + pub const TICKING_STEP: i32 = 131; + pub const TRANSFER: i32 = 132; + pub const UPDATE_ADVANCEMENTS: i32 = 133; + pub const UPDATE_ATTRIBUTES: i32 = 134; + pub const UPDATE_MOB_EFFECT: i32 = 135; + pub const UPDATE_RECIPES: i32 = 136; + pub const UPDATE_TAGS: i32 = 137; + pub const PROJECTILE_POWER: i32 = 138; + pub const CUSTOM_REPORT_DETAILS: i32 = 139; + pub const SERVER_LINKS: i32 = 140; + pub const WAYPOINT: i32 = 141; + pub const CLEAR_DIALOG: i32 = 142; + pub const SHOW_DIALOG: i32 = 143; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "bundle_delimiter", + "add_entity", + "animate", + "award_stats", + "block_changed_ack", + "block_destruction", + "block_entity_data", + "block_event", + "block_update", + "boss_event", + "change_difficulty", + "chunk_batch_finished", + "chunk_batch_start", + "chunks_biomes", + "clear_titles", + "command_suggestions", + "commands", + "container_close", + "container_set_content", + "container_set_data", + "container_set_slot", + "cookie_request", + "cooldown", + "custom_chat_completions", + "custom_payload", + "damage_event", + "debug/block_value", + "debug/chunk_value", + "debug/entity_value", + "debug/event", + "debug_sample", + "delete_chat", + "disconnect", + "disguised_chat", + "entity_event", + "entity_position_sync", + "explode", + "add_transient_block", + "forget_level_chunk", + "game_event", + "game_rule_values", + "game_test_highlight_pos", + "mount_screen_open", + "hurt_animation", + "initialize_border", + "keep_alive", + "level_chunk_with_light", + "level_event", + "level_particles", + "light_update", + "login", + "low_disk_space_warning", + "map_item_data", + "merchant_offers", + "move_entity_pos", + "move_entity_pos_rot", + "move_minecart_along_track", + "move_entity_rot", + "move_vehicle", + "open_book", + "open_screen", + "open_sign_editor", + "ping", + "pong_response", + "place_ghost_recipe", + "player_abilities", + "player_chat", + "player_combat_end", + "player_combat_enter", + "player_combat_kill", + "player_info_remove", + "player_info_update", + "player_look_at", + "player_position", + "player_rotation", + "recipe_book_add", + "recipe_book_remove", + "recipe_book_settings", + "remove_entities", + "remove_mob_effect", + "reset_score", + "resource_pack_pop", + "resource_pack_push", + "post_effects", + "respawn", + "rotate_head", + "section_blocks_update", + "select_advancements_tab", + "server_data", + "set_action_bar_text", + "set_border_center", + "set_border_lerp_size", + "set_border_size", + "set_border_warning_delay", + "set_border_warning_distance", + "set_camera", + "set_chunk_cache_center", + "set_chunk_cache_radius", + "set_cursor_item", + "set_default_spawn_position", + "set_display_objective", + "set_entity_data", + "set_entity_link", + "set_entity_motion", + "set_equipment", + "set_experience", + "set_health", + "set_held_slot", + "set_objective", + "set_passengers", + "set_player_inventory", + "set_player_team", + "set_score", + "set_simulation_distance", + "set_subtitle_text", + "set_time", + "set_title_text", + "set_titles_animation", + "sound_entity", + "sound", + "start_configuration", + "stop_sound", + "store_cookie", + "swing_animation", + "system_chat", + "tab_list", + "tag_query", + "take_item_entity", + "teleport_entity", + "test_instance_block_status", + "ticking_state", + "ticking_step", + "transfer", + "update_advancements", + "update_attributes", + "update_mob_effect", + "update_recipes", + "update_tags", + "projectile_power", + "custom_report_details", + "server_links", + "waypoint", + "clear_dialog", + "show_dialog", + ]; + } + pub mod serverbound { + pub const ACCEPT_TELEPORTATION: i32 = 0; + pub const ATTACK: i32 = 1; + pub const BLOCK_ENTITY_TAG_QUERY: i32 = 2; + pub const BUNDLE_ITEM_SELECTED: i32 = 3; + pub const CHANGE_DIFFICULTY: i32 = 4; + pub const CHANGE_GAME_MODE: i32 = 5; + pub const CHAT_ACK: i32 = 6; + pub const CHAT_COMMAND: i32 = 7; + pub const CHAT_COMMAND_SIGNED: i32 = 8; + pub const CHAT: i32 = 9; + pub const CHAT_SESSION_UPDATE: i32 = 10; + pub const CHUNK_BATCH_RECEIVED: i32 = 11; + pub const CLIENT_COMMAND: i32 = 12; + pub const CLIENT_TICK_END: i32 = 13; + pub const CLIENT_INFORMATION: i32 = 14; + pub const COMMAND_SUGGESTION: i32 = 15; + pub const CONFIGURATION_ACKNOWLEDGED: i32 = 16; + pub const CONTAINER_BUTTON_CLICK: i32 = 17; + pub const CONTAINER_CLICK: i32 = 18; + pub const CONTAINER_CLOSE: i32 = 19; + pub const CONTAINER_SLOT_STATE_CHANGED: i32 = 20; + pub const COOKIE_RESPONSE: i32 = 21; + pub const CUSTOM_PAYLOAD: i32 = 22; + pub const DEBUG_SUBSCRIPTION_REQUEST: i32 = 23; + pub const EDIT_BOOK: i32 = 24; + pub const ENTITY_TAG_QUERY: i32 = 25; + pub const INTERACT: i32 = 26; + pub const JIGSAW_GENERATE: i32 = 27; + pub const KEEP_ALIVE: i32 = 28; + pub const LOCK_DIFFICULTY: i32 = 29; + pub const MOVE_PLAYER_POS: i32 = 30; + pub const MOVE_PLAYER_POS_ROT: i32 = 31; + pub const MOVE_PLAYER_ROT: i32 = 32; + pub const MOVE_PLAYER_STATUS_ONLY: i32 = 33; + pub const MOVE_VEHICLE: i32 = 34; + pub const PADDLE_BOAT: i32 = 35; + pub const PICK_ITEM_FROM_BLOCK: i32 = 36; + pub const PICK_ITEM_FROM_ENTITY: i32 = 37; + pub const PING_REQUEST: i32 = 38; + pub const PLACE_RECIPE: i32 = 39; + pub const PLAYER_ABILITIES: i32 = 40; + pub const PLAYER_ACTION: i32 = 41; + pub const PLAYER_COMMAND: i32 = 42; + pub const PLAYER_INPUT: i32 = 43; + pub const PLAYER_LOADED: i32 = 44; + pub const PONG: i32 = 45; + pub const PUNCH: i32 = 46; + pub const RECIPE_BOOK_CHANGE_SETTINGS: i32 = 47; + pub const RECIPE_BOOK_SEEN_RECIPE: i32 = 48; + pub const RENAME_ITEM: i32 = 49; + pub const RESOURCE_PACK: i32 = 50; + pub const SEEN_ADVANCEMENTS: i32 = 51; + pub const SELECT_TRADE: i32 = 52; + pub const SET_BEACON: i32 = 53; + pub const SET_CARRIED_ITEM: i32 = 54; + pub const SET_COMMAND_BLOCK: i32 = 55; + pub const SET_COMMAND_MINECART: i32 = 56; + pub const SET_CREATIVE_MODE_SLOT: i32 = 57; + pub const SET_GAME_RULE: i32 = 58; + pub const SET_JIGSAW_BLOCK: i32 = 59; + pub const SET_STRUCTURE_BLOCK: i32 = 60; + pub const SET_TEST_BLOCK: i32 = 61; + pub const SIGN_UPDATE: i32 = 62; + pub const SPECTATOR_ACTION: i32 = 63; + pub const TELEPORT_TO_ENTITY: i32 = 64; + pub const TEST_INSTANCE_BLOCK_ACTION: i32 = 65; + pub const USE_ITEM_ON: i32 = 66; + pub const USE_ITEM: i32 = 67; + pub const CUSTOM_CLICK_ACTION: i32 = 68; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "accept_teleportation", + "attack", + "block_entity_tag_query", + "bundle_item_selected", + "change_difficulty", + "change_game_mode", + "chat_ack", + "chat_command", + "chat_command_signed", + "chat", + "chat_session_update", + "chunk_batch_received", + "client_command", + "client_tick_end", + "client_information", + "command_suggestion", + "configuration_acknowledged", + "container_button_click", + "container_click", + "container_close", + "container_slot_state_changed", + "cookie_response", + "custom_payload", + "debug_subscription_request", + "edit_book", + "entity_tag_query", + "interact", + "jigsaw_generate", + "keep_alive", + "lock_difficulty", + "move_player_pos", + "move_player_pos_rot", + "move_player_rot", + "move_player_status_only", + "move_vehicle", + "paddle_boat", + "pick_item_from_block", + "pick_item_from_entity", + "ping_request", + "place_recipe", + "player_abilities", + "player_action", + "player_command", + "player_input", + "player_loaded", + "pong", + "punch", + "recipe_book_change_settings", + "recipe_book_seen_recipe", + "rename_item", + "resource_pack", + "seen_advancements", + "select_trade", + "set_beacon", + "set_carried_item", + "set_command_block", + "set_command_minecart", + "set_creative_mode_slot", + "set_game_rule", + "set_jigsaw_block", + "set_structure_block", + "set_test_block", + "sign_update", + "spectator_action", + "teleport_to_entity", + "test_instance_block_action", + "use_item_on", + "use_item", + "custom_click_action", + ]; + } +} + +/// The packet name for an id, if the state and direction define it. +pub fn name(state: State, direction: Direction, id: i32) -> Option<&'static str> { + let names: &[&str] = match (state, direction) { + (State::Handshake, Direction::Serverbound) => handshake::serverbound::NAMES, + (State::Status, Direction::Clientbound) => status::clientbound::NAMES, + (State::Status, Direction::Serverbound) => status::serverbound::NAMES, + (State::Login, Direction::Clientbound) => login::clientbound::NAMES, + (State::Login, Direction::Serverbound) => login::serverbound::NAMES, + (State::Configuration, Direction::Clientbound) => configuration::clientbound::NAMES, + (State::Configuration, Direction::Serverbound) => configuration::serverbound::NAMES, + (State::Play, Direction::Clientbound) => play::clientbound::NAMES, + (State::Play, Direction::Serverbound) => play::serverbound::NAMES, + _ => &[], + }; + usize::try_from(id).ok().and_then(|i| names.get(i)).copied() +} diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs new file mode 100644 index 000000000..81d429865 --- /dev/null +++ b/crates/horizon-protocol/src/item.rs @@ -0,0 +1,337 @@ +//! Item stacks on the wire (ItemStack.OPTIONAL_STREAM_CODEC): a count, the +//! item's registry id and a data component patch, plus the hashed form the +//! client sends back in container clicks (HashedStack). +use crate::{ + Error, Result, + buf::{Codec, Reader, Writer}, +}; +use horizon_world::nbt::Tag; + +/// minecraft:data_component_type registry ids (26.3). +pub mod component { + pub const CUSTOM_DATA: i32 = 0; + pub const MAX_STACK_SIZE: i32 = 1; + pub const MAX_DAMAGE: i32 = 2; + pub const DAMAGE: i32 = 3; + pub const UNBREAKABLE: i32 = 4; + pub const CUSTOM_NAME: i32 = 6; + pub const ITEM_NAME: i32 = 9; + pub const ITEM_MODEL: i32 = 10; + pub const LORE: i32 = 11; + pub const RARITY: i32 = 12; + pub const ENCHANTMENTS: i32 = 13; + pub const CUSTOM_MODEL_DATA: i32 = 17; + pub const TOOLTIP_DISPLAY: i32 = 18; + pub const REPAIR_COST: i32 = 19; + pub const CREATIVE_SLOT_LOCK: i32 = 20; + pub const ENCHANTMENT_GLINT_OVERRIDE: i32 = 21; + pub const STORED_ENCHANTMENTS: i32 = 45; + pub const DYED_COLOR: i32 = 47; + pub const MAP_ID: i32 = 48; +} + +/// The value of one patched data component. Components whose stream codec +/// Horizon does not implement make the whole stack (and packet) undecodable. +#[derive(Clone, Debug, PartialEq)] +pub enum Component { + Int(i32), + Unit, + Bool(bool), + Text(Tag), + Nbt(Tag), + Ident(String), + Lore(Vec), + Enchantments(Vec<(i32, i32)>), + CustomModelData { + floats: Vec, + flags: Vec, + strings: Vec, + colors: Vec, + }, + TooltipDisplay { + hide: bool, + hidden: Vec, + }, +} +impl Component { + fn read(kind: i32, r: &mut Reader) -> Result { + use component::*; + Ok(match kind { + MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID => { + Self::Int(r.varint()?) + } + DYED_COLOR => Self::Int(r.i32()?), + UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, + ENCHANTMENT_GLINT_OVERRIDE => Self::Bool(r.bool()?), + CUSTOM_NAME | ITEM_NAME => Self::Text(r.nbt()?), + CUSTOM_DATA => Self::Nbt(r.nbt()?), + ITEM_MODEL => Self::Ident(r.string(32767)?), + LORE => { + let n = r.count(256)?; + Self::Lore((0..n).map(|_| r.nbt()).collect::>()?) + } + ENCHANTMENTS | STORED_ENCHANTMENTS => { + let n = r.count(r.remaining())?; + Self::Enchantments( + (0..n) + .map(|_| Ok((r.varint()?, r.varint()?))) + .collect::>()?, + ) + } + CUSTOM_MODEL_DATA => { + let n = r.count(r.remaining())?; + let floats = (0..n).map(|_| r.f32()).collect::>()?; + let n = r.count(r.remaining())?; + let flags = (0..n).map(|_| r.bool()).collect::>()?; + let n = r.count(r.remaining())?; + let strings = (0..n).map(|_| r.string(32767)).collect::>()?; + let n = r.count(r.remaining())?; + let colors = (0..n).map(|_| r.i32()).collect::>()?; + Self::CustomModelData { + floats, + flags, + strings, + colors, + } + } + TOOLTIP_DISPLAY => { + let hide = r.bool()?; + let n = r.count(r.remaining())?; + Self::TooltipDisplay { + hide, + hidden: (0..n).map(|_| r.varint()).collect::>()?, + } + } + other => return Err(Error::new(format!("unsupported item component {other}"))), + }) + } + fn write(&self, kind: i32, w: &mut Writer) { + match self { + Self::Int(v) if kind == component::DYED_COLOR => w.i32(*v), + Self::Int(v) => w.varint(*v), + Self::Unit => {} + Self::Bool(v) => w.bool(*v), + Self::Text(t) | Self::Nbt(t) => w.nbt(t), + Self::Ident(s) => w.string(s), + Self::Lore(lines) => { + w.varint(lines.len() as i32); + lines.iter().for_each(|l| w.nbt(l)); + } + Self::Enchantments(list) => { + w.varint(list.len() as i32); + for (e, level) in list { + w.varint(*e); + w.varint(*level); + } + } + Self::CustomModelData { + floats, + flags, + strings, + colors, + } => { + w.varint(floats.len() as i32); + floats.iter().for_each(|f| w.f32(*f)); + w.varint(flags.len() as i32); + flags.iter().for_each(|f| w.bool(*f)); + w.varint(strings.len() as i32); + strings.iter().for_each(|s| w.string(s)); + w.varint(colors.len() as i32); + colors.iter().for_each(|c| w.i32(*c)); + } + Self::TooltipDisplay { hide, hidden } => { + w.bool(*hide); + w.varint(hidden.len() as i32); + hidden.iter().for_each(|h| w.varint(*h)); + } + } + } +} + +/// A non-empty item stack. +#[derive(Clone, Debug, PartialEq)] +pub struct Stack { + pub item: i32, + pub count: i32, + pub added: Vec<(i32, Component)>, + pub removed: Vec, +} +impl Stack { + pub fn new(item: i32, count: i32) -> Self { + Self { + item, + count, + added: Vec::new(), + removed: Vec::new(), + } + } + pub fn component(&self, kind: i32) -> Option<&Component> { + self.added.iter().find(|(k, _)| *k == kind).map(|(_, c)| c) + } + pub fn damage(&self) -> i32 { + match self.component(component::DAMAGE) { + Some(Component::Int(d)) => *d, + _ => 0, + } + } +} +/// ItemStack.OPTIONAL_STREAM_CODEC: `None` is the empty stack (count 0). +pub struct Slot; +impl Codec> for Slot { + fn read(r: &mut Reader) -> Result> { + let count = r.varint()?; + if count <= 0 { + return Ok(None); + } + let item = r.varint()?; + let positive = r.count(65536)?; + let negative = r.count(65536)?; + let mut added = Vec::with_capacity(positive.min(64)); + for _ in 0..positive { + let kind = r.varint()?; + added.push((kind, Component::read(kind, r)?)); + } + let removed = (0..negative).map(|_| r.varint()).collect::>()?; + Ok(Some(Stack { + item, + count, + added, + removed, + })) + } + fn write(v: &Option, w: &mut Writer) { + let Some(s) = v else { + w.varint(0); + return; + }; + w.varint(s.count); + w.varint(s.item); + w.varint(s.added.len() as i32); + w.varint(s.removed.len() as i32); + for (kind, c) in &s.added { + w.varint(*kind); + c.write(*kind, w); + } + for kind in &s.removed { + w.varint(*kind); + } + } +} + +/// HashedStack: what the client believes a slot holds. Component values are +/// sent as hashes; Horizon sends patches without hashes, so a server whose +/// stack carries components resynchronises that slot (as it does for any +/// mismatched prediction). +#[derive(Clone, Debug, PartialEq)] +pub struct Hashed { + pub item: i32, + pub count: i32, + pub added: Vec<(i32, i32)>, + pub removed: Vec, +} +impl Hashed { + pub fn of(stack: &Stack) -> Self { + Self { + item: stack.item, + count: stack.count, + added: Vec::new(), + removed: stack.removed.clone(), + } + } +} +pub struct HashedSlot; +impl Codec> for HashedSlot { + fn read(r: &mut Reader) -> Result> { + if !r.bool()? { + return Ok(None); + } + let item = r.varint()?; + let count = r.varint()?; + let n = r.count(256)?; + let added = (0..n) + .map(|_| Ok((r.varint()?, r.i32()?))) + .collect::>()?; + let n = r.count(256)?; + let removed = (0..n).map(|_| r.varint()).collect::>()?; + Ok(Some(Hashed { + item, + count, + added, + removed, + })) + } + fn write(v: &Option, w: &mut Writer) { + w.bool(v.is_some()); + if let Some(h) = v { + w.varint(h.item); + w.varint(h.count); + w.varint(h.added.len() as i32); + for (k, hash) in &h.added { + w.varint(*k); + w.i32(*hash); + } + w.varint(h.removed.len() as i32); + for k in &h.removed { + w.varint(*k); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text::literal; + + fn round>(v: T) { + let mut w = Writer::new(); + C::write(&v, &mut w); + let mut r = Reader::new(&w.data); + assert_eq!(C::read(&mut r).unwrap(), v); + assert_eq!(r.remaining(), 0); + } + + #[test] + fn stacks_round_trip() { + round::, Slot>(None); + round::, Slot>(Some(Stack::new(42, 64))); + let mut sword = Stack::new(900, 1); + sword.added.push((component::DAMAGE, Component::Int(17))); + sword.added.push(( + component::CUSTOM_NAME, + Component::Text(literal("Excalibur")), + )); + sword.added.push(( + component::ENCHANTMENTS, + Component::Enchantments(vec![(5, 3), (12, 1)]), + )); + sword + .added + .push((component::DYED_COLOR, Component::Int(-6265536))); + sword.added.push(( + component::LORE, + Component::Lore(vec![literal("a"), literal("b")]), + )); + sword.removed.push(component::REPAIR_COST); + assert_eq!(sword.damage(), 17); + round::, Slot>(Some(sword.clone())); + round::, HashedSlot>(Some(Hashed::of(&sword))); + round::, HashedSlot>(None); + } + + #[test] + fn empty_stack_is_a_zero_count() { + let mut w = Writer::new(); + Slot::write(&None, &mut w); + assert_eq!(w.data, [0]); + let mut w = Writer::new(); + Slot::write(&Some(Stack::new(1, 2)), &mut w); + assert_eq!(w.data, [2, 1, 0, 0]); + } + + #[test] + fn unknown_components_are_errors() { + let bytes = [1, 5, 1, 0, 99]; + assert!(Slot::read(&mut Reader::new(&bytes)).is_err()); + } +} diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs new file mode 100644 index 000000000..1f29637dd --- /dev/null +++ b/crates/horizon-protocol/src/lib.rs @@ -0,0 +1,58 @@ +//! The Minecraft Java Edition 26.3 network protocol (protocol version 777): +//! primitive codecs, framing, compression, encryption, and typed packets for +//! every connection state, shared by the Horizon client and (later) server. +#![forbid(unsafe_code)] +pub mod buf; +pub mod chunk; +pub mod connection; +pub mod crypto; +pub mod entity_data; +pub mod frame; +pub mod ids; +pub mod item; +pub mod packets; +pub mod registry; +pub mod servers; +pub mod text; + +/// SharedConstants.getProtocolVersion() for 26.3. +pub const PROTOCOL_VERSION: i32 = 777; +/// The game version servers report in their status. +pub const GAME_VERSION: &str = "26.3"; + +/// Connection protocol states (ConnectionProtocol). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum State { + Handshake, + Status, + Login, + Configuration, + Play, +} +/// PacketFlow. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Direction { + Clientbound, + Serverbound, +} + +/// A malformed or unsupported packet. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Error(pub String); +impl Error { + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } +} +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for Error {} +impl From for Error { + fn from(e: std::io::Error) -> Self { + Self(e.to_string()) + } +} +pub type Result = std::result::Result; diff --git a/crates/horizon-protocol/src/packets/configuration.rs b/crates/horizon-protocol/src/packets/configuration.rs new file mode 100644 index 000000000..a767110eb --- /dev/null +++ b/crates/horizon-protocol/src/packets/configuration.rs @@ -0,0 +1,226 @@ +//! Configuration state: registries, tags, known packs, feature flags and the +//! common packets (keep-alive, ping, custom payloads, resource packs). +use crate::{ + Result, + buf::{ + Bool, Byte, Codec, Ident, Int, List, Long, Nbt, Opt, Reader, Rest, Str, StrN, UByte, Uuid, + VarInt, Writer, + }, + packet, packet_enum, + packets::Empty, +}; +use horizon_world::nbt::Tag; + +packet!(CookieRequest { key: String => Ident }); +packet!(CustomPayload { channel: String => Ident, data: Vec => Rest }); +packet!( + /// Common disconnect: a chat component (NBT). + Disconnect { reason: Tag => Nbt } +); +packet!(KeepAlive { id: i64 => Long }); +packet!(Ping { id: i32 => Int }); +packet!( + /// RegistrySynchronization.PackedRegistryEntry: data is absent when the + /// client already has the entry from a known pack. + RegistryEntry { id: String => Ident, data: Option => Opt } +); +packet!(RegistryData { registry: String => Ident, entries: Vec => List }); +packet!(ResourcePackPop { id: Option => Opt }); +packet!(ResourcePackPush { + id: u128 => Uuid, + url: String => Str, + hash: String => StrN<40>, + required: bool => Bool, + prompt: Option => Opt, +}); +packet!(StoreCookie { key: String => Ident, payload: Vec => crate::buf::Bytes }); +packet!(Transfer { host: String => Str, port: i32 => VarInt }); +packet!(UpdateEnabledFeatures { features: Vec => List }); +packet!(TagEntry { name: String => Ident, ids: Vec => List }); +packet!(RegistryTags { registry: String => Ident, tags: Vec => List }); +packet!( + /// ClientboundUpdateTagsPacket: tags per registry. + UpdateTags { registries: Vec => List } +); +packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str }); +packet!(SelectKnownPacks { packs: Vec => List }); +packet!(CodeOfConduct { text: String => Str }); + +packet_enum!(Clientbound, crate::ids::configuration::clientbound { + CookieRequest(CookieRequest) = COOKIE_REQUEST, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + Disconnect(Disconnect) = DISCONNECT, + FinishConfiguration(Empty) = FINISH_CONFIGURATION, + KeepAlive(KeepAlive) = KEEP_ALIVE, + Ping(Ping) = PING, + ResetChat(Empty) = RESET_CHAT, + RegistryData(RegistryData) = REGISTRY_DATA, + ResourcePackPop(ResourcePackPop) = RESOURCE_PACK_POP, + ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH, + StoreCookie(StoreCookie) = STORE_COOKIE, + Transfer(Transfer) = TRANSFER, + UpdateEnabledFeatures(UpdateEnabledFeatures) = UPDATE_ENABLED_FEATURES, + UpdateTags(UpdateTags) = UPDATE_TAGS, + SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS, + ClearDialog(Empty) = CLEAR_DIALOG, + CodeOfConduct(CodeOfConduct) = CODE_OF_CONDUCT, +}); + +/// ClientInformation. +#[derive(Clone, Debug, PartialEq)] +pub struct ClientInformation { + pub language: String, + pub view_distance: i8, + /// ChatVisiblity: 0 full, 1 system, 2 hidden. + pub chat_visibility: i32, + pub chat_colors: bool, + /// Skin layer bits (PlayerModelPart). + pub model_customisation: u8, + /// HumanoidArm: 0 left, 1 right. + pub main_hand: i32, + pub text_filtering: bool, + pub allows_listing: bool, + /// ParticleStatus: 0 all, 1 decreased, 2 minimal. + pub particle_status: i32, +} +impl ClientInformation { + /// ClientInformation.createDefault with a view distance. + pub fn new(view_distance: i8) -> Self { + Self { + language: "en_us".into(), + view_distance, + chat_visibility: 0, + chat_colors: true, + model_customisation: 0x7F, + main_hand: 1, + text_filtering: false, + allows_listing: true, + particle_status: 0, + } + } +} +impl Codec for ClientInformation { + fn read(r: &mut Reader) -> Result { + Ok(Self { + language: StrN::<16>::read(r)?, + view_distance: Byte::read(r)?, + chat_visibility: VarInt::read(r)?, + chat_colors: Bool::read(r)?, + model_customisation: UByte::read(r)?, + main_hand: VarInt::read(r)?, + text_filtering: Bool::read(r)?, + allows_listing: Bool::read(r)?, + particle_status: VarInt::read(r)?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.string(&v.language); + w.i8(v.view_distance); + w.varint(v.chat_visibility); + w.bool(v.chat_colors); + w.u8(v.model_customisation); + w.varint(v.main_hand); + w.bool(v.text_filtering); + w.bool(v.allows_listing); + w.varint(v.particle_status); + } +} +packet!(CookieResponse { key: String => Ident, payload: Option> => Opt }); +packet!( + /// ServerboundResourcePackPacket.Action: 0 loaded, 1 declined, 2 failed + /// download, 3 accepted, 4 downloaded, 5 invalid url, 6 failed reload, 7 discarded. + ResourcePackResponse { id: u128 => Uuid, action: i32 => VarInt } +); + +packet_enum!(Serverbound, crate::ids::configuration::serverbound { + ClientInformation(ClientInformation) = CLIENT_INFORMATION, + CookieResponse(CookieResponse) = COOKIE_RESPONSE, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + FinishConfiguration(Empty) = FINISH_CONFIGURATION, + KeepAlive(KeepAlive) = KEEP_ALIVE, + Pong(Ping) = PONG, + ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS, + AcceptCodeOfConduct(Empty) = ACCEPT_CODE_OF_CONDUCT, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::round_trip; + + #[test] + fn configuration_round_trips() { + let biome = Tag::compound([ + ("has_precipitation", Tag::Byte(1)), + ("temperature", Tag::Float(0.8f32.to_bits())), + ]); + for p in [ + Clientbound::CustomPayload(CustomPayload { + channel: "minecraft:brand".into(), + data: vec![7, b'v', b'a', b'n', b'i', b'l', b'l', b'a'], + }), + Clientbound::Disconnect(Disconnect { + reason: crate::text::literal("bye"), + }), + Clientbound::FinishConfiguration(Empty), + Clientbound::KeepAlive(KeepAlive { id: 99 }), + Clientbound::Ping(Ping { id: -3 }), + Clientbound::RegistryData(RegistryData { + registry: "minecraft:worldgen/biome".into(), + entries: vec![ + RegistryEntry { + id: "minecraft:plains".into(), + data: Some(biome), + }, + RegistryEntry { + id: "minecraft:desert".into(), + data: None, + }, + ], + }), + Clientbound::ResourcePackPush(ResourcePackPush { + id: 5, + url: "http://x".into(), + hash: String::new(), + required: false, + prompt: None, + }), + Clientbound::UpdateEnabledFeatures(UpdateEnabledFeatures { + features: vec!["minecraft:vanilla".into()], + }), + Clientbound::UpdateTags(UpdateTags { + registries: vec![RegistryTags { + registry: "minecraft:block".into(), + tags: vec![TagEntry { + name: "minecraft:logs".into(), + ids: vec![1, 2, 300], + }], + }], + }), + Clientbound::SelectKnownPacks(SelectKnownPacks { + packs: vec![KnownPack { + namespace: "minecraft".into(), + id: "core".into(), + version: "26.3".into(), + }], + }), + Clientbound::CodeOfConduct(CodeOfConduct { + text: "Be nice".into(), + }), + ] { + round_trip(p, Clientbound::encode, Clientbound::decode); + } + for p in [ + Serverbound::ClientInformation(ClientInformation::new(12)), + Serverbound::FinishConfiguration(Empty), + Serverbound::KeepAlive(KeepAlive { id: 99 }), + Serverbound::Pong(Ping { id: -3 }), + Serverbound::ResourcePack(ResourcePackResponse { id: 5, action: 1 }), + Serverbound::SelectKnownPacks(SelectKnownPacks { packs: vec![] }), + Serverbound::AcceptCodeOfConduct(Empty), + ] { + round_trip(p, Serverbound::encode, Serverbound::decode); + } + } +} diff --git a/crates/horizon-protocol/src/packets/handshake.rs b/crates/horizon-protocol/src/packets/handshake.rs new file mode 100644 index 000000000..1686adb23 --- /dev/null +++ b/crates/horizon-protocol/src/packets/handshake.rs @@ -0,0 +1,39 @@ +//! Handshake state: ClientIntentionPacket. +use crate::{ + buf::{StrN, UShort, VarInt}, + packet, packet_enum, +}; + +/// ClientIntent ids. +pub const STATUS: i32 = 1; +pub const LOGIN: i32 = 2; +pub const TRANSFER: i32 = 3; + +packet!(Intention { + protocol: i32 => VarInt, + host: String => StrN<255>, + port: u16 => UShort, + intent: i32 => VarInt, +}); + +packet_enum!(Serverbound, crate::ids::handshake::serverbound { Intention(Intention) = INTENTION }); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn intention_bytes() { + let p = Serverbound::Intention(Intention { + protocol: 777, + host: "localhost".into(), + port: 25565, + intent: LOGIN, + }); + let body = p.encode(); + assert_eq!(body[0], 0); + assert_eq!(&body[1..3], &[0x89, 0x06]); + assert_eq!(&body[body.len() - 3..], &[0x63, 0xdd, 2]); + crate::packets::round_trip(p, Serverbound::encode, Serverbound::decode); + } +} diff --git a/crates/horizon-protocol/src/packets/login.rs b/crates/horizon-protocol/src/packets/login.rs new file mode 100644 index 000000000..3e494a6a9 --- /dev/null +++ b/crates/horizon-protocol/src/packets/login.rs @@ -0,0 +1,134 @@ +//! Login state: offline/online hello, encryption request, compression, +//! login plugin queries and the finished game profile. +use crate::{ + buf::{Bool, Bytes, Ident, Opt, Rest, Str, StrN, Uuid, VarInt}, + packet, packet_enum, + packets::Empty, +}; + +packet!( + /// com.mojang.authlib.properties.Property. + Property { + name: String => StrN<64>, + value: String => Str, + signature: Option => Opt>, + } +); +packet!( + /// ByteBufCodecs.GAME_PROFILE. + GameProfile { + uuid: u128 => Uuid, + name: String => StrN<16>, + properties: Vec => crate::buf::List, + } +); +packet!(Disconnect { reason_json: String => StrN<262144> }); +packet!(Hello { + server_id: String => StrN<20>, + public_key: Vec => Bytes, + challenge: Vec => Bytes, + should_authenticate: bool => Bool, +}); +packet!(LoginFinished { profile: GameProfile => GameProfile, session: u128 => Uuid }); +packet!(Compression { threshold: i32 => VarInt }); +packet!(CustomQuery { transaction: i32 => VarInt, channel: String => Ident, data: Vec => Rest }); +packet!(CookieRequest { key: String => Ident }); + +packet_enum!(Clientbound, crate::ids::login::clientbound { + Disconnect(Disconnect) = LOGIN_DISCONNECT, + Hello(Hello) = HELLO, + LoginFinished(LoginFinished) = LOGIN_FINISHED, + Compression(Compression) = LOGIN_COMPRESSION, + CustomQuery(CustomQuery) = CUSTOM_QUERY, + CookieRequest(CookieRequest) = COOKIE_REQUEST, +}); + +packet!(ServerHello { name: String => StrN<16>, uuid: u128 => Uuid }); +packet!(Key { key: Vec => Bytes, challenge: Vec => Bytes }); +packet!(CustomQueryAnswer { transaction: i32 => VarInt, payload: Option> => Opt }); +packet!(CookieResponse { key: String => Ident, payload: Option> => Opt }); + +packet_enum!(Serverbound, crate::ids::login::serverbound { + Hello(ServerHello) = HELLO, + Key(Key) = KEY, + CustomQueryAnswer(CustomQueryAnswer) = CUSTOM_QUERY_ANSWER, + LoginAcknowledged(Empty) = LOGIN_ACKNOWLEDGED, + CookieResponse(CookieResponse) = COOKIE_RESPONSE, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::round_trip; + + #[test] + fn login_round_trips() { + let profile = GameProfile { + uuid: crate::crypto::offline_uuid("Horizon"), + name: "Horizon".into(), + properties: vec![Property { + name: "textures".into(), + value: "e30=".into(), + signature: None, + }], + }; + for p in [ + Clientbound::Disconnect(Disconnect { + reason_json: "{\"text\":\"bye\"}".into(), + }), + Clientbound::Hello(Hello { + server_id: String::new(), + public_key: vec![1, 2], + challenge: vec![3; 4], + should_authenticate: true, + }), + Clientbound::LoginFinished(LoginFinished { + profile, + session: 7, + }), + Clientbound::Compression(Compression { threshold: 256 }), + Clientbound::CustomQuery(CustomQuery { + transaction: 3, + channel: "velocity:player_info".into(), + data: vec![1], + }), + Clientbound::CookieRequest(CookieRequest { key: "a:b".into() }), + ] { + round_trip(p, Clientbound::encode, Clientbound::decode); + } + for p in [ + Serverbound::Hello(ServerHello { + name: "Horizon".into(), + uuid: 1, + }), + Serverbound::Key(Key { + key: vec![9; 128], + challenge: vec![8; 128], + }), + Serverbound::CustomQueryAnswer(CustomQueryAnswer { + transaction: 3, + payload: None, + }), + Serverbound::LoginAcknowledged(Empty), + Serverbound::CookieResponse(CookieResponse { + key: "a:b".into(), + payload: Some(vec![1]), + }), + ] { + round_trip(p, Serverbound::encode, Serverbound::decode); + } + } + + #[test] + fn rejects_trailing_bytes_and_long_names() { + let mut body = Serverbound::LoginAcknowledged(Empty).encode(); + body.push(0); + assert!(Serverbound::decode(3, &body[1..]).is_err()); + let long = Serverbound::Hello(ServerHello { + name: "x".repeat(17), + uuid: 0, + }) + .encode(); + assert!(Serverbound::decode(0, &long[1..]).is_err()); + } +} diff --git a/crates/horizon-protocol/src/packets/mod.rs b/crates/horizon-protocol/src/packets/mod.rs new file mode 100644 index 000000000..57c4f7f36 --- /dev/null +++ b/crates/horizon-protocol/src/packets/mod.rs @@ -0,0 +1,86 @@ +//! Typed packets per connection state and direction. Every state has a +//! `Clientbound` and a `Serverbound` enum whose `decode` checks that the +//! whole body was consumed (vanilla rejects oversized packets the same way) +//! and whose `encode` writes the id and payload. Packets Horizon does not +//! model decode as `Unknown` and keep their raw payload. +pub mod configuration; +pub mod handshake; +pub mod login; +pub mod play; +pub mod status; + +use crate::buf::{Codec, Reader, Writer}; + +/// Generate a state's packet enum from (Variant(Type) = ID) entries. +#[macro_export] +macro_rules! packet_enum { + ($(#[$meta:meta])* $name:ident, $ids:path { $($variant:ident($ty:ty) = $id:ident),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub enum $name { + $($variant($ty),)* + /// A packet Horizon does not model: id and raw payload. + Unknown(i32, Vec), + } + impl $name { + pub fn id(&self) -> i32 { + use $ids as ids; + match self { + $(Self::$variant(_) => ids::$id,)* + Self::Unknown(id, _) => *id, + } + } + /// Decode a packet body (after the id). + pub fn decode(id: i32, payload: &[u8]) -> $crate::Result { + use $ids as ids; + let mut r = $crate::buf::Reader::new(payload); + let packet = match id { + $(ids::$id => Self::$variant(<$ty as $crate::buf::Codec<$ty>>::read(&mut r)?),)* + _ => return Ok(Self::Unknown(id, payload.to_vec())), + }; + if r.remaining() != 0 { + return Err($crate::Error::new(format!( + "packet {} ({}) was larger than expected: {} extra bytes", + id, + stringify!($name), + r.remaining() + ))); + } + Ok(packet) + } + /// The packet body: VarInt id then payload. + pub fn encode(&self) -> Vec { + let mut w = $crate::buf::Writer::new(); + w.varint(self.id()); + match self { + $(Self::$variant(p) => <$ty as $crate::buf::Codec<$ty>>::write(p, &mut w),)* + Self::Unknown(_, payload) => w.bytes(payload), + } + w.data + } + } + }; +} + +/// A packet with no fields. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Empty; +impl Codec for Empty { + fn read(_: &mut Reader) -> crate::Result { + Ok(Empty) + } + fn write(_: &Empty, _: &mut Writer) {} +} + +#[cfg(test)] +pub(crate) fn round_trip( + packet: T, + encode: impl Fn(&T) -> Vec, + decode: impl Fn(i32, &[u8]) -> crate::Result, +) { + let body = encode(&packet); + let mut r = Reader::new(&body); + let id = r.varint().unwrap(); + let back = decode(id, r.rest()).unwrap(); + assert_eq!(back, packet); +} diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs new file mode 100644 index 000000000..f90370cf3 --- /dev/null +++ b/crates/horizon-protocol/src/packets/play.rs @@ -0,0 +1,1136 @@ +//! Play state packets: world, entities, player state, inventory and chat. +use crate::{ + Error, Result, + buf::{ + Bool, Byte, ChunkPos, Codec, Double, Float, Ident, Int, List, Long, LpVec3, Nbt, Opt, + OptVarInt, Pos, Reader, SectionPos, Short, Str, StrN, UByte, Uuid, VarInt, VarLong, Vec3d, + Writer, + }, + chunk::{ChunkData, LightData}, + entity_data::{EntityData, Value}, + item::{Hashed, HashedSlot, Slot, Stack}, + packet, packet_enum, + packets::{ + Empty, + configuration::{ + ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPush, + ResourcePackResponse, UpdateTags, + }, + login::Property, + }, +}; +use horizon_world::nbt::Tag; + +// ---- shared structures ------------------------------------------------- + +packet!( + /// GlobalPos: a dimension and a block position. + GlobalPos { dimension: String => Ident, pos: [i32; 3] => Pos } +); +packet!( + /// CommonPlayerSpawnInfo. + SpawnInfo { + dimension_type: i32 => VarInt, + dimension: String => Ident, + seed: i64 => Long, + game_type: i32 => VarInt, + previous_game_type: Option => OptVarInt, + debug: bool => Bool, + flat: bool => Bool, + last_death: Option => Opt, + portal_cooldown: i32 => VarInt, + sea_level: i32 => VarInt, + } +); + +/// Relative flags (Relative.pack): X, Y, Z, Y_ROT, X_ROT, DELTA_X/Y/Z, ROTATE_DELTA. +pub mod relative { + pub const X: i32 = 1; + pub const Y: i32 = 2; + pub const Z: i32 = 4; + pub const Y_ROT: i32 = 8; + pub const X_ROT: i32 = 16; + pub const DELTA_X: i32 = 32; + pub const DELTA_Y: i32 = 64; + pub const DELTA_Z: i32 = 128; + pub const ROTATE_DELTA: i32 = 256; +} + +// ---- clientbound ------------------------------------------------------- + +packet!(AddEntity { + id: i32 => VarInt, + uuid: u128 => Uuid, + kind: i32 => VarInt, + position: [f64; 3] => Vec3d, + velocity: [f64; 3] => LpVec3, + pitch: i8 => Byte, + yaw: i8 => Byte, + head_yaw: i8 => Byte, + data: i32 => VarInt, +}); +packet!(Animate { id: i32 => VarInt, action: u8 => UByte }); +packet!(BlockChangedAck { sequence: i32 => VarInt }); +packet!(BlockDestruction { id: i32 => VarInt, pos: [i32; 3] => Pos, progress: u8 => UByte }); +packet!(BlockEntityData { pos: [i32; 3] => Pos, kind: i32 => VarInt, tag: Tag => Nbt }); +packet!(BlockUpdate { pos: [i32; 3] => Pos, state: i32 => VarInt }); +packet!(ChangeDifficulty { difficulty: i32 => VarInt, locked: bool => Bool }); +packet!(ChunkBatchFinished { size: i32 => VarInt }); +packet!(ContainerClose { container: i32 => VarInt }); +packet!(ContainerSetContent { + container: i32 => VarInt, + state: i32 => VarInt, + items: Vec> => List, + carried: Option => Slot, +}); +packet!(ContainerSetData { container: i32 => VarInt, id: i16 => Short, value: i16 => Short }); +packet!(ContainerSetSlot { container: i32 => VarInt, state: i32 => VarInt, slot: i16 => Short, item: Option => Slot }); +/// A holder reference: registry id + 1, or 0 for an inline value (unsupported). +pub struct HolderId; +impl Codec for HolderId { + fn read(r: &mut Reader) -> Result { + match r.varint()? { + 0 => Err(Error::new("inline registry values are not supported")), + id => Ok(id - 1), + } + } + fn write(v: &i32, w: &mut Writer) { + w.varint(v + 1) + } +} +packet!( + /// ChatType.Bound. + ChatTypeBound { chat_type: i32 => HolderId, name: Tag => Nbt, target: Option => Opt } +); +packet!(DisguisedChat { message: Tag => Nbt, chat_type: ChatTypeBound => ChatTypeBound }); +packet!(EntityEvent { id: i32 => Int, event: i8 => Byte }); +/// PositionPath: Linear(end position) or Stepped(list of (position, tick offset)). +#[derive(Clone, Debug, PartialEq)] +pub enum PositionPath { + Linear([f64; 3]), + Stepped(Vec<([f64; 3], i32)>), +} +impl PositionPath { + pub fn end(&self) -> [f64; 3] { + match self { + Self::Linear(p) => *p, + Self::Stepped(steps) => steps.last().map_or([0.0; 3], |s| s.0), + } + } +} +impl Codec for PositionPath { + fn read(r: &mut Reader) -> Result { + Ok(match r.varint()? { + 1 => { + let n = r.count(r.remaining() / 25)?; + Self::Stepped( + (0..n) + .map(|_| Ok((Vec3d::read(r)?, r.varint()?))) + .collect::>()?, + ) + } + _ => Self::Linear(Vec3d::read(r)?), + }) + } + fn write(v: &Self, w: &mut Writer) { + match v { + Self::Linear(p) => { + w.varint(0); + Vec3d::write(p, w); + } + Self::Stepped(steps) => { + w.varint(1); + w.varint(steps.len() as i32); + for (p, t) in steps { + Vec3d::write(p, w); + w.varint(*t); + } + } + } + } +} +packet!(EntityPositionSync { id: i32 => VarInt, path: PositionPath => PositionPath, yaw: f32 => Float, pitch: f32 => Float, on_ground: bool => Bool }); +packet!(ForgetLevelChunk { pos: [i32; 2] => ChunkPos }); +packet!(GameEvent { event: u8 => UByte, param: f32 => Float }); +packet!(HurtAnimation { id: i32 => VarInt, yaw: f32 => Float }); +packet!(LevelChunkWithLight { x: i32 => Int, z: i32 => Int, chunk: ChunkData => ChunkData, light: LightData => LightData }); +packet!(LevelEvent { kind: i32 => Int, pos: [i32; 3] => Pos, data: i32 => Int, global: bool => Bool }); +packet!(LightUpdate { x: i32 => VarInt, z: i32 => VarInt, light: LightData => LightData }); +packet!(Login { + player_id: i32 => Int, + hardcore: bool => Bool, + levels: Vec => List, + max_players: i32 => VarInt, + chunk_radius: i32 => VarInt, + simulation_distance: i32 => VarInt, + reduced_debug_info: bool => Bool, + show_death_screen: bool => Bool, + limited_crafting: bool => Bool, + spawn: SpawnInfo => SpawnInfo, + online_mode: bool => Bool, + enforces_secure_chat: bool => Bool, +}); +/// VecDelta: per-axis deltas in 1/4096 blocks, linear or in timed steps. +#[derive(Clone, Debug, PartialEq)] +pub enum VecDelta { + Linear([i16; 3]), + Stepped(Vec<([i16; 3], i32)>), +} +impl VecDelta { + /// VecDeltaCodec.decode against a base position: zero deltas keep the + /// base coordinate exactly, others add to its 1/4096 quantization. + pub fn apply(base: [f64; 3], delta: [i16; 3]) -> [f64; 3] { + let mut out = base; + for i in 0..3 { + if delta[i] != 0 { + out[i] = ((base[i] * 4096.0).round() as i64 + i64::from(delta[i])) as f64 / 4096.0; + } + } + out + } + /// The final position after all steps. + pub fn end(&self, base: [f64; 3]) -> [f64; 3] { + match self { + Self::Linear(d) => Self::apply(base, *d), + Self::Stepped(steps) => steps.iter().fold(base, |p, (d, _)| Self::apply(p, *d)), + } + } + fn read(r: &mut Reader, steps: usize) -> Result { + if steps == 0 { + return Ok(Self::Linear([r.i16()?, r.i16()?, r.i16()?])); + } + if steps > r.remaining() / 7 { + return Err(Error::new("VecDelta with too many steps")); + } + Ok(Self::Stepped( + (0..steps) + .map(|_| { + let ticks = r.varint()?; + Ok(([r.i16()?, r.i16()?, r.i16()?], ticks)) + }) + .collect::>()?, + )) + } + fn steps(&self) -> usize { + match self { + Self::Linear(_) => 0, + Self::Stepped(s) => s.len(), + } + } + fn write(&self, w: &mut Writer) { + match self { + Self::Linear(d) => d.iter().for_each(|v| w.i16(*v)), + Self::Stepped(steps) => { + for (d, ticks) in steps { + w.varint(*ticks); + d.iter().for_each(|v| w.i16(*v)); + } + } + } + } +} +/// ClientboundMoveEntityPacket.Pos / PosRot / Rot. +#[derive(Clone, Debug, PartialEq)] +pub struct MoveEntity { + pub id: i32, + pub delta: Option, + pub rotation: Option<(i8, i8)>, + pub on_ground: bool, +} +macro_rules! move_entity { + ($name:ident, pos: $pos:expr, rot: $rot:expr) => { + #[derive(Clone, Debug, PartialEq)] + pub struct $name(pub MoveEntity); + impl Codec<$name> for $name { + fn read(r: &mut Reader) -> Result<$name> { + Self::read_inner(r).map($name) + } + fn write(v: &$name, w: &mut Writer) { + Self::write_inner(&v.0, w) + } + } + impl $name { + fn read_inner(r: &mut Reader) -> Result { + let id = r.varint()?; + if !$pos { + let on_ground = r.bool()?; + let rotation = Some((r.i8()?, r.i8()?)); + return Ok(MoveEntity { + id, + delta: None, + rotation, + on_ground, + }); + } + let properties = r.varint()?; + let delta = Some(VecDelta::read(r, (properties as u32 >> 1) as usize)?); + let rotation = if $rot { Some((r.i8()?, r.i8()?)) } else { None }; + Ok(MoveEntity { + id, + delta, + rotation, + on_ground: properties & 1 != 0, + }) + } + fn write_inner(v: &MoveEntity, w: &mut Writer) { + w.varint(v.id); + if !$pos { + w.bool(v.on_ground); + } else { + let delta = v.delta.clone().unwrap_or(VecDelta::Linear([0; 3])); + w.varint(i32::from(v.on_ground) | (delta.steps() as i32) << 1); + delta.write(w); + } + if let Some((y, x)) = v.rotation.filter(|_| $rot) { + w.i8(y); + w.i8(x); + } + } + } + }; +} +move_entity!(MoveEntityPos, pos: true, rot: false); +move_entity!(MoveEntityPosRot, pos: true, rot: true); +move_entity!(MoveEntityRot, pos: false, rot: true); +packet!(OpenScreen { container: i32 => VarInt, menu: i32 => VarInt, title: Tag => Nbt }); +packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); +/// MessageSignature.Packed: an index into the last-seen cache or a full signature. +pub struct PackedSignature; +impl Codec<(i32, Option>)> for PackedSignature { + fn read(r: &mut Reader) -> Result<(i32, Option>)> { + let id = r.varint()? - 1; + Ok(if id == -1 { + (-1, Some(r.bytes(256)?.to_vec())) + } else { + (id, None) + }) + } + fn write(v: &(i32, Option>), w: &mut Writer) { + w.varint(v.0 + 1); + if let Some(sig) = &v.1 { + w.bytes(sig); + } + } +} +/// MessageSignature: 256 raw bytes. +pub struct Signature; +impl Codec> for Signature { + fn read(r: &mut Reader) -> Result> { + Ok(r.bytes(256)?.to_vec()) + } + fn write(v: &Vec, w: &mut Writer) { + w.bytes(v) + } +} +/// FilterMask: 0 pass-through, 1 fully filtered, 2 partially (with a BitSet). +pub struct FilterMask; +impl Codec<(i32, Vec)> for FilterMask { + fn read(r: &mut Reader) -> Result<(i32, Vec)> { + let kind = r.varint()?; + Ok(( + kind, + if kind == 2 { + r.long_array()? + } else { + Vec::new() + }, + )) + } + fn write(v: &(i32, Vec), w: &mut Writer) { + w.varint(v.0); + if v.0 == 2 { + w.long_array(&v.1); + } + } +} +packet!(PlayerChat { + global_index: i32 => VarInt, + sender: u128 => Uuid, + index: i32 => VarInt, + signature: Option> => Opt, + content: String => StrN<256>, + timestamp: i64 => Long, + salt: i64 => Long, + last_seen: Vec<(i32, Option>)> => List, + unsigned_content: Option => Opt, + filter: (i32, Vec) => FilterMask, + chat_type: ChatTypeBound => ChatTypeBound, +}); +packet!(PlayerCombatKill { id: i32 => VarInt, message: Tag => Nbt }); +packet!(PlayerInfoRemove { uuids: Vec => List }); +/// One ClientboundPlayerInfoUpdatePacket entry; fields are set for the +/// actions in the packet. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PlayerInfo { + pub uuid: u128, + pub name: Option, + pub properties: Vec, + /// RemoteChatSession.Data: session id, key expiry, key, key signature. + pub chat_session: Option<(u128, i64, Vec, Vec)>, + pub game_mode: Option, + pub listed: Option, + pub latency: Option, + pub display_name: Option>, + pub list_order: Option, + pub show_hat: Option, +} +/// Actions bits: ADD_PLAYER, INITIALIZE_CHAT, UPDATE_GAME_MODE, UPDATE_LISTED, +/// UPDATE_LATENCY, UPDATE_DISPLAY_NAME, UPDATE_LIST_ORDER, UPDATE_HAT. +#[derive(Clone, Debug, PartialEq)] +pub struct PlayerInfoUpdate { + pub actions: u8, + pub entries: Vec, +} +impl Codec for PlayerInfoUpdate { + fn read(r: &mut Reader) -> Result { + let actions = r.u8()?; + let n = r.count(r.remaining())?; + let mut entries = Vec::with_capacity(n.min(256)); + for _ in 0..n { + let mut e = PlayerInfo { + uuid: r.uuid()?, + ..PlayerInfo::default() + }; + if actions & 1 != 0 { + e.name = Some(r.string(16)?); + let count = r.count(16)?; + e.properties = (0..count) + .map(|_| Property::read(r)) + .collect::>()?; + } + if actions & 2 != 0 && r.bool()? { + e.chat_session = + Some((r.uuid()?, r.i64()?, r.byte_array(512)?, r.byte_array(4096)?)); + } + if actions & 4 != 0 { + e.game_mode = Some(r.varint()?); + } + if actions & 8 != 0 { + e.listed = Some(r.bool()?); + } + if actions & 16 != 0 { + e.latency = Some(r.varint()?); + } + if actions & 32 != 0 { + e.display_name = Some(if r.bool()? { Some(r.nbt()?) } else { None }); + } + if actions & 64 != 0 { + e.list_order = Some(r.varint()?); + } + if actions & 128 != 0 { + e.show_hat = Some(r.bool()?); + } + entries.push(e); + } + Ok(Self { actions, entries }) + } + fn write(v: &Self, w: &mut Writer) { + w.u8(v.actions); + w.varint(v.entries.len() as i32); + for e in &v.entries { + w.uuid(e.uuid); + if v.actions & 1 != 0 { + w.string(e.name.as_deref().unwrap_or("")); + w.varint(e.properties.len() as i32); + e.properties.iter().for_each(|p| Property::write(p, w)); + } + if v.actions & 2 != 0 { + w.bool(e.chat_session.is_some()); + if let Some((id, expires, key, sig)) = &e.chat_session { + w.uuid(*id); + w.i64(*expires); + w.byte_array(key); + w.byte_array(sig); + } + } + if v.actions & 4 != 0 { + w.varint(e.game_mode.unwrap_or(0)); + } + if v.actions & 8 != 0 { + w.bool(e.listed.unwrap_or(false)); + } + if v.actions & 16 != 0 { + w.varint(e.latency.unwrap_or(0)); + } + if v.actions & 32 != 0 { + let name = e.display_name.clone().flatten(); + w.bool(name.is_some()); + if let Some(t) = &name { + w.nbt(t); + } + } + if v.actions & 64 != 0 { + w.varint(e.list_order.unwrap_or(0)); + } + if v.actions & 128 != 0 { + w.bool(e.show_hat.unwrap_or(false)); + } + } + } +} +packet!(PlayerPosition { + teleport: i32 => VarInt, + position: [f64; 3] => Vec3d, + delta: [f64; 3] => Vec3d, + yaw: f32 => Float, + pitch: f32 => Float, + relatives: i32 => Int, +}); +packet!(PlayerRotation { yaw: f32 => Float, relative_yaw: bool => Bool, pitch: f32 => Float, relative_pitch: bool => Bool }); +packet!(RemoveEntities { ids: Vec => List }); +packet!(Respawn { spawn: SpawnInfo => SpawnInfo, keep: i8 => Byte }); +packet!(RotateHead { id: i32 => VarInt, head_yaw: i8 => Byte }); +packet!( + /// Each change is `state << 12 | x << 8 | z << 4 | y` within the section. + SectionBlocksUpdate { section: [i32; 3] => SectionPos, changes: Vec => List } +); +packet!(Text { text: Tag => Nbt }); +packet!(SetChunkCacheCenter { x: i32 => VarInt, z: i32 => VarInt }); +packet!(Distance { distance: i32 => VarInt }); +packet!(SetCursorItem { item: Option => Slot }); +packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); +packet!(SetEntityData { id: i32 => VarInt, values: Vec<(u8, i32, Value)> => EntityData }); +packet!(SetEntityMotion { id: i32 => VarInt, velocity: [f64; 3] => LpVec3 }); +/// ClientboundSetEquipmentPacket: (EquipmentSlot ordinal, stack) pairs. +pub struct Equipment; +impl Codec)>> for Equipment { + fn read(r: &mut Reader) -> Result)>> { + let mut out = Vec::new(); + loop { + let slot = r.u8()?; + out.push((slot & 127, Slot::read(r)?)); + if slot & 128 == 0 { + return Ok(out); + } + } + } + fn write(v: &Vec<(u8, Option)>, w: &mut Writer) { + for (i, (slot, stack)) in v.iter().enumerate() { + w.u8(if i + 1 < v.len() { slot | 128 } else { *slot }); + Slot::write(stack, w); + } + } +} +packet!(SetEquipment { id: i32 => VarInt, slots: Vec<(u8, Option)> => Equipment }); +packet!(SetExperience { progress: f32 => Float, level: i32 => VarInt, total: i32 => VarInt }); +packet!(SetHealth { health: f32 => Float, food: i32 => VarInt, saturation: f32 => Float }); +packet!(SetHeldSlot { slot: i32 => VarInt }); +packet!(SetPlayerInventory { slot: i32 => VarInt, item: Option => Slot }); +packet!( + /// ClockNetworkState for one world clock (registry id). + ClockState { clock: i32 => VarInt, total_ticks: i64 => VarLong, partial_tick: f32 => Float, rate: f32 => Float } +); +packet!(SetTime { game_time: i64 => Long, clocks: Vec => List }); +packet!(TitlesAnimation { fade_in: i32 => Int, stay: i32 => Int, fade_out: i32 => Int }); +/// SoundEvent holder: a registry id, or an inline location with optional range. +pub struct SoundHolder; +impl Codec<(i32, Option<(String, Option)>)> for SoundHolder { + fn read(r: &mut Reader) -> Result<(i32, Option<(String, Option)>)> { + let id = r.varint()?; + if id != 0 { + return Ok((id - 1, None)); + } + let location = r.string(32767)?; + let range = if r.bool()? { Some(r.f32()?) } else { None }; + Ok((-1, Some((location, range)))) + } + fn write(v: &(i32, Option<(String, Option)>), w: &mut Writer) { + match &v.1 { + None => w.varint(v.0 + 1), + Some((location, range)) => { + w.varint(0); + w.string(location); + as Codec>>::write(range, w); + } + } + } +} +packet!(Sound { + sound: (i32, Option<(String, Option)>) => SoundHolder, + source: i32 => VarInt, + x: i32 => Int, + y: i32 => Int, + z: i32 => Int, + volume: f32 => Float, + pitch: f32 => Float, + seed: i64 => Long, +}); +packet!(SystemChat { content: Tag => Nbt, overlay: bool => Bool }); +packet!(TakeItemEntity { item: i32 => VarInt, player: i32 => VarInt, amount: i32 => VarInt }); +packet!(TeleportEntity { + id: i32 => VarInt, + position: [f64; 3] => Vec3d, + delta: [f64; 3] => Vec3d, + yaw: f32 => Float, + pitch: f32 => Float, + relatives: i32 => Int, + on_ground: bool => Bool, +}); + +packet_enum!(Clientbound, crate::ids::play::clientbound { + BundleDelimiter(Empty) = BUNDLE_DELIMITER, + AddEntity(AddEntity) = ADD_ENTITY, + Animate(Animate) = ANIMATE, + BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK, + BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION, + BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA, + BlockUpdate(BlockUpdate) = BLOCK_UPDATE, + ChangeDifficulty(ChangeDifficulty) = CHANGE_DIFFICULTY, + ChunkBatchFinished(ChunkBatchFinished) = CHUNK_BATCH_FINISHED, + ChunkBatchStart(Empty) = CHUNK_BATCH_START, + ClearTitles(Bool1) = CLEAR_TITLES, + ContainerClose(ContainerClose) = CONTAINER_CLOSE, + ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT, + ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA, + ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + Disconnect(Disconnect) = DISCONNECT, + DisguisedChat(DisguisedChat) = DISGUISED_CHAT, + EntityEvent(EntityEvent) = ENTITY_EVENT, + EntityPositionSync(EntityPositionSync) = ENTITY_POSITION_SYNC, + ForgetLevelChunk(ForgetLevelChunk) = FORGET_LEVEL_CHUNK, + GameEvent(GameEvent) = GAME_EVENT, + HurtAnimation(HurtAnimation) = HURT_ANIMATION, + KeepAlive(KeepAlive) = KEEP_ALIVE, + LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT, + LevelEvent(LevelEvent) = LEVEL_EVENT, + LightUpdate(LightUpdate) = LIGHT_UPDATE, + Login(Login) = LOGIN, + MoveEntityPos(MoveEntityPos) = MOVE_ENTITY_POS, + MoveEntityPosRot(MoveEntityPosRot) = MOVE_ENTITY_POS_ROT, + MoveEntityRot(MoveEntityRot) = MOVE_ENTITY_ROT, + OpenScreen(OpenScreen) = OPEN_SCREEN, + Ping(Ping) = PING, + PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, + PlayerChat(PlayerChat) = PLAYER_CHAT, + PlayerCombatKill(PlayerCombatKill) = PLAYER_COMBAT_KILL, + PlayerInfoRemove(PlayerInfoRemove) = PLAYER_INFO_REMOVE, + PlayerInfoUpdate(PlayerInfoUpdate) = PLAYER_INFO_UPDATE, + PlayerPosition(PlayerPosition) = PLAYER_POSITION, + PlayerRotation(PlayerRotation) = PLAYER_ROTATION, + RemoveEntities(RemoveEntities) = REMOVE_ENTITIES, + ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH, + Respawn(Respawn) = RESPAWN, + RotateHead(RotateHead) = ROTATE_HEAD, + SectionBlocksUpdate(SectionBlocksUpdate) = SECTION_BLOCKS_UPDATE, + SetActionBarText(Text) = SET_ACTION_BAR_TEXT, + SetChunkCacheCenter(SetChunkCacheCenter) = SET_CHUNK_CACHE_CENTER, + SetChunkCacheRadius(Distance) = SET_CHUNK_CACHE_RADIUS, + SetCursorItem(SetCursorItem) = SET_CURSOR_ITEM, + SetDefaultSpawnPosition(SetDefaultSpawnPosition) = SET_DEFAULT_SPAWN_POSITION, + SetEntityData(SetEntityData) = SET_ENTITY_DATA, + SetEntityMotion(SetEntityMotion) = SET_ENTITY_MOTION, + SetEquipment(SetEquipment) = SET_EQUIPMENT, + SetExperience(SetExperience) = SET_EXPERIENCE, + SetHealth(SetHealth) = SET_HEALTH, + SetHeldSlot(SetHeldSlot) = SET_HELD_SLOT, + SetPlayerInventory(SetPlayerInventory) = SET_PLAYER_INVENTORY, + SetSimulationDistance(Distance) = SET_SIMULATION_DISTANCE, + SetSubtitleText(Text) = SET_SUBTITLE_TEXT, + SetTime(SetTime) = SET_TIME, + SetTitleText(Text) = SET_TITLE_TEXT, + SetTitlesAnimation(TitlesAnimation) = SET_TITLES_ANIMATION, + Sound(Sound) = SOUND, + StartConfiguration(Empty) = START_CONFIGURATION, + SystemChat(SystemChat) = SYSTEM_CHAT, + TakeItemEntity(TakeItemEntity) = TAKE_ITEM_ENTITY, + TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, + UpdateTags(UpdateTags) = UPDATE_TAGS, +}); +packet!( + /// ClientboundClearTitlesPacket: whether to also reset the timings. + Bool1 { value: bool => Bool } +); + +// ---- serverbound ------------------------------------------------------- + +packet!(AcceptTeleportation { id: i32 => VarInt, x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float }); +packet!(Attack { id: i32 => VarInt }); +packet!(LastSeenUpdate { offset: i32 => VarInt, acknowledged: [u8; 3] => Fixed3, checksum: i8 => Byte }); +/// LastSeenMessages.Update's fixed 20-bit BitSet (3 bytes). +pub struct Fixed3; +impl Codec<[u8; 3]> for Fixed3 { + fn read(r: &mut Reader) -> Result<[u8; 3]> { + Ok(r.bytes(3)?.try_into().expect("3 bytes")) + } + fn write(v: &[u8; 3], w: &mut Writer) { + w.bytes(v) + } +} +packet!(Chat { + message: String => StrN<256>, + timestamp: i64 => Long, + salt: i64 => Long, + signature: Option> => Opt, + last_seen: LastSeenUpdate => LastSeenUpdate, +}); +packet!(ChatCommand { command: String => Str }); +packet!(ChunkBatchReceived { chunks_per_tick: f32 => Float }); +packet!( + /// ServerboundClientCommandPacket.Action: 0 respawn, 1 request stats, 2 request game rules. + ClientCommand { action: i32 => VarInt } +); +/// Changed slots: (slot, hashed stack) pairs. +pub struct ChangedSlots; +impl Codec)>> for ChangedSlots { + fn read(r: &mut Reader) -> Result)>> { + let n = r.count(128)?; + (0..n) + .map(|_| Ok((r.i16()?, HashedSlot::read(r)?))) + .collect() + } + fn write(v: &Vec<(i16, Option)>, w: &mut Writer) { + w.varint(v.len() as i32); + for (slot, h) in v { + w.i16(*slot); + HashedSlot::write(h, w); + } + } +} +packet!( + /// ContainerInput: 0 pickup, 1 quick move, 2 swap, 3 clone, 4 throw, 5 quick craft, 6 pickup all. + ContainerClick { + container: i32 => VarInt, + state: i32 => VarInt, + slot: i16 => Short, + button: i8 => Byte, + input: i32 => VarInt, + changed: Vec<(i16, Option)> => ChangedSlots, + carried: Option => HashedSlot, + } +); +packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); +packet!( + /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. + MovePlayerPos { x: f64 => Double, y: f64 => Double, z: f64 => Double, flags: u8 => UByte } +); +packet!(MovePlayerPosRot { x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float, flags: u8 => UByte }); +packet!(MovePlayerRot { yaw: f32 => Float, pitch: f32 => Float, flags: u8 => UByte }); +packet!(MovePlayerStatus { flags: u8 => UByte }); +packet!(PickItemFromBlock { pos: [i32; 3] => Pos, include_data: bool => Bool }); +packet!( + /// ServerboundPlayerActionPacket.Action: 0 start destroy, 1 change destroy + /// direction, 2 abort, 3 stop destroy, 4 drop all, 5 drop item, 6 release + /// use item, 7 swap offhand, 8 stab. Direction is the 3D data value. + PlayerAction { action: i32 => VarInt, pos: [i32; 3] => Pos, direction: u8 => UByte, sequence: i32 => VarInt } +); +packet!( + /// ServerboundPlayerCommandPacket.Action: 0 stop sleeping, 1 start sprinting, + /// 2 stop sprinting, 3/4 riding jump, 5 open inventory, 6 start fall flying. + PlayerCommand { id: i32 => VarInt, action: i32 => VarInt, data: i32 => VarInt } +); +packet!( + /// Input flags: forward 1, backward 2, left 4, right 8, jump 16, shift 32, sprint 64. + PlayerInput { flags: u8 => UByte } +); +packet!(SetCarriedItem { slot: i16 => Short }); +packet!(SetCreativeModeSlot { slot: i16 => Short, item: Option => Slot }); +packet!(UseItem { hand: i32 => VarInt, sequence: i32 => VarInt, yaw: f32 => Float, pitch: f32 => Float }); +packet!(UseItemOn { + hand: i32 => VarInt, + pos: [i32; 3] => Pos, + face: i32 => VarInt, + cursor: [f32; 3] => Cursor, + inside: bool => Bool, + world_border: bool => Bool, + sequence: i32 => VarInt, +}); +/// The click location relative to the block (three floats). +pub struct Cursor; +impl Codec<[f32; 3]> for Cursor { + fn read(r: &mut Reader) -> Result<[f32; 3]> { + Ok([r.f32()?, r.f32()?, r.f32()?]) + } + fn write(v: &[f32; 3], w: &mut Writer) { + v.iter().for_each(|f| w.f32(*f)); + } +} + +packet_enum!(Serverbound, crate::ids::play::serverbound { + AcceptTeleportation(AcceptTeleportation) = ACCEPT_TELEPORTATION, + Attack(Attack) = ATTACK, + Chat(Chat) = CHAT, + ChatCommand(ChatCommand) = CHAT_COMMAND, + ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, + ClientCommand(ClientCommand) = CLIENT_COMMAND, + ClientInformation(ClientInformation) = CLIENT_INFORMATION, + ClientTickEnd(Empty) = CLIENT_TICK_END, + ConfigurationAcknowledged(Empty) = CONFIGURATION_ACKNOWLEDGED, + ContainerClick(ContainerClick) = CONTAINER_CLICK, + ContainerClose(ContainerClose) = CONTAINER_CLOSE, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + Interact(Interact) = INTERACT, + KeepAlive(KeepAlive) = KEEP_ALIVE, + MovePlayerPos(MovePlayerPos) = MOVE_PLAYER_POS, + MovePlayerPosRot(MovePlayerPosRot) = MOVE_PLAYER_POS_ROT, + MovePlayerRot(MovePlayerRot) = MOVE_PLAYER_ROT, + MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY, + PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK, + PlayerAction(PlayerAction) = PLAYER_ACTION, + PlayerCommand(PlayerCommand) = PLAYER_COMMAND, + PlayerInput(PlayerInput) = PLAYER_INPUT, + PlayerLoaded(Empty) = PLAYER_LOADED, + Pong(Ping) = PONG, + Punch(Empty) = PUNCH, + ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, + SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, + UseItem(UseItem) = USE_ITEM, + UseItemOn(UseItemOn) = USE_ITEM_ON, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal}; + + fn spawn() -> SpawnInfo { + SpawnInfo { + dimension_type: 0, + dimension: "minecraft:overworld".into(), + seed: -123, + game_type: 0, + previous_game_type: None, + debug: false, + flat: false, + last_death: Some(GlobalPos { + dimension: "minecraft:the_nether".into(), + pos: [1, 2, 3], + }), + portal_cooldown: 0, + sea_level: 63, + } + } + + #[test] + fn clientbound_round_trips() { + let packets = vec![ + Clientbound::BundleDelimiter(Empty), + Clientbound::AddEntity(AddEntity { + id: 5, + uuid: 9, + kind: 100, + position: [1.5, 64.0, -3.25], + velocity: [0.0; 3], + pitch: 0, + yaw: 64, + head_yaw: 64, + data: 0, + }), + Clientbound::BlockUpdate(BlockUpdate { + pos: [-5, -60, 7], + state: 1, + }), + Clientbound::ContainerSetContent(ContainerSetContent { + container: 0, + state: 3, + items: vec![None, Some(Stack::new(1, 64))], + carried: None, + }), + Clientbound::ContainerSetSlot(ContainerSetSlot { + container: 0, + state: 4, + slot: 36, + item: Some(Stack::new(2, 1)), + }), + Clientbound::Disconnect(Disconnect { + reason: literal("kicked"), + }), + Clientbound::EntityPositionSync(EntityPositionSync { + id: 1, + path: PositionPath::Stepped(vec![([1.0, 2.0, 3.0], 0), ([1.5, 2.0, 3.0], 2)]), + yaw: 1.0, + pitch: 2.0, + on_ground: true, + }), + Clientbound::ForgetLevelChunk(ForgetLevelChunk { pos: [-1, 2] }), + Clientbound::GameEvent(GameEvent { + event: 13, + param: 0.0, + }), + Clientbound::LevelChunkWithLight(LevelChunkWithLight { + x: 3, + z: -4, + chunk: ChunkData { + heightmaps: vec![(4, vec![0; 37])], + buffer: vec![0, 0, 0, 0, 0, 0, 0, 0], + block_entities: vec![BlockEntityInfo { + packed_xz: 1, + y: 70, + kind: 3, + tag: Tag::End, + }], + }, + light: LightData { + sky_mask: vec![1], + block_mask: vec![], + empty_sky_mask: vec![], + empty_block_mask: vec![2], + sky: vec![vec![0xFF; 2048]], + block: vec![], + }, + }), + Clientbound::Login(Login { + player_id: 42, + hardcore: false, + levels: vec!["minecraft:overworld".into(), "minecraft:the_nether".into()], + max_players: 20, + chunk_radius: 10, + simulation_distance: 10, + reduced_debug_info: false, + show_death_screen: true, + limited_crafting: false, + spawn: spawn(), + online_mode: false, + enforces_secure_chat: false, + }), + Clientbound::MoveEntityPos(MoveEntityPos(MoveEntity { + id: 3, + delta: Some(VecDelta::Linear([4096, 0, -4096])), + rotation: None, + on_ground: true, + })), + Clientbound::MoveEntityPosRot(MoveEntityPosRot(MoveEntity { + id: 3, + delta: Some(VecDelta::Stepped(vec![([1, 2, 3], 1), ([0, 0, 1], 2)])), + rotation: Some((10, -10)), + on_ground: false, + })), + Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { + id: 3, + delta: None, + rotation: Some((1, 2)), + on_ground: true, + })), + Clientbound::OpenScreen(OpenScreen { + container: 1, + menu: 2, + title: literal("Chest"), + }), + Clientbound::PlayerChat(PlayerChat { + global_index: 0, + sender: 5, + index: 0, + signature: None, + content: "hello".into(), + timestamp: 1, + salt: 2, + last_seen: vec![(3, None), (-1, Some(vec![7; 256]))], + unsigned_content: None, + filter: (0, vec![]), + chat_type: ChatTypeBound { + chat_type: 0, + name: literal("Steve"), + target: None, + }, + }), + Clientbound::PlayerInfoUpdate(PlayerInfoUpdate { + actions: 0b0001_1101, + entries: vec![PlayerInfo { + uuid: 1, + name: Some("Steve".into()), + game_mode: Some(1), + listed: Some(true), + latency: Some(12), + ..PlayerInfo::default() + }], + }), + Clientbound::PlayerPosition(PlayerPosition { + teleport: 1, + position: [0.5, 70.0, 0.5], + delta: [0.0; 3], + yaw: 90.0, + pitch: 0.0, + relatives: relative::DELTA_X, + }), + Clientbound::Respawn(Respawn { + spawn: spawn(), + keep: 3, + }), + Clientbound::SectionBlocksUpdate(SectionBlocksUpdate { + section: [1, -4, 2], + changes: vec![(9 << 12) | 0x123], + }), + Clientbound::SetEntityData(SetEntityData { + id: 2, + values: vec![(8, 7, Value::Item(Some(Stack::new(5, 3))))], + }), + Clientbound::SetEntityMotion(SetEntityMotion { + id: 2, + velocity: [0.0; 3], + }), + Clientbound::SetEquipment(SetEquipment { + id: 2, + slots: vec![(0, None), (5, Some(Stack::new(1, 1)))], + }), + Clientbound::SetHealth(SetHealth { + health: 17.5, + food: 18, + saturation: 3.0, + }), + Clientbound::SetTime(SetTime { + game_time: 100, + clocks: vec![ClockState { + clock: 0, + total_ticks: 6000, + partial_tick: 0.0, + rate: 1.0, + }], + }), + Clientbound::Sound(Sound { + sound: (12, None), + source: 4, + x: 8, + y: 9, + z: 10, + volume: 1.0, + pitch: 1.0, + seed: 3, + }), + Clientbound::Sound(Sound { + sound: (-1, Some(("minecraft:x".into(), Some(16.0)))), + source: 0, + x: 0, + y: 0, + z: 0, + volume: 1.0, + pitch: 1.0, + seed: 0, + }), + Clientbound::SystemChat(SystemChat { + content: literal("hi"), + overlay: false, + }), + Clientbound::TeleportEntity(TeleportEntity { + id: 1, + position: [1.0; 3], + delta: [0.0; 3], + yaw: 0.0, + pitch: 0.0, + relatives: 0, + on_ground: true, + }), + ]; + for p in packets { + round_trip(p, Clientbound::encode, Clientbound::decode); + } + } + + #[test] + fn serverbound_round_trips() { + let packets = vec![ + Serverbound::AcceptTeleportation(AcceptTeleportation { + id: 1, + x: 0.5, + y: 64.0, + z: 0.5, + yaw: 0.0, + pitch: 0.0, + }), + Serverbound::Chat(Chat { + message: "hello".into(), + timestamp: 1, + salt: 0, + signature: None, + last_seen: LastSeenUpdate { + offset: 0, + acknowledged: [0; 3], + checksum: 0, + }, + }), + Serverbound::ChatCommand(ChatCommand { + command: "time set day".into(), + }), + Serverbound::ChunkBatchReceived(ChunkBatchReceived { + chunks_per_tick: 9.5, + }), + Serverbound::ClientCommand(ClientCommand { action: 0 }), + Serverbound::ClientTickEnd(Empty), + Serverbound::ContainerClick(ContainerClick { + container: 0, + state: 5, + slot: 36, + button: 0, + input: 0, + changed: vec![(36, None)], + carried: Some(Hashed::of(&Stack::new(1, 64))), + }), + Serverbound::MovePlayerPosRot(MovePlayerPosRot { + x: 1.0, + y: 2.0, + z: 3.0, + yaw: 4.0, + pitch: 5.0, + flags: 1, + }), + Serverbound::MovePlayerStatus(MovePlayerStatus { flags: 3 }), + Serverbound::PlayerAction(PlayerAction { + action: 0, + pos: [1, 2, 3], + direction: 1, + sequence: 7, + }), + Serverbound::PlayerInput(PlayerInput { flags: 0b0101_0001 }), + Serverbound::PlayerLoaded(Empty), + Serverbound::Punch(Empty), + Serverbound::SetCarriedItem(SetCarriedItem { slot: 4 }), + Serverbound::UseItemOn(UseItemOn { + hand: 0, + pos: [1, 64, 1], + face: 1, + cursor: [0.5, 1.0, 0.5], + inside: false, + world_border: false, + sequence: 8, + }), + Serverbound::Interact(Interact { + id: 9, + hand: 0, + location: [0.25, 1.0, 0.0], + secondary: false, + }), + ]; + for p in packets { + if let Serverbound::Interact(_) = &p { + // LpVec3 is lossy; check bytes instead. + let body = p.encode(); + let mut r = Reader::new(&body); + let id = r.varint().unwrap(); + assert!(matches!( + Serverbound::decode(id, r.rest()).unwrap(), + Serverbound::Interact(Interact { id: 9, .. }) + )); + continue; + } + round_trip(p, Serverbound::encode, Serverbound::decode); + } + } + + #[test] + fn move_entity_deltas_decode_like_vec_delta_codec() { + let base = [10.0, 64.0, -3.5]; + assert_eq!( + VecDelta::Linear([4096, 0, -2048]).end(base), + [11.0, 64.0, -4.0] + ); + // Zero deltas keep unquantized base coordinates exactly. + assert_eq!( + VecDelta::Linear([0, 0, 0]).end([0.123_456_789, 1.0, 2.0]), + [0.123_456_789, 1.0, 2.0] + ); + assert_eq!( + VecDelta::Stepped(vec![([4096, 0, 0], 1), ([4096, 0, 0], 2)]).end(base), + [12.0, 64.0, -3.5] + ); + } + + #[test] + fn unknown_packets_keep_their_payload() { + let p = Clientbound::decode(crate::ids::play::clientbound::BOSS_EVENT, &[1, 2, 3]).unwrap(); + assert_eq!( + p, + Clientbound::Unknown(crate::ids::play::clientbound::BOSS_EVENT, vec![1, 2, 3]) + ); + assert_eq!(p.encode()[1..], [1, 2, 3]); + } +} diff --git a/crates/horizon-protocol/src/packets/status.rs b/crates/horizon-protocol/src/packets/status.rs new file mode 100644 index 000000000..7df73880f --- /dev/null +++ b/crates/horizon-protocol/src/packets/status.rs @@ -0,0 +1,50 @@ +//! Status state: server list ping. +use crate::{ + buf::{Long, Str}, + packet, packet_enum, + packets::Empty, +}; + +packet!(StatusResponse { json: String => Str }); +packet!(Ping { time: i64 => Long }); + +packet_enum!(Clientbound, crate::ids::status::clientbound { + StatusResponse(StatusResponse) = STATUS_RESPONSE, + PongResponse(Ping) = PONG_RESPONSE, +}); +packet_enum!(Serverbound, crate::ids::status::serverbound { + StatusRequest(Empty) = STATUS_REQUEST, + PingRequest(Ping) = PING_REQUEST, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::round_trip; + + #[test] + fn status_round_trips() { + round_trip( + Clientbound::StatusResponse(StatusResponse { + json: "{\"version\":{}}".into(), + }), + Clientbound::encode, + Clientbound::decode, + ); + round_trip( + Clientbound::PongResponse(Ping { time: 123 }), + Clientbound::encode, + Clientbound::decode, + ); + round_trip( + Serverbound::StatusRequest(Empty), + Serverbound::encode, + Serverbound::decode, + ); + round_trip( + Serverbound::PingRequest(Ping { time: -5 }), + Serverbound::encode, + Serverbound::decode, + ); + } +} diff --git a/crates/horizon-protocol/src/registry.rs b/crates/horizon-protocol/src/registry.rs new file mode 100644 index 000000000..f97401670 --- /dev/null +++ b/crates/horizon-protocol/src/registry.rs @@ -0,0 +1,221 @@ +//! Registry id tables. Built-in registries (items, entity types, menus, sound +//! events ...) have fixed network ids, read from the data generator's +//! registries report. Data-driven registries (dimension types, biomes, chat +//! types, damage types ...) are numbered in the order the server sends them +//! during configuration. +use crate::{Error, Result, packets::configuration::RegistryData}; +use horizon_world::nbt::{JavaString, Tag}; +use std::{collections::HashMap, path::Path}; + +/// One registry: names by network id and the reverse lookup. +#[derive(Clone, Debug, Default)] +pub struct Ids { + pub names: Vec, + pub ids: HashMap, +} +impl Ids { + pub fn from_names(names: Vec) -> Self { + let ids = names + .iter() + .enumerate() + .map(|(i, n)| (n.clone(), i as i32)) + .collect(); + Self { names, ids } + } + pub fn name(&self, id: i32) -> Option<&str> { + usize::try_from(id) + .ok() + .and_then(|i| self.names.get(i)) + .map(String::as_str) + } + pub fn id(&self, name: &str) -> Option { + self.ids.get(name).copied() + } +} + +/// The built-in registries from `registries.json` (`--reports`). +#[derive(Clone, Debug, Default)] +pub struct Builtin { + pub registries: HashMap, +} +impl Builtin { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| Error::new(format!("{}: {e}", path.display())))?; + Self::parse(&text) + } + pub fn parse(text: &str) -> Result { + let json: serde_json::Value = serde_json::from_str(text) + .map_err(|e| Error::new(format!("registries report: {e}")))?; + let mut registries = HashMap::new(); + for (name, registry) in json + .as_object() + .ok_or_else(|| Error::new("registries report is not an object"))? + { + let Some(entries) = registry["entries"].as_object() else { + continue; + }; + let mut names = vec![String::new(); entries.len()]; + for (entry, value) in entries { + let id = value["protocol_id"] + .as_u64() + .ok_or_else(|| Error::new(format!("{entry}: no protocol_id")))? + as usize; + if id >= names.len() { + names.resize(id + 1, String::new()); + } + names[id] = entry.clone(); + } + registries.insert(name.clone(), Ids::from_names(names)); + } + Ok(Self { registries }) + } + pub fn get(&self, registry: &str) -> Option<&Ids> { + self.registries.get(registry) + } + /// Look for the report next to prepared resources, then in the data + /// generator output of a development checkout. + pub fn find(resources: &Path) -> Option { + let candidates = [ + resources.join("registries.json"), + resources.join("../../datagen/out/reports/registries.json"), + resources.join("../datagen/out/reports/registries.json"), + ]; + candidates.into_iter().find(|p| p.is_file()) + } +} + +/// Registries synchronized during configuration, in arrival order. +#[derive(Clone, Debug, Default)] +pub struct Dynamic { + pub registries: HashMap)>>, +} +impl Dynamic { + pub fn add(&mut self, packet: RegistryData) { + let entries = packet.entries.into_iter().map(|e| (e.id, e.data)).collect(); + self.registries.insert(packet.registry, entries); + } + pub fn name(&self, registry: &str, id: i32) -> Option<&str> { + let i = usize::try_from(id).ok()?; + self.registries + .get(registry)? + .get(i) + .map(|(n, _)| n.as_str()) + } + pub fn data(&self, registry: &str, id: i32) -> Option<&Tag> { + let i = usize::try_from(id).ok()?; + self.registries.get(registry)?.get(i)?.1.as_ref() + } + pub fn len(&self, registry: &str) -> usize { + self.registries.get(registry).map_or(0, Vec::len) + } + pub fn is_empty(&self) -> bool { + self.registries.is_empty() + } + /// The dimension type's vertical range and sky light, from its + /// synchronized data or the vanilla defaults for known names. + pub fn dimension(&self, id: i32) -> DimensionType { + let name = self + .name("minecraft:dimension_type", id) + .unwrap_or("minecraft:overworld"); + let mut d = DimensionType::vanilla(name); + if let Some(Tag::Compound(map)) = self.data("minecraft:dimension_type", id) { + let int = |k: &str| match map.get(&JavaString::from(k)) { + Some(Tag::Int(v)) => Some(*v), + _ => None, + }; + if let Some(v) = int("min_y") { + d.min_y = v; + } + if let Some(v) = int("height") { + d.height = v; + } + if let Some(Tag::Byte(v)) = map.get(&JavaString::from("has_skylight")) { + d.has_skylight = *v != 0; + } + } + d + } +} +/// The parts of a DimensionType the client needs for chunk layout. +#[derive(Clone, Debug, PartialEq)] +pub struct DimensionType { + pub name: String, + pub min_y: i32, + pub height: i32, + pub has_skylight: bool, +} +impl DimensionType { + pub fn vanilla(name: &str) -> Self { + let (min_y, height, has_skylight) = match name { + "minecraft:the_nether" => (0, 256, false), + "minecraft:the_end" => (0, 256, false), + _ => (-64, 384, true), + }; + Self { + name: name.to_owned(), + min_y, + height, + has_skylight, + } + } + pub fn sections(&self) -> usize { + (self.height / 16) as usize + } +} + +/// Mth.ceillog2(n): bits for a global palette over `n` values. +pub fn ceil_log2(n: usize) -> u8 { + if n <= 1 { + 0 + } else { + (usize::BITS - (n - 1).leading_zeros()) as u8 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::configuration::RegistryEntry; + + #[test] + fn parses_registry_reports() { + let report = r#"{"minecraft:item":{"default":"minecraft:air","entries":{"minecraft:stone":{"protocol_id":1},"minecraft:air":{"protocol_id":0}},"protocol_id":5}}"#; + let b = Builtin::parse(report).unwrap(); + let items = b.get("minecraft:item").unwrap(); + assert_eq!(items.name(1), Some("minecraft:stone")); + assert_eq!(items.id("minecraft:air"), Some(0)); + assert_eq!(items.name(2), None); + } + + #[test] + fn dynamic_registries_follow_arrival_order() { + let mut d = Dynamic::default(); + d.add(RegistryData { + registry: "minecraft:dimension_type".into(), + entries: vec![ + RegistryEntry { + id: "minecraft:overworld".into(), + data: None, + }, + RegistryEntry { + id: "minecraft:the_nether".into(), + data: Some(Tag::compound([ + ("min_y", Tag::Int(0)), + ("height", Tag::Int(256)), + ("has_skylight", Tag::Byte(0)), + ])), + }, + ], + }); + assert_eq!( + d.dimension(0), + DimensionType::vanilla("minecraft:overworld") + ); + assert_eq!(d.dimension(1).sections(), 16); + assert!(!d.dimension(1).has_skylight); + assert_eq!(ceil_log2(35723), 16); + assert_eq!(ceil_log2(65), 7); + assert_eq!(ceil_log2(64), 6); + } +} diff --git a/crates/horizon-protocol/src/servers.rs b/crates/horizon-protocol/src/servers.rs new file mode 100644 index 000000000..1540df20a --- /dev/null +++ b/crates/horizon-protocol/src/servers.rs @@ -0,0 +1,149 @@ +//! The multiplayer server list, stored like vanilla's ServerList in an +//! uncompressed `servers.dat`: `{servers: [{name, ip, icon?, acceptTextures?}]}`. +use horizon_world::nbt::{self, JavaString, NamedTag, Tag}; +use std::path::Path; + +#[derive(Clone, Debug, PartialEq)] +pub struct ServerEntry { + pub name: String, + pub ip: String, + /// Base64 PNG favicon from the last status ping. + pub icon: Option, + /// ServerPackStatus: None = prompt, Some(true) enabled, Some(false) disabled. + pub accept_textures: Option, +} +impl ServerEntry { + pub fn new(name: &str, ip: &str) -> Self { + Self { + name: name.to_owned(), + ip: ip.to_owned(), + icon: None, + accept_textures: None, + } + } + fn to_tag(&self) -> Tag { + let mut entries = vec![ + ("name", Tag::String(JavaString::from(self.name.as_str()))), + ("ip", Tag::String(JavaString::from(self.ip.as_str()))), + ]; + if let Some(icon) = &self.icon { + entries.push(("icon", Tag::String(JavaString::from(icon.as_str())))); + } + if let Some(accept) = self.accept_textures { + entries.push(("acceptTextures", Tag::Byte(i8::from(accept)))); + } + Tag::compound(entries) + } + fn from_tag(tag: &Tag) -> Option { + let string = |k: &str| match tag.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + Some(Self { + name: string("name").unwrap_or_default(), + ip: string("ip")?, + icon: string("icon"), + accept_textures: match tag.get("acceptTextures") { + Some(Tag::Byte(b)) => Some(*b != 0), + _ => None, + }, + }) + } +} + +/// ServerList.load: missing or unreadable files give an empty list. +pub fn load(path: &Path) -> Vec { + let Ok(bytes) = std::fs::read(path) else { + return Vec::new(); + }; + let Ok((root, _)) = nbt::read_named(&bytes, nbt::Limits::default()) else { + return Vec::new(); + }; + // ServerList skips entries flagged "hidden" (the LAN/quick-play ones). + match root.tag.get("servers") { + Some(Tag::List(list)) => list + .iter() + .filter(|t| !matches!(t.get("hidden"), Some(Tag::Byte(1)))) + .filter_map(ServerEntry::from_tag) + .collect(), + _ => Vec::new(), + } +} +/// ServerList.save: write to a temporary file, then replace. +pub fn save(path: &Path, servers: &[ServerEntry]) -> std::io::Result<()> { + let root = NamedTag { + name: JavaString::from(""), + tag: Tag::compound([( + "servers", + Tag::List(servers.iter().map(ServerEntry::to_tag).collect()), + )]), + }; + let bytes = nbt::write_named(&root, nbt::Limits::default()).map_err(std::io::Error::other)?; + let tmp = path.with_extension("dat_tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(tmp, path) +} + +/// ServerAddress.parseString: `host`, `host:port` or `[v6]:port`; default 25565. +pub fn parse_address(text: &str) -> Option<(String, u16)> { + let text = text.trim(); + if text.is_empty() { + return None; + } + if let Some(rest) = text.strip_prefix('[') { + let (host, tail) = rest.split_once(']')?; + let port = match tail.strip_prefix(':') { + Some(p) => p.parse().ok()?, + None if tail.is_empty() => 25565, + None => return None, + }; + return Some((host.to_owned(), port)); + } + match text.rsplit_once(':') { + Some((host, port)) if !host.contains(':') => Some((host.to_owned(), port.parse().ok()?)), + Some(_) => Some((text.to_owned(), 25565)), + None => Some((text.to_owned(), 25565)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn servers_dat_round_trips() { + let dir = std::env::temp_dir().join(format!("horizon-servers-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("servers.dat"); + let list = vec![ + ServerEntry::new("Minecraft Server", "localhost:25565"), + ServerEntry { + accept_textures: Some(false), + ..ServerEntry::new("Other", "example.org") + }, + ]; + save(&path, &list).unwrap(); + assert_eq!(load(&path), list); + // Vanilla layout: an unnamed root compound with a "servers" list. + let (root, _) = + nbt::read_named(&std::fs::read(&path).unwrap(), nbt::Limits::default()).unwrap(); + assert_eq!(root.name, JavaString::from("")); + assert!(matches!(root.tag.get("servers"), Some(Tag::List(l)) if l.len() == 2)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn parses_addresses_like_server_address() { + assert_eq!( + parse_address("localhost"), + Some(("localhost".into(), 25565)) + ); + assert_eq!( + parse_address("127.0.0.1:25570"), + Some(("127.0.0.1".into(), 25570)) + ); + assert_eq!(parse_address("[::1]:1234"), Some(("::1".into(), 1234))); + assert_eq!(parse_address("host:notaport"), None); + assert_eq!(parse_address(""), None); + } +} diff --git a/crates/horizon-protocol/src/text.rs b/crates/horizon-protocol/src/text.rs new file mode 100644 index 000000000..7a23f16a8 --- /dev/null +++ b/crates/horizon-protocol/src/text.rs @@ -0,0 +1,190 @@ +//! Chat components as sent on the network (ComponentSerialization in NBT form) +//! flattened to display strings, with `translate` keys resolved through a +//! language table (en_us.json) and Java `String.format` style arguments. +use horizon_world::nbt::{JavaString, Tag}; +use std::collections::HashMap; + +/// A language table: translation key -> pattern. +pub type Language = HashMap; + +fn string(tag: &Tag) -> Option { + match tag { + Tag::String(s) => Some(s.to_string_lossy()), + _ => None, + } +} +fn get<'t>(tag: &'t Tag, key: &str) -> Option<&'t Tag> { + match tag { + Tag::Compound(map) => map.get(&JavaString::from(key)), + _ => None, + } +} + +/// Flatten a component to text. +pub fn plain(tag: &Tag, lang: &Language) -> String { + let mut out = String::new(); + append(tag, lang, &mut out, 0); + out +} +fn append(tag: &Tag, lang: &Language, out: &mut String, depth: usize) { + if depth > 32 { + return; + } + match tag { + Tag::String(s) => out.push_str(&s.to_string_lossy()), + Tag::Byte(v) => out.push_str(&v.to_string()), + Tag::Short(v) => out.push_str(&v.to_string()), + Tag::Int(v) => out.push_str(&v.to_string()), + Tag::Long(v) => out.push_str(&v.to_string()), + Tag::Float(v) => out.push_str(&f32::from_bits(*v).to_string()), + Tag::Double(v) => out.push_str(&f64::from_bits(*v).to_string()), + // A list is its first element with the rest appended as siblings. + Tag::List(items) => { + for item in items { + append(item, lang, out, depth + 1); + } + } + Tag::Compound(_) => { + if let Some(text) = get(tag, "text").and_then(string) { + out.push_str(&text); + } else if let Some(text) = get(tag, "").and_then(string) { + // Mixed-list wrapper for a bare string. + out.push_str(&text); + } else if let Some(key) = get(tag, "translate").and_then(string) { + let args: Vec = match get(tag, "with") { + Some(Tag::List(args)) => args + .iter() + .map(|a| { + let mut s = String::new(); + append(a, lang, &mut s, depth + 1); + s + }) + .collect(), + _ => Vec::new(), + }; + let pattern = lang + .get(&key) + .cloned() + .or_else(|| get(tag, "fallback").and_then(string)) + .unwrap_or_else(|| key.clone()); + out.push_str(&format_java(&pattern, &args)); + } else if let Some(key) = get(tag, "keybind").and_then(string) { + out.push_str(lang.get(&key).map_or(key.as_str(), String::as_str)); + } else if let Some(selector) = get(tag, "selector").and_then(string) { + out.push_str(&selector); + } else if let Some(score) = get(tag, "score") { + if let Some(name) = get(score, "name").and_then(string) { + out.push_str(&name); + } + } + if let Some(Tag::List(extra)) = get(tag, "extra") { + for e in extra { + append(e, lang, out, depth + 1); + } + } + } + _ => {} + } +} + +/// TranslatableContents.decomposeTemplate: `%s`, `%n$s` and `%%`. +pub fn format_java(pattern: &str, args: &[String]) -> String { + let mut out = String::new(); + let mut next = 0usize; + let mut chars = pattern.char_indices().peekable(); + while let Some((_, c)) = chars.next() { + if c != '%' { + out.push(c); + continue; + } + let mut digits = String::new(); + while let Some(&(_, d)) = chars.peek() { + if d.is_ascii_digit() { + digits.push(d); + chars.next(); + } else { + break; + } + } + match chars.next() { + Some((_, '%')) if digits.is_empty() => out.push('%'), + Some((_, '$')) if !digits.is_empty() => { + if chars.next().map(|(_, c)| c) == Some('s') { + let i = digits.parse::().unwrap_or(1).saturating_sub(1); + out.push_str(args.get(i).map_or("", String::as_str)); + } + } + Some((_, 's')) if digits.is_empty() => { + out.push_str(args.get(next).map_or("", String::as_str)); + next += 1; + } + Some((_, other)) => { + out.push('%'); + out.push_str(&digits); + out.push(other); + } + None => out.push('%'), + } + } + out +} + +/// A literal text component. +pub fn literal(text: &str) -> Tag { + Tag::String(JavaString::from(text)) +} +/// A translatable component with literal arguments. +pub fn translatable(key: &str, args: &[&str]) -> Tag { + let mut entries = vec![("translate", Tag::String(JavaString::from(key)))]; + if !args.is_empty() { + entries.push(("with", Tag::List(args.iter().map(|a| literal(a)).collect()))); + } + Tag::compound(entries) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_like_translatable_contents() { + let args = vec!["Steve".to_owned(), "hi".to_owned()]; + assert_eq!(format_java("<%s> %s", &args), " hi"); + assert_eq!(format_java("%2$s by %1$s", &args), "hi by Steve"); + assert_eq!(format_java("100%% sure", &[]), "100% sure"); + } + + #[test] + fn flattens_components() { + let mut lang = Language::new(); + lang.insert( + "multiplayer.player.joined".into(), + "%s joined the game".into(), + ); + let joined = Tag::compound([ + ("translate", Tag::String("multiplayer.player.joined".into())), + ( + "with", + Tag::List(vec![Tag::compound([("text", Tag::String("Alex".into()))])]), + ), + ("color", Tag::String("yellow".into())), + ]); + assert_eq!(plain(&joined, &lang), "Alex joined the game"); + let extra = Tag::compound([ + ("text", Tag::String("a".into())), + ( + "extra", + Tag::List(vec![ + literal("b"), + Tag::compound([("text", Tag::String("c".into()))]), + ]), + ), + ]); + assert_eq!(plain(&extra, &lang), "abc"); + assert_eq!( + plain(&translatable("missing.key", &[]), &lang), + "missing.key" + ); + assert_eq!(plain(&literal("plain"), &lang), "plain"); + } +} diff --git a/tools/generate_packet_ids.py b/tools/generate_packet_ids.py new file mode 100644 index 000000000..c5c0b90f8 --- /dev/null +++ b/tools/generate_packet_ids.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Generate crates/horizon-protocol/src/ids.rs from the vanilla data generator's +packets report (`java -DbundlerMainClass=net.minecraft.data.Main -jar server.jar --reports`). + +Packet ids are protocol facts (the order packets are registered in each +connection state); the report is the authoritative source for them. +""" + +import argparse +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +STATES = ["handshake", "status", "login", "configuration", "play"] +DIRECTIONS = ["clientbound", "serverbound"] + + +def const_name(name): + return name.split(":", 1)[1].replace("/", "_").upper() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--report", type=Path, default=ROOT / ".local/datagen/out/reports/packets.json") + parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-protocol/src/ids.rs") + args = parser.parse_args() + report = json.loads(args.report.read_text()) + lines = [ + "//! Packet ids per connection state and direction for protocol 777 (26.3).", + "//! Generated by tools/generate_packet_ids.py from the data generator's", + "//! packets report; do not edit by hand.", + "#![allow(missing_docs)]", + "use crate::{Direction, State};", + "", + ] + tables = [] + for state in STATES: + lines.append(f"pub mod {state} {{") + for direction in DIRECTIONS: + packets = report.get(state, {}).get(direction, {}) + if not packets: + continue + ordered = sorted(packets.items(), key=lambda kv: kv[1]["protocol_id"]) + assert [e["protocol_id"] for _, e in ordered] == list(range(len(ordered))), (state, direction) + lines.append(f" pub mod {direction} {{") + for name, entry in ordered: + lines.append(f" pub const {const_name(name)}: i32 = {entry['protocol_id']};") + lines.append(" /// Packet names indexed by id.") + names = ", ".join(f'"{name.split(":", 1)[1]}"' for name, _ in ordered) + lines.append(f" pub const NAMES: &[&str] = &[{names}];") + lines.append(" }") + tables.append((state, direction)) + lines.append("}") + lines.append("") + lines.append("/// The packet name for an id, if the state and direction define it.") + lines.append("pub fn name(state: State, direction: Direction, id: i32) -> Option<&'static str> {") + lines.append(" let names: &[&str] = match (state, direction) {") + for state, direction in tables: + lines.append( + f" (State::{state.capitalize()}, Direction::{direction.capitalize()}) => {state}::{direction}::NAMES," + ) + lines.append(" _ => &[],") + lines.append(" };") + lines.append(" usize::try_from(id).ok().and_then(|i| names.get(i)).copied()") + lines.append("}") + args.out.write_text("\n".join(lines) + "\n") + + +if __name__ == "__main__": + main()