Dedicated server: load the spawn area; vanilla-codec client harness

VanillaProtocolClient joins a server with vanilla's own codecs;
test_dedicated_server_parity.py compares a vanilla and a Horizon dedicated
server serving the same world.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 00:18:01 +02:00
parent 3319f92c0e
commit 8d16a937c5
3 changed files with 762 additions and 1 deletions
+1 -1
View File
@@ -350,7 +350,7 @@ impl Game<'_> {
self.set_default_game_mode(game_mode);
self.ui.difficulty = props.difficulty as u8;
self.settings.render_distance = props.view_distance.clamp(2, 32);
self.streaming.radius = 0;
self.streaming.radius = self.settings.render_distance;
self.settle_spawn()?;
let gate_lists = lists.clone();
let gate: LoginGate = Arc::new(move |address, uuid, name| {
@@ -0,0 +1,476 @@
package dev.horizonlab.parity;
import com.google.gson.JsonElement;
import com.mojang.serialization.JsonOps;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.UUID;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.minecraft.SharedConstants;
import net.minecraft.core.UUIDUtil;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.network.chat.LastSeenMessages;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.ProtocolInfo;
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ClientboundDisconnectPacket;
import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket;
import net.minecraft.network.protocol.common.ClientboundPingPacket;
import net.minecraft.network.protocol.common.ServerboundClientInformationPacket;
import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ServerboundKeepAlivePacket;
import net.minecraft.network.protocol.common.ServerboundPongPacket;
import net.minecraft.network.protocol.common.custom.BrandPayload;
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks;
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket;
import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks;
import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket;
import net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.network.protocol.game.ClientboundSystemChatPacket;
import net.minecraft.network.protocol.game.GameProtocols;
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
import net.minecraft.network.protocol.game.ServerboundChatCommandPacket;
import net.minecraft.network.protocol.game.ServerboundChatPacket;
import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket;
import net.minecraft.network.protocol.handshake.ClientIntent;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.handshake.HandshakeProtocols;
import net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.network.protocol.login.ClientboundLoginFinishedPacket;
import net.minecraft.network.protocol.login.LoginProtocols;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.network.protocol.login.ServerboundLoginAcknowledgedPacket;
import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket;
import net.minecraft.network.protocol.ping.ServerboundPingRequestPacket;
import net.minecraft.network.protocol.status.ClientboundStatusResponsePacket;
import net.minecraft.network.protocol.status.ServerStatus;
import net.minecraft.network.protocol.status.ServerboundStatusRequestPacket;
import net.minecraft.network.protocol.status.StatusProtocols;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.world.entity.PositionMoveRotation;
import net.minecraft.world.phys.Vec3;
/**
* A headless client made of vanilla's own protocol: it frames, compresses and
* decodes every packet with the codecs of the pinned server JAR (the client
* shares them), so any byte a server sends that vanilla would not read is
* recorded as an error. tools/test_dedicated_server_parity.py points it at a
* vanilla dedicated server and at Horizon's, with the same settings and
* world, and compares the transcripts.
*
* <p>{@code VanillaProtocolClient HOST PORT NAME OUT} pings the server (status
* and ping), joins as NAME in offline mode, goes through login and
* configuration, accepts the spawn teleport, waits for the chunks around the
* spawn, sends a chat message and the {@code /list} command, and leaves.
* Each transcript line is a section and a summary: the login and
* configuration packets in order; in play, the packets up to the first chunk
* batch in order, then the chunks by position with the hash of their bytes
* and the replies to the chat and command. Values that change between runs
* (entity ids, keep-alive ids, times, salts) are not part of the summaries.
*/
public final class VanillaProtocolClient {
private Socket socket;
private DataInputStream in;
private OutputStream out;
private int threshold = -1;
private final List<String> lines = new ArrayList<>();
private ProtocolInfo<?> inbound;
private ProtocolInfo<?> outbound;
private String state;
public static void main(String[] args) throws Exception {
ParityData.init();
String host = args[0];
int port = Integer.parseInt(args[1]);
String name = args[2];
Path output = Path.of(args[3]);
VanillaProtocolClient client = new VanillaProtocolClient();
try {
client.status(host, port);
client.join(host, port, name);
} catch (Exception e) {
client.lines.add("error " + client.state + " " + e);
} finally {
if (client.socket != null) client.socket.close();
}
try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
for (String line : client.lines) w.println(line);
}
System.exit(0);
}
// ---- connection ---------------------------------------------------
private void open(String host, int port) throws Exception {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 10_000);
socket.setSoTimeout(30_000);
socket.setTcpNoDelay(true);
in = new DataInputStream(socket.getInputStream());
out = socket.getOutputStream();
threshold = -1;
}
private static int readVarInt(InputStream in) throws Exception {
int value = 0;
for (int i = 0; i < 5; i++) {
int b = in.read();
if (b < 0) throw new EOFException();
value |= (b & 0x7F) << (7 * i);
if ((b & 0x80) == 0) return value;
}
throw new IllegalStateException("VarInt too big");
}
private static void writeVarInt(ByteBuf buf, int value) {
while ((value & ~0x7F) != 0) {
buf.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
buf.writeByte(value);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void send(Packet<?> packet) throws Exception {
ByteBuf body = Unpooled.buffer();
((ProtocolInfo) outbound).codec().encode(body, packet);
byte[] raw = new byte[body.readableBytes()];
body.readBytes(raw);
ByteBuf frame = Unpooled.buffer();
if (threshold >= 0) {
ByteBuf inner = Unpooled.buffer();
if (raw.length >= threshold) {
writeVarInt(inner, raw.length);
Deflater d = new Deflater();
d.setInput(raw);
d.finish();
byte[] tmp = new byte[raw.length + 64];
while (!d.finished()) {
int n = d.deflate(tmp);
inner.writeBytes(tmp, 0, n);
}
d.end();
} else {
writeVarInt(inner, 0);
inner.writeBytes(raw);
}
writeVarInt(frame, inner.readableBytes());
frame.writeBytes(inner);
} else {
writeVarInt(frame, raw.length);
frame.writeBytes(raw);
}
byte[] bytes = new byte[frame.readableBytes()];
frame.readBytes(bytes);
out.write(bytes);
out.flush();
}
/** The next packet's raw payload, decompressed as CompressionDecoder does (validating). */
private byte[] readFrame() throws Exception {
int length = readVarInt(in);
byte[] frame = new byte[length];
in.readFully(frame);
if (threshold < 0) return frame;
ByteBuf buf = Unpooled.wrappedBuffer(frame);
int dataLength = readVarInt(new java.io.ByteArrayInputStream(frame));
int header = varIntSize(dataLength);
buf.skipBytes(header);
if (dataLength == 0) {
byte[] raw = new byte[buf.readableBytes()];
buf.readBytes(raw);
return raw;
}
if (dataLength < threshold) {
throw new IllegalStateException("Badly compressed packet - size of " + dataLength + " is below server threshold of " + threshold);
}
if (dataLength > 8388608) {
throw new IllegalStateException("Badly compressed packet - size of " + dataLength + " is larger than protocol maximum of 8388608");
}
Inflater inflater = new Inflater();
inflater.setInput(frame, header, frame.length - header);
byte[] raw = new byte[dataLength];
int n;
try {
n = inflater.inflate(raw);
} catch (DataFormatException e) {
throw new IllegalStateException("bad zlib data", e);
}
boolean finished = inflater.finished();
inflater.end();
if (n != dataLength || !finished) throw new IllegalStateException("decompressed " + n + " of " + dataLength + " bytes");
return raw;
}
private static int varIntSize(int v) {
int n = 1;
while ((v & ~0x7F) != 0) {
v >>>= 7;
n++;
}
return n;
}
private record Received(Packet<?> packet, byte[] payload, String type) {}
/** The next packet, decoded with the inbound protocol; leftover bytes are an error (PacketDecoder). */
private Received read() throws Exception {
byte[] payload = readFrame();
ByteBuf buf = Unpooled.wrappedBuffer(payload);
Packet<?> packet = inbound.codec().decode(buf);
if (buf.readableBytes() > 0) {
throw new IllegalStateException("Packet " + inbound.id().id() + "/" + packet.type().id() + " was larger than I expected, found "
+ buf.readableBytes() + " bytes extra whilst reading");
}
return new Received(packet, payload, packet.type().id().toString());
}
// ---- summaries ----------------------------------------------------
private static String sha(byte[] bytes) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)).substring(0, 16);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String json(Component c) {
JsonElement e = ComponentSerialization.CODEC.encodeStart(ParityData.access.createSerializationContext(JsonOps.INSTANCE), c).getOrThrow();
return e.toString();
}
/** A record's text without object identities. */
private static String text(Object o) {
return String.valueOf(o).replaceAll("@[0-9a-f]{4,}", "@");
}
private void record(String section, String line) {
lines.add(section + " " + line);
}
// ---- status -------------------------------------------------------
private void status(String host, int port) throws Exception {
state = "status";
open(host, port);
outbound = HandshakeProtocols.SERVERBOUND;
send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.STATUS));
outbound = StatusProtocols.SERVERBOUND;
inbound = StatusProtocols.CLIENTBOUND;
send(ServerboundStatusRequestPacket.INSTANCE);
Received r = read();
if (r.packet instanceof ClientboundStatusResponsePacket p) {
JsonElement e = ServerStatus.CODEC.encodeStart(JsonOps.INSTANCE, p.status()).getOrThrow();
// The favicon is compared by its bytes' hash.
String s = e.toString().replaceAll("\"favicon\":\"[^\"]*\"", "\"favicon\":\"" + p.status().favicon().map(f -> sha(f.iconBytes())).orElse("") + "\"");
record("status", r.type + " " + s);
} else {
record("status", r.type + " " + text(r.packet));
}
send(new ServerboundPingRequestPacket(1234567890123L));
Received pong = read();
record("status", pong.type + " " + (pong.packet instanceof ClientboundPongResponsePacket p ? p.time() : text(pong.packet)));
int after = in.read();
record("status", "closed-after-pong " + (after < 0));
socket.close();
}
// ---- join ---------------------------------------------------------
private void join(String host, int port, String name) throws Exception {
open(host, port);
state = "login";
outbound = HandshakeProtocols.SERVERBOUND;
send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.LOGIN));
outbound = LoginProtocols.SERVERBOUND;
inbound = LoginProtocols.CLIENTBOUND;
UUID uuid = UUIDUtil.createOfflinePlayerUUID(name);
send(new ServerboundHelloPacket(name, uuid));
while (true) {
Received r = read();
if (r.packet instanceof ClientboundLoginCompressionPacket p) {
threshold = p.getCompressionThreshold();
record("login", r.type + " " + threshold);
} else if (r.packet instanceof ClientboundLoginFinishedPacket p) {
record("login", r.type + " " + p.gameProfile().id() + " " + p.gameProfile().name() + " " + p.gameProfile().properties().size());
send(ServerboundLoginAcknowledgedPacket.INSTANCE);
break;
} else if (r.packet instanceof ClientboundLoginDisconnectPacket p) {
record("login", r.type + " " + json(p.reason()));
return;
} else {
record("login", r.type + " " + text(r.packet));
}
}
state = "configuration";
outbound = ConfigurationProtocols.SERVERBOUND;
inbound = ConfigurationProtocols.CLIENTBOUND;
// ClientHandshakePacketListenerImpl.handleLoginFinished: brand, then the options.
send(new ServerboundCustomPayloadPacket(new BrandPayload("vanilla")));
send(new ServerboundClientInformationPacket(ClientInformation.createDefault()));
while (true) {
Received r = read();
if (r.packet instanceof ClientboundSelectKnownPacks p) {
record("config", r.type + " " + text(p.knownPacks()));
send(new ServerboundSelectKnownPacks(p.knownPacks()));
} else if (r.packet instanceof ClientboundKeepAlivePacket p) {
record("config", r.type);
send(new ServerboundKeepAlivePacket(p.getId()));
} else if (r.packet instanceof ClientboundPingPacket p) {
record("config", r.type);
send(new ServerboundPongPacket(p.getId()));
} else if (r.packet instanceof ClientboundCustomPayloadPacket p) {
record("config", r.type + " " + text(p.payload()));
} else if (r.packet instanceof ClientboundFinishConfigurationPacket) {
record("config", r.type);
send(ServerboundFinishConfigurationPacket.INSTANCE);
break;
} else if (r.packet instanceof ClientboundDisconnectPacket p) {
record("config", r.type + " " + json(p.reason()));
return;
} else {
record("config", r.type + " " + (r.payload.length > 200 ? "sha=" + sha(r.payload) : text(r.packet)));
}
}
play();
}
private void play() throws Exception {
state = "play";
GameProtocols.Context context = new GameProtocols.Context() {
@Override
public boolean hasInfiniteMaterials() {
return false;
}
@Override
public boolean canUseCommandBlocks() {
return false;
}
};
outbound = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access), context);
inbound = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access));
socket.setSoTimeout(250);
Map<String, String> chunks = new TreeMap<>();
Map<String, Integer> counts = new TreeMap<>();
boolean ordered = true;
boolean loaded = false;
PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0);
long lastChunk = 0;
long deadline = System.currentTimeMillis() + 90_000;
int step = 0;
long stepAt = 0;
while (System.currentTimeMillis() < deadline) {
Received r;
try {
r = read();
} catch (SocketTimeoutException e) {
r = null;
}
long now = System.currentTimeMillis();
if (r != null) {
Packet<?> packet = r.packet;
counts.merge(r.type, 1, Integer::sum);
if (r.type.equals("minecraft:chunk_batch_start")) ordered = false;
if (packet instanceof ClientboundKeepAlivePacket p) {
send(new ServerboundKeepAlivePacket(p.getId()));
} else if (packet instanceof ClientboundPingPacket p) {
send(new ServerboundPongPacket(p.getId()));
} else if (packet instanceof ClientboundPlayerPositionPacket p) {
position = PositionMoveRotation.calculateAbsolute(position, p.change(), p.relatives());
record("play-move", text(position.position()) + " " + position.yRot() + " " + position.xRot());
send(new ServerboundAcceptTeleportationPacket(p.id(), position.position().x, position.position().y, position.position().z,
position.yRot(), position.xRot()));
send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false));
if (!loaded) {
send(new ServerboundPlayerLoadedPacket());
loaded = true;
}
} else if (packet instanceof ClientboundChunkBatchFinishedPacket) {
send(new ServerboundChunkBatchReceivedPacket(64.0F));
} else if (packet instanceof ClientboundLevelChunkWithLightPacket p) {
chunks.put(p.x() + "," + p.z(), sha(r.payload));
lastChunk = now;
} else if (packet instanceof ClientboundSystemChatPacket p && step > 0) {
record("play-chat", "system " + p.overlay() + " " + json(p.content()));
} else if (packet instanceof ClientboundPlayerChatPacket p && step > 0) {
record("play-chat", "player " + p.sender() + " " + p.index() + " " + p.body().content() + " " + p.signature().isPresent()
+ " " + p.unsignedContent().map(VanillaProtocolClient::json) + " " + text(p.filterMask()) + " "
+ p.chatType().chatType().getRegisteredName() + " " + json(p.chatType().name()) + " "
+ p.chatType().targetName().map(VanillaProtocolClient::json));
} else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0) {
record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName());
} else if (packet instanceof ClientboundDisconnectPacket p) {
record("play", r.type + " " + json(p.reason()));
break;
}
if (ordered) {
record("play-start", r.type + " " + summary(r));
}
}
// Once the chunks stop coming: chat, then /list, then leave.
if (loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) {
record("play-chunks", chunks.size() + " " + chunks);
step = 1;
stepAt = now;
send(new ServerboundChatPacket("hello from the parity client", Instant.now(), 0L, Optional.empty(),
new LastSeenMessages.Update(0, new BitSet(), (byte) 0)));
} else if (step == 1 && now - stepAt > 1500) {
step = 2;
stepAt = now;
send(new ServerboundChatCommandPacket("list"));
} else if (step == 2 && now - stepAt > 1500) {
record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0));
return;
}
}
record("error", "timed out in play, step " + step + ", chunks " + chunks.size());
}
/** The first play packets: entity ids, seeds and times aside. */
private String summary(Received r) {
String t = r.type;
if (t.equals("minecraft:login")) {
return text(r.packet).replaceAll("playerId=-?\\d+", "playerId=_");
}
if (t.equals("minecraft:set_time") || t.equals("minecraft:keep_alive") || t.equals("minecraft:ping")) return "";
if (t.contains("entity") || t.equals("minecraft:add_entity") || t.equals("minecraft:update_attributes")
|| t.equals("minecraft:player_info_update") || t.equals("minecraft:player_position")) {
return "";
}
return r.payload.length > 200 ? "sha=" + sha(r.payload) : text(r.packet);
}
}
+285
View File
@@ -0,0 +1,285 @@
#!/usr/bin/env python3
"""The dedicated server against vanilla's, seen from a vanilla client.
The pinned server JAR first generates a world (offline mode, a fixed seed,
respawn_radius 0) and stops; a vanilla dedicated server and Horizon's
(`horizon-client --dedicated --nogui`) then serve copies of it with the same
server.properties, server-icon.png and lists. VanillaProtocolClient, a
headless client made of vanilla's own codecs (any byte vanilla would not
read is an error), pings each server, joins it in offline mode through
login, configuration and play, accepts the spawn teleport, receives the
chunks around the spawn (their bytes are compared: the world is loaded from
the same files), chats, runs /list and leaves. The console then runs `list`
and `say` and `stop`. Compared, all of them exactly:
- the status response (MOTD, players, version, favicon) and the ping;
- the legacy (pre-1.7, 0xFE) ping reply;
- the login and configuration packets in order (compression, profile,
brand, features, known packs, every registry, tags);
- the play packets up to the first chunk batch, in order, with entity ids,
keep-alive ids and times left out; the chunks sent and their bytes; the
replies to the chat message and to /list;
- the console lines about the player, the chat, `list`, `say` and `stop`;
- the files the servers leave: server.properties (but the date line),
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json.
Online mode needs Mojang's session servers and is not tested.
"""
import json
import os
from pathlib import Path
import platform
import re
import shutil
import socket
import struct
import subprocess
import sys
import threading
import time
import zlib
try:
from . import lab, oracle_harness as oh, test_rust_parity as base
except ImportError:
import lab
import oracle_harness as oh
import test_rust_parity as base
NAME = 'dedicated-server-parity'
SEED = 12345
PLAYER = 'Tester'
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
'level-seed': str(SEED),
'view-distance': '4',
'simulation-distance': '4',
'spawn-protection': '0',
'max-players': '5',
'motd': '\\u00a7aHorizon \\u00a7rparity \\u00e9t\\u00e9',
'pause-when-empty-seconds': '-1',
}
def free_port():
with socket.socket() as s:
s.bind(('127.0.0.1', 0))
return s.getsockname()[1]
def icon_png():
"""A 64x64 RGBA PNG (server-icon.png)."""
rows = b''.join(b'\0' + b''.join(bytes((x * 4, y * 4, (x ^ y) * 4, 255)) for x in range(64)) for y in range(64))
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 64, 64, 8, 6, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b''))
def write_server_dir(directory, port, world=None):
if directory.exists():
shutil.rmtree(directory)
directory.mkdir(parents=True)
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()), encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
(directory / 'server-icon.png').write_bytes(icon_png())
if world is not None:
shutil.copytree(world, directory / 'world')
for lock in (directory / 'world').glob('session.lock'):
lock.unlink()
class Server:
"""A server process with its console on stdin and its log collected."""
def __init__(self, command, directory, log_name):
self.log_path = directory.parent / f'{log_name}.log'
self.log = self.log_path.open('w', encoding='utf-8')
self.lines = []
self.process = subprocess.Popen(list(map(str, command)), cwd=directory, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
encoding='utf-8', errors='replace')
self.reader = threading.Thread(target=self._read, daemon=True)
self.reader.start()
def _read(self):
for line in self.process.stdout:
self.lines.append(line.rstrip('\n'))
self.log.write(line)
self.log.flush()
def wait_for(self, pattern, timeout=300):
deadline = time.time() + timeout
regex = re.compile(pattern)
while time.time() < deadline:
if any(regex.search(l) for l in self.lines):
return
if self.process.poll() is not None:
time.sleep(0.5)
raise AssertionError(f'{self.log_path.name}: server exited ({self.process.returncode}):\n'
+ '\n'.join(self.lines[-30:]))
time.sleep(0.2)
raise AssertionError(f'{self.log_path.name}: no line matching {pattern!r} in {timeout} s:\n' + '\n'.join(self.lines[-30:]))
def console(self, command):
self.process.stdin.write(command + '\n')
self.process.stdin.flush()
def stop(self, timeout=120):
if self.process.poll() is None:
try:
self.console('stop')
self.process.wait(timeout=timeout)
except (BrokenPipeError, subprocess.TimeoutExpired):
self.process.kill()
self.process.wait()
self.reader.join(timeout=10)
self.log.close()
def legacy_ping(port):
"""The reply to a 1.6 client's 0xFE 0x01 0xFA MC|PingHost query (LegacyQueryHandler)."""
host = 'localhost'
data = (b'\xfe\x01\xfa' + struct.pack('>H', 11) + 'MC|PingHost'.encode('utf-16-be')
+ struct.pack('>H', 7 + 2 * len(host)) + bytes([78]) + struct.pack('>H', len(host))
+ host.encode('utf-16-be') + struct.pack('>I', port))
with socket.create_connection(('127.0.0.1', port), timeout=10) as s:
s.sendall(data)
reply = b''
while True:
try:
chunk = s.recv(4096)
except TimeoutError:
return reply.hex() + ' <no close>'
if not chunk:
break
reply += chunk
return reply.hex()
CONSOLE_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*)$')
KEPT = re.compile(r'Tester|\[Server\]|\[Not Secure\]|There are|Stopping|Saving|ThreadedAnvilChunkStorage|All dimensions|Unknown or incomplete')
def console_lines(lines):
"""The console lines the comparison covers, timestamps and ports aside."""
out = []
for line in lines:
m = CONSOLE_LINE.match(line)
if not m or not KEPT.search(m.group(2)):
continue
text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2))
text = re.sub(r'entity id \d+', 'entity id _', text)
out.append(f'[{m.group(1)}] {text}')
return out
def server_files(directory):
out = []
for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json']:
path = directory / name
if not path.exists():
out.append(f'{name}: missing')
continue
text = path.read_bytes().decode('iso-8859-1')
if name in ('server.properties', 'eula.txt'):
# The second comment line is the date Properties.store wrote.
text = re.sub(r'^(#[^\n]*\n)#[^\n]*\n', r'\1#<date>\n', text)
out.append(f'{name}: {text!r}')
return out
def run_side(label, command, directory, client):
server = Server(command, directory, label)
try:
server.wait_for(r'Done \(')
port = int(PROPERTIES_PORTS[label])
legacy = legacy_ping(port)
client(port, directory.parent / f'{label}-client.txt')
time.sleep(1)
server.console('list')
server.console('say console says hi')
server.wait_for(r'\[Server\] console says hi', timeout=30)
finally:
server.stop()
transcript = (directory.parent / f'{label}-client.txt').read_text(encoding='utf-8').splitlines()
return (['legacy-ping ' + legacy] + transcript + ['console ' + l for l in console_lines(server.lines)]
+ ['file ' + l for l in server_files(directory)])
PROPERTIES_PORTS = {}
def main():
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / NAME
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java'
classes = build / 'classes'
shutil.rmtree(classes, ignore_errors=True)
classes.mkdir()
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
build, 'compile-java')
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
# The world, generated once by vanilla.
generate = build / 'generate'
write_server_dir(generate, free_port())
server = Server(vanilla_server, generate, 'generate')
try:
server.wait_for(r'Done \(')
server.console('gamerule respawn_radius 0')
server.wait_for(r'respawn_radius', timeout=30)
finally:
server.stop()
world = generate / 'world'
(world / 'playerdata').mkdir(exist_ok=True)
def client(port, out):
oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build,
out.stem, timeout=300)
results = {}
for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]:
PROPERTIES_PORTS[label] = free_port()
directory = build / label
write_server_dir(directory, PROPERTIES_PORTS[label], world)
results[label] = run_side(label, command, directory, client)
(build / f'{label}.txt').write_text('\n'.join(results[label]) + '\n', encoding='utf-8')
vanilla, horizon = results['vanilla'], results['horizon']
errors = [l for l in vanilla + horizon if l.startswith('error')]
differences = []
import difflib
for line in difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=0, lineterm=''):
differences.append(line[:400])
if differences or errors:
raise AssertionError(f'{len([d for d in differences if d[:1] in "+-" and d[:3] not in ("+++", "---")])} differing lines '
f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80]))
lab.write_json(report, dict(
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
scope='Dedicated server seen by a vanilla-codec client: status, legacy ping, login, configuration, play '
'start, chunks, chat, /list, console list/say/stop, files written. Offline mode.'))
print(f'dedicated server: {len(vanilla)} transcript lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')