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 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:13:51 +02:00
parent 1b38d82aac
commit fa21ea7688
23 changed files with 5405 additions and 1 deletions
@@ -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<u8> => 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<Tag> => Opt<Nbt> }
);
packet!(RegistryData { registry: String => Ident, entries: Vec<RegistryEntry> => List<RegistryEntry> });
packet!(ResourcePackPop { id: Option<u128> => Opt<Uuid> });
packet!(ResourcePackPush {
id: u128 => Uuid,
url: String => Str,
hash: String => StrN<40>,
required: bool => Bool,
prompt: Option<Tag> => Opt<Nbt>,
});
packet!(StoreCookie { key: String => Ident, payload: Vec<u8> => crate::buf::Bytes });
packet!(Transfer { host: String => Str, port: i32 => VarInt });
packet!(UpdateEnabledFeatures { features: Vec<String> => List<Ident> });
packet!(TagEntry { name: String => Ident, ids: Vec<i32> => List<VarInt> });
packet!(RegistryTags { registry: String => Ident, tags: Vec<TagEntry> => List<TagEntry> });
packet!(
/// ClientboundUpdateTagsPacket: tags per registry.
UpdateTags { registries: Vec<RegistryTags> => List<RegistryTags> }
);
packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str });
packet!(SelectKnownPacks { packs: Vec<KnownPack> => List<KnownPack> });
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<ClientInformation> for ClientInformation {
fn read(r: &mut Reader) -> Result<Self> {
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<Vec<u8>> => Opt<crate::buf::Bytes> });
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);
}
}
}
@@ -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);
}
}
@@ -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<String> => Opt<StrN<1024>>,
}
);
packet!(
/// ByteBufCodecs.GAME_PROFILE.
GameProfile {
uuid: u128 => Uuid,
name: String => StrN<16>,
properties: Vec<Property> => crate::buf::List<Property>,
}
);
packet!(Disconnect { reason_json: String => StrN<262144> });
packet!(Hello {
server_id: String => StrN<20>,
public_key: Vec<u8> => Bytes,
challenge: Vec<u8> => 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<u8> => 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<u8> => Bytes, challenge: Vec<u8> => Bytes });
packet!(CustomQueryAnswer { transaction: i32 => VarInt, payload: Option<Vec<u8>> => Opt<Rest> });
packet!(CookieResponse { key: String => Ident, payload: Option<Vec<u8>> => Opt<Bytes> });
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());
}
}
@@ -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<u8>),
}
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<Self> {
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<u8> {
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<Empty> for Empty {
fn read(_: &mut Reader) -> crate::Result<Empty> {
Ok(Empty)
}
fn write(_: &Empty, _: &mut Writer) {}
}
#[cfg(test)]
pub(crate) fn round_trip<T: Clone + PartialEq + std::fmt::Debug>(
packet: T,
encode: impl Fn(&T) -> Vec<u8>,
decode: impl Fn(i32, &[u8]) -> crate::Result<T>,
) {
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);
}
File diff suppressed because it is too large Load Diff
@@ -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,
);
}
}