Draw player list heads from players' skins as vanilla does

Profiles' textures properties are unpacked as authlib does and looked up
as SkinManager does (signatures, the local player, allowed texture URLs,
downloads), skins are fetched and processed as SkinTextureDownloader does
and shown from atlas slots. The tab_list harness now runs a real
SkinManager and compares processLegacySkin over 400 PNGs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 03:16:04 +02:00
parent 360ddcbdba
commit 19d4146f04
10 changed files with 851 additions and 13 deletions
@@ -0,0 +1,32 @@
//! Headless transport for the skin half of the player list parity gate:
//! decodes each base64 PNG and runs `horizon_client::skins::process_legacy_skin`,
//! writing the RGBA result in base64, or "refused".
#![forbid(unsafe_code)]
use std::{
fs,
io::{BufWriter, Write},
path::PathBuf,
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
let [inputs, output] = args.as_slice() else {
return Err("usage: skin_image_fixture INPUTS OUTPUT".into());
};
let mut out = BufWriter::new(fs::File::create(output)?);
for line in fs::read_to_string(inputs)?
.lines()
.filter(|l| !l.is_empty())
{
let png = horizon_client::skins::base64_decode(line).ok_or("bad base64")?;
let result = horizon_client::hud::decode_bytes(&png)
.ok()
.and_then(|(w, h, rgba)| horizon_client::skins::process_legacy_skin(w, h, &rgba));
match result {
Some(rgba) => writeln!(out, "{}", horizon_client::lan::base64(&rgba))?,
None => writeln!(out, "refused")?,
}
}
Ok(())
}
@@ -2,7 +2,8 @@
//! scoreboard (teams, `list` objective, scores), listed players, header and
//! footer, replays its frames through `horizon_client::tab_list` and writes
//! the draw calls in vanilla's GuiGraphicsExtractor terms (text as styled
//! runs, faces as skin blits).
//! runs, faces as skin blits), each face's skin chosen by
//! `horizon_client::skins` from the profile's `textures` property.
#![forbid(unsafe_code)]
use horizon_client::{
component,
@@ -10,6 +11,7 @@ use horizon_client::{
hud_layout::GuiDraw,
lang,
scoreboard::{NumberFormat, RenderType, Scoreboard},
skins,
tab_list::{self, TabInputs, TabList, TabPlayer},
text::Text,
};
@@ -92,6 +94,12 @@ fn main() -> Result<()> {
format(&c["objective"]["numberFormat"]),
);
}
let uris: Vec<&str> = c["validUris"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let mut players = Vec::new();
let mut upside = Vec::new();
for p in c["players"].as_array().into_iter().flatten() {
@@ -108,6 +116,26 @@ fn main() -> Result<()> {
player.display_name = (!p["displayName"].is_null()).then(|| p["displayName"].clone());
player.list_order = p["listOrder"].as_i64().unwrap_or(0) as i32;
player.show_hat = p["showHat"].as_bool().unwrap_or(true);
if let Some(t) = p.get("textures").filter(|t| !t.is_null()) {
let signature = match t["signature"].as_str() {
None => skins::Signature::Unsigned,
Some("valid") => skins::Signature::Signed,
Some(_) => skins::Signature::Invalid,
};
let textures = skins::unpack(t["value"].as_str().unwrap_or(""), signature, &uris);
let local = c["local"].as_str() == p["uuid"].as_str();
let download = |_, url: &str| {
let hash = skins::texture_hash(url).unwrap_or_default();
match c["downloads"][&hash].as_str() {
Some("pending") => skins::Download::Pending,
Some("fail") => skins::Download::Failed,
_ => skins::Download::Ready,
}
};
if let Some(skin) = skins::lookup(&textures, !local, download) {
player.skin = skin;
}
}
players.push(player);
}
let mut list = TabList::default();
+10
View File
@@ -743,6 +743,10 @@ struct Game<'a> {
dragon_model: Option<horizon_client::mobs::Part>,
/// Map textures waiting for the next HUD batch to upload them.
map_patches: Vec<horizon_client::font::Patch>,
/// Player skin downloads, and which skin each atlas skin slot holds
/// (least recently shown first).
skin_downloads: horizon_client::skins::Downloader,
skin_slots: Vec<(String, usize)>,
cart_models: minecarts::CartModels,
/// The boat the player rides.
riding: Option<u32>,
@@ -8375,6 +8379,12 @@ pub fn run() -> Result<()> {
breath_clouds: Vec::new(),
dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"),
map_patches: Vec::new(),
skin_downloads: horizon_client::skins::Downloader::new(
std::env::current_dir()
.unwrap_or_default()
.join("assets/skins"),
),
skin_slots: Vec::new(),
cart_models: minecarts::CartModels::load(&root),
riding: None,
ender_items: vec![None; 27],
+87 -4
View File
@@ -105,6 +105,8 @@ pub(super) struct Remote {
/// `ClientPacketListener.playerInfoMap` as player-list entries, and
/// which of them are listed.
tab_players: HashMap<u128, horizon_client::tab_list::TabPlayer>,
/// Each listed profile's unpacked `textures` property.
skin_textures: HashMap<u128, horizon_client::skins::Textures>,
listed: std::collections::HashSet<u128>,
/// `ClientboundLoginPacket.onlineMode`: the player list shows heads.
online_mode: bool,
@@ -234,6 +236,7 @@ impl Game<'_> {
action_bar: None,
players: HashMap::new(),
tab_players: HashMap::new(),
skin_textures: HashMap::new(),
listed: Default::default(),
online_mode: false,
level_players: HashMap::new(),
@@ -1120,6 +1123,21 @@ impl Game<'_> {
r.tab_players.entry(e.uuid).or_insert_with(|| {
horizon_client::tab_list::TabPlayer::new(e.uuid, name.clone())
});
if let Some(t) = e.properties.iter().find(|p| p.name == "textures")
{
// Without the services' profile property keys a
// signature can't be checked; a signed property
// counts as genuine.
use horizon_client::skins::{self, Signature};
let signature = if t.signature.is_some() {
Signature::Signed
} else {
Signature::Unsigned
};
let textures =
skins::unpack(&t.value, signature, &skins::TEXTURE_URIS);
r.skin_textures.entry(e.uuid).or_insert(textures);
}
}
}
}
@@ -1162,6 +1180,7 @@ impl Game<'_> {
for u in p.uuids {
r.players.remove(&u);
r.tab_players.remove(&u);
r.skin_textures.remove(&u);
r.listed.remove(&u);
}
}
@@ -1327,17 +1346,41 @@ impl Game<'_> {
_ => {}
}
}
/// The player list's view of the connection: the listed players, online
/// mode, and which players are in the level with an upside-down name.
/// The player list's view of the connection: the listed players (with
/// their downloaded skins once ready), online mode, and which players
/// are in the level with an upside-down name.
pub(super) fn remote_tab_players(
&self,
&mut self,
) -> Option<(Vec<horizon_client::tab_list::TabPlayer>, bool, Vec<u128>)> {
let r = self.remote.as_ref()?;
let players: Vec<_> = r
let mut players: Vec<_> = r
.listed
.iter()
.filter_map(|u| r.tab_players.get(u).cloned())
.collect();
for p in &mut players {
let Some(textures) = r.skin_textures.get(&p.uuid) else {
continue;
};
// PlayerInfo.createSkinLookup: only the local player's own skin
// may be unsigned.
let downloads = &mut self.skin_downloads;
let skin = horizon_client::skins::lookup(textures, p.uuid != r.profile, |kind, url| {
downloads.state(kind, url)
});
if let Some(skin) = skin {
p.skin = skin;
}
}
for (location, rgba) in self.skin_downloads.take_ready() {
self.store_skin(location, rgba);
}
for p in &mut players {
if p.skin.starts_with("skins/") && !self.show_skin(&p.skin) {
p.skin = horizon_client::tab_list::default_skin(p.uuid).to_owned();
}
}
let r = self.remote.as_ref()?;
let upside_down = players
.iter()
.filter(|p| {
@@ -1348,6 +1391,46 @@ impl Game<'_> {
.collect();
Some((players, r.online_mode, upside_down))
}
/// Puts a downloaded skin in an atlas skin slot: a free one, else the
/// least recently shown.
fn store_skin(&mut self, location: String, rgba: Vec<u8>) {
use horizon_client::hud::SKIN_SLOTS;
let slot = if self.skin_slots.len() < SKIN_SLOTS {
self.skin_slots.len()
} else {
let (old, slot) = self.skin_slots.remove(0);
self.res.atlas.sprites.remove(&old);
slot
};
let Some(rect) = self
.res
.atlas
.sprites
.get(&format!("horizon/skin{slot}"))
.copied()
else {
return;
};
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
width: 64,
height: 64,
rgba,
});
self.res.atlas.sprites.insert(location.clone(), rect);
self.skin_slots.push((location, slot));
}
/// Whether a downloaded skin is in the atlas, marking it recently shown.
fn show_skin(&mut self, location: &str) -> bool {
let Some(i) = self.skin_slots.iter().position(|e| e.0 == location) else {
return false;
};
let e = self.skin_slots.remove(i);
self.skin_slots.push(e);
true
}
/// ChatType decoration: `chat.translation_key` with sender/content parameters.
fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String {
let Some(r) = self.remote.as_ref() else {
+11 -1
View File
@@ -31,8 +31,14 @@ pub struct HudAtlas {
pub const GLYPH_ROWS: u32 = 512;
/// 128x128 atlas slots for map textures.
pub const MAP_SLOTS: usize = 16;
/// Atlas slots for downloaded player skins (`skins/<sha1>`), 64x64 each.
pub const SKIN_SLOTS: usize = 32;
pub fn decode(path: &Path) -> Result<(u32, u32, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?));
decode_bytes(&fs::read(path)?)
}
/// A PNG in memory as RGBA pixels.
pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info()?;
let mut bytes = vec![0; reader.output_buffer_size().ok_or("image too large")?];
@@ -194,6 +200,10 @@ impl HudAtlas {
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
}
// Downloaded skins (game/scoreboard.rs) likewise.
for i in 0..SKIN_SLOTS {
images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4]));
}
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
let width = 4096u32;
let mut placements = Vec::with_capacity(images.len());
+1
View File
@@ -95,6 +95,7 @@ pub mod server;
pub mod settings;
pub mod shadows;
pub mod signs;
pub mod skins;
pub mod snbt;
pub mod sound_engine;
pub mod sound_events;
+442
View File
@@ -0,0 +1,442 @@
//! Player skins from profile `textures` properties: authlib's
//! `MinecraftServicesSessionService.unpackTextures`, vanilla's
//! `SkinManager` lookup (which texture a player shows, and when the default
//! one) and `SkinTextureDownloader.processLegacySkin`.
/// `Property.hasSignature` and the services key check, as authlib's
/// `SignatureState`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Signature {
Unsigned,
Signed,
Invalid,
}
/// `MinecraftProfileTextures`: the texture URLs a profile names. Empty when
/// the payload doesn't decode or names a URL outside the allowed domains.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Textures {
pub skin: Option<String>,
pub cape: Option<String>,
pub elytra: Option<String>,
pub signed: bool,
}
/// The `getTexture` endpoint's valid URIs from Minecraft services discovery.
pub const TEXTURE_URIS: [&str; 2] = [
"https://textures.minecraft.net/texture/{textureId}",
"http://textures.minecraft.net/texture/{textureId}",
];
/// `java.util.Base64.getDecoder().decode`.
pub fn base64_decode(text: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(text.len() / 4 * 3);
let (mut bits, mut shift) = (0u32, 18i32);
let bytes: Vec<char> = text.chars().collect();
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
i += 1;
let b = match c {
'A'..='Z' => c as u32 - 'A' as u32,
'a'..='z' => c as u32 - 'a' as u32 + 26,
'0'..='9' => c as u32 - '0' as u32 + 52,
'+' => 62,
'/' => 63,
'=' => {
if shift == 6 && (i == bytes.len() || bytes[i] != '=') || shift == 18 {
return None;
}
if shift == 6 {
i += 1;
}
break;
}
_ => return None,
};
bits |= b << shift;
shift -= 6;
if shift < 0 {
out.extend([(bits >> 16) as u8, (bits >> 8) as u8, bits as u8]);
shift = 18;
bits = 0;
}
}
match shift {
6 => out.push((bits >> 16) as u8),
0 => out.extend([(bits >> 16) as u8, (bits >> 8) as u8]),
12 => return None,
_ => {}
}
(i >= bytes.len()).then_some(out)
}
/// `unpackTextures(property)`: the textures of a `textures` property's
/// base64 JSON payload.
pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Textures {
let empty = Textures::default();
let Some(json) = base64_decode(value)
.map(|b| String::from_utf8_lossy(&b).into_owned())
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
else {
return empty;
};
let Some(textures) = json.get("textures").and_then(|t| t.as_object()) else {
return empty;
};
if textures.is_empty() {
return empty;
}
let mut out = Textures {
signed: signature == Signature::Signed,
..empty.clone()
};
for (kind, texture) in textures {
let Some(url) = texture.get("url").and_then(|u| u.as_str()) else {
return empty;
};
let allowed = valid_uris
.iter()
.any(|u| url.starts_with(&u.replace("{textureId}", "")));
if !allowed {
return empty;
}
let slot = match kind.as_str() {
"SKIN" => &mut out.skin,
"CAPE" => &mut out.cape,
"ELYTRA" => &mut out.elytra,
_ => continue,
};
*slot = Some(url.to_owned());
}
out
}
/// `MinecraftProfileTexture.getHash`: the base name of the URL's path.
pub fn texture_hash(url: &str) -> Option<String> {
let rest = url.split_once("://")?.1;
let path = &rest[rest.find('/').unwrap_or(rest.len())..];
let path = &path[..path.find(['?', '#']).unwrap_or(path.len())];
let name = &path[path.rfind(['/', '\\']).map_or(0, |i| i + 1)..];
Some(name[..name.rfind('.').unwrap_or(name.len())].to_owned())
}
/// `SkinManager.TextureCache.registerTexture`: the texture id of a skin,
/// `skins/` and the SHA-1 of its hash's UTF-16 code units.
pub fn skin_location(hash: &str) -> String {
let units: Vec<u8> = hash.encode_utf16().flat_map(u16::to_le_bytes).collect();
let digest = sha1(&units);
let mut out = String::from("skins/");
for b in digest {
out.push_str(&format!("{b:02x}"));
}
out
}
/// Where a texture download stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Download {
Ready,
Pending,
Failed,
}
/// `MinecraftProfileTexture.Type`: which texture cache a download is in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
Skin,
Cape,
Elytra,
}
/// `SkinManager.createLookup(profile, requireSecure).get()`: the skin
/// texture a player shows, or `None` for their default skin. `download`
/// tells how the skin, cape and elytra texture downloads stand.
pub fn lookup(
textures: &Textures,
require_secure: bool,
mut download: impl FnMut(Kind, &str) -> Download,
) -> Option<String> {
let mut skin = None;
let mut state = Download::Ready;
let urls = [
(Kind::Skin, &textures.skin),
(Kind::Cape, &textures.cape),
(Kind::Elytra, &textures.elytra),
];
for (kind, url) in urls {
let Some(url) = url else { continue };
// registerTexture computes the hash first; a bad URL fails the lookup.
let hash = texture_hash(url)?;
if kind == Kind::Skin {
skin = Some(skin_location(&hash));
}
match download(kind, url) {
Download::Failed => return None,
Download::Pending => state = Download::Pending,
Download::Ready => {}
}
}
if state != Download::Ready || require_secure && !textures.signed {
return None;
}
skin
}
/// `SkinTextureDownloader.processLegacySkin` on RGBA pixels: 64x32 skins
/// get the 64x64 layout, and the opaque parts lose their alpha. `None` for
/// any other size (the download fails).
pub fn process_legacy_skin(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
if width != 64 || height != 32 && height != 64 {
return None;
}
let legacy = height == 32;
let mut img = vec![0u8; 64 * 64 * 4];
let n = rgba.len().min(img.len());
img[..n].copy_from_slice(&rgba[..n]);
let at = |x: i32, y: i32| ((y * 64 + x) * 4) as usize;
if legacy {
let rects = [
(4, 16, 16, 32, 4, 4),
(8, 16, 16, 32, 4, 4),
(0, 20, 24, 32, 4, 12),
(4, 20, 16, 32, 4, 12),
(8, 20, 8, 32, 4, 12),
(12, 20, 16, 32, 4, 12),
(44, 16, -8, 32, 4, 4),
(48, 16, -8, 32, 4, 4),
(40, 20, 0, 32, 4, 12),
(44, 20, -8, 32, 4, 12),
(48, 20, -16, 32, 4, 12),
(52, 20, -8, 32, 4, 12),
];
for (sx, sy, ox, oy, w, h) in rects {
for y in 0..h {
for x in 0..w {
let (s, d) = (at(sx + x, sy + y), at(sx + ox + w - 1 - x, sy + oy + y));
let p: [u8; 4] = img[s..s + 4].try_into().unwrap();
img[d..d + 4].copy_from_slice(&p);
}
}
}
}
let no_alpha = |img: &mut Vec<u8>, x0: i32, y0: i32, x1: i32, y1: i32| {
for x in x0..x1 {
for y in y0..y1 {
img[at(x, y) + 3] = 255;
}
}
};
no_alpha(&mut img, 0, 0, 32, 16);
if legacy {
// doNotchTransparencyHack: a fully opaque hat layer is cleared.
let opaque = (32..64).all(|x| (0..32).all(|y| img[at(x, y) + 3] >= 128));
if opaque {
for x in 32..64 {
for y in 0..32 {
img[at(x, y) + 3] = 0;
}
}
}
}
no_alpha(&mut img, 0, 16, 64, 32);
no_alpha(&mut img, 16, 48, 48, 64);
Some(img)
}
/// `SkinTextureDownloader`: fetches textures on background threads, from
/// the local cache (`<root>/<2 hex>/<sha1>`) or over HTTP, keeping each one
/// by kind and hash as vanilla's `TextureCache`s do. Plain HTTP only: an
/// `https` texture that isn't cached fails, and the player keeps their
/// default skin.
pub struct Downloader {
root: std::path::PathBuf,
states: std::collections::HashMap<(Kind, String), Download>,
done: std::sync::mpsc::Receiver<((Kind, String), Option<Vec<u8>>)>,
send: std::sync::mpsc::Sender<((Kind, String), Option<Vec<u8>>)>,
ready: Vec<(String, Vec<u8>)>,
}
impl Downloader {
pub fn new(root: std::path::PathBuf) -> Self {
let (send, done) = std::sync::mpsc::channel();
Self {
root,
states: Default::default(),
done,
send,
ready: Vec::new(),
}
}
/// How the download of `url` stands, starting it the first time.
pub fn state(&mut self, kind: Kind, url: &str) -> Download {
while let Ok((key, image)) = self.done.try_recv() {
let state = match image {
Some(rgba) => {
if key.0 == Kind::Skin {
self.ready.push((skin_location(&key.1), rgba));
}
Download::Ready
}
None => Download::Failed,
};
self.states.insert(key, state);
}
let Some(hash) = texture_hash(url) else {
return Download::Failed;
};
let key = (kind, hash);
if let Some(state) = self.states.get(&key) {
return *state;
}
self.states.insert(key.clone(), Download::Pending);
let digest: String = skin_location(&key.1)["skins/".len()..].to_owned();
let file = self
.root
.join(if digest.len() > 2 { &digest[..2] } else { "xx" })
.join(&digest);
let (url, send) = (url.to_owned(), self.send.clone());
std::thread::spawn(move || {
let bytes = std::fs::read(&file).ok().or_else(|| {
let body = http_get(&url)?;
let _ = std::fs::create_dir_all(file.parent()?);
let _ = std::fs::write(&file, &body);
Some(body)
});
let image = bytes
.and_then(|b| crate::hud::decode_bytes(&b).ok())
.and_then(|(w, h, rgba)| match kind {
Kind::Skin => process_legacy_skin(w, h, &rgba),
_ => Some(rgba),
});
let _ = send.send((key, image));
});
Download::Pending
}
/// Skins that finished since the last call: texture id and 64x64 RGBA.
pub fn take_ready(&mut self) -> Vec<(String, Vec<u8>)> {
std::mem::take(&mut self.ready)
}
}
/// A plain HTTP/1.1 GET; the body of a 2xx answer.
fn http_get(url: &str) -> Option<Vec<u8>> {
use std::io::{Read, Write};
let rest = url.strip_prefix("http://")?;
let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
let path = if path.is_empty() { "/" } else { path };
let path = &path[..path.find('#').unwrap_or(path.len())];
let host = authority.split(':').next()?;
let address = if authority.contains(':') {
authority.to_owned()
} else {
format!("{authority}:80")
};
let timeout = std::time::Duration::from_secs(15);
let addr = std::net::ToSocketAddrs::to_socket_addrs(&address)
.ok()?
.next()?;
let mut stream = std::net::TcpStream::connect_timeout(&addr, timeout).ok()?;
stream.set_read_timeout(Some(timeout)).ok()?;
write!(
stream,
"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: Java\r\n\r\n"
)
.ok()?;
let mut response = Vec::new();
stream.take(16 << 20).read_to_end(&mut response).ok()?;
let split = response.windows(4).position(|w| w == b"\r\n\r\n")?;
let head = String::from_utf8_lossy(&response[..split]).to_ascii_lowercase();
let mut body = response[split + 4..].to_vec();
let status: u32 = head.split_whitespace().nth(1)?.parse().ok()?;
if status / 100 != 2 {
return None;
}
if head.contains("transfer-encoding: chunked") {
let (mut out, mut at) = (Vec::new(), 0);
loop {
let end = at + body[at..].windows(2).position(|w| w == b"\r\n")?;
let line = String::from_utf8_lossy(&body[at..end]);
let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?;
if size == 0 {
break;
}
out.extend_from_slice(body.get(end + 2..end + 2 + size)?);
at = end + 4 + size;
}
body = out;
}
Some(body)
}
/// SHA-1 (FIPS 180-4).
pub fn sha1(data: &[u8]) -> [u8; 20] {
let mut h: [u32; 5] = [
0x6745_2301,
0xEFCD_AB89,
0x98BA_DCFE,
0x1032_5476,
0xC3D2_E1F0,
];
let mut msg = data.to_vec();
msg.push(0x80);
while msg.len() % 64 != 56 {
msg.push(0);
}
msg.extend((data.len() as u64 * 8).to_be_bytes());
for block in msg.chunks_exact(64) {
let mut w = [0u32; 80];
for (i, word) in block.chunks_exact(4).enumerate() {
w[i] = u32::from_be_bytes(word.try_into().unwrap());
}
for i in 16..80 {
w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
}
let [mut a, mut b, mut c, mut d, mut e] = h;
for (i, wi) in w.iter().enumerate() {
let (f, k) = match i {
0..=19 => ((b & c) | (!b & d), 0x5A82_7999),
20..=39 => (b ^ c ^ d, 0x6ED9_EBA1),
40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC),
_ => (b ^ c ^ d, 0xCA62_C1D6),
};
let t = a
.rotate_left(5)
.wrapping_add(f)
.wrapping_add(e)
.wrapping_add(k)
.wrapping_add(*wi);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = t;
}
for (x, y) in h.iter_mut().zip([a, b, c, d, e]) {
*x = x.wrapping_add(y);
}
}
let mut out = [0u8; 20];
for (i, x) in h.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&x.to_be_bytes());
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha1_and_base64() {
let hex: String = sha1(b"abc").iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(hex, "a9993e364706816aba3e25717850c26c9cd0d89d");
assert_eq!(base64_decode("aGk=").unwrap(), b"hi");
assert_eq!(base64_decode("aGk").unwrap(), b"hi");
assert!(base64_decode("a").is_none());
assert!(base64_decode("aGk=x").is_none());
assert_eq!(
texture_hash("http://textures.minecraft.net/texture/abc.png?x=1").unwrap(),
"abc"
);
}
}
@@ -0,0 +1,47 @@
package dev.horizonlab.parity;
import com.mojang.blaze3d.platform.NativeImage;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Base64;
import net.minecraft.client.renderer.texture.SkinTextureDownloader;
/**
* Decodes downloaded skin PNGs as vanilla does (NativeImage.read) and runs
* SkinTextureDownloader.processLegacySkin on them: 64x32 skins get the 64x64
* layout, opaque parts lose their alpha, other sizes are refused.
*
* Input lines: base64 PNG. Output lines: base64 RGBA pixels of the result,
* or "refused".
*/
public final class VanillaSkinImageOracle {
public static void main(String[] args) throws Exception {
Method process = SkinTextureDownloader.class.getDeclaredMethod("processLegacySkin", NativeImage.class, String.class);
process.setAccessible(true);
var out = new StringBuilder();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.isBlank()) continue;
String result;
try {
var image = (NativeImage) process.invoke(null, NativeImage.read(Base64.getDecoder().decode(line)), "case");
var pixels = new byte[image.getWidth() * image.getHeight() * 4];
for (int y = 0, i = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int argb = image.getPixel(x, y);
pixels[i++] = (byte) (argb >> 16);
pixels[i++] = (byte) (argb >> 8);
pixels[i++] = (byte) argb;
pixels[i++] = (byte) (argb >>> 24);
}
}
image.close();
result = Base64.getEncoder().encodeToString(pixels);
} catch (java.lang.reflect.InvocationTargetException e) {
result = "refused";
}
out.append(result).append('\n');
}
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
}
}
@@ -2,6 +2,22 @@ package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.services.MinecraftServicesDiscoveryService;
import com.mojang.authlib.services.MinecraftServicesSessionService;
import com.mojang.authlib.services.ServicesKeyInfo;
import com.mojang.authlib.services.ServicesKeySet;
import com.mojang.authlib.services.response.discovery.Discovery;
import com.mojang.authlib.services.response.discovery.DiscoveryResponse;
import com.mojang.authlib.services.response.discovery.Endpoint;
import com.mojang.authlib.services.response.discovery.Endpoints;
import java.util.concurrent.CompletableFuture;
import net.minecraft.client.renderer.texture.SkinTextureDownloader;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.core.ClientAsset;
import net.minecraft.server.Services;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import com.mojang.serialization.JsonOps;
import java.lang.reflect.*;
@@ -47,6 +63,9 @@ import net.minecraft.world.scores.criteria.ObjectiveCriteria;
* Visibility changes clear the heart states as setVisible does (without
* the narration).
*
* Profiles may carry a signed or unsigned `textures` property; a real
* SkinManager (see skinManager) decides each face's texture.
*
* Input lines: case JSON. Output lines: {case, frames:[[draws]...]} or {case, error}.
*/
public final class VanillaTabListOracle {
@@ -106,6 +125,47 @@ public final class VanillaTabListOracle {
};
}
/**
* A real SkinManager over a real MinecraftServicesSessionService whose
* discovery lists the case's texture URIs and whose profile property key
* accepts the signature "valid". Downloads succeed, fail or never finish
* by texture hash, as the case says.
*/
static SkinManager skinManager(JsonObject c) throws Exception {
var uris = new ArrayList<String>();
for (var u : c.getAsJsonArray("validUris")) uris.add(u.getAsString());
var endpoints = new Endpoints(Map.of("getTexture", new Endpoint(null, uris)));
var response = new DiscoveryResponse("prod", "minecraft", new Discovery("minecraft", Endpoints.empty(), Endpoints.empty(), Endpoints.empty(), endpoints, Endpoints.empty()));
var dc = MinecraftServicesDiscoveryService.class.getDeclaredConstructor(java.net.Proxy.class, boolean.class, java.util.function.Supplier.class);
dc.setAccessible(true);
var discovery = dc.newInstance(java.net.Proxy.NO_PROXY, false, (java.util.function.Supplier<DiscoveryResponse>) () -> response);
var key = (ServicesKeyInfo) Proxy.newProxyInstance(ServicesKeyInfo.class.getClassLoader(), new Class<?>[] {ServicesKeyInfo.class},
(proxy, method, a) -> switch (method.getName()) {
case "validateProperty" -> "valid".equals(((Property) a[0]).signature());
case "keyBitCount" -> 4096;
default -> throw new UnsupportedOperationException(method.getName());
});
ServicesKeySet keys = type -> List.of(key);
var sc = MinecraftServicesSessionService.class.getDeclaredConstructor(ServicesKeySet.class, java.net.Proxy.class, MinecraftServicesDiscoveryService.class);
sc.setAccessible(true);
var session = sc.newInstance(keys, java.net.Proxy.NO_PROXY, discovery);
var downloads = c.getAsJsonObject("downloads");
var downloader = new SkinTextureDownloader(java.net.Proxy.NO_PROXY, null, Runnable::run) {
@Override
public CompletableFuture<ClientAsset.Texture> downloadAndRegisterSkin(Identifier textureId, Path localCopy, String url, boolean processLegacySkin) {
String hash = new MinecraftProfileTexture(url, Map.of()).getHash();
String state = downloads.has(hash) ? downloads.get(hash).getAsString() : "ok";
return switch (state) {
case "ok" -> CompletableFuture.completedFuture(new ClientAsset.DownloadedTexture(textureId, url));
case "pending" -> new CompletableFuture<>();
default -> CompletableFuture.failedFuture(new java.io.IOException("download failed"));
};
}
};
var services = new Services(session, keys, null, null, null);
return new SkinManager(Path.of("skins"), services, downloader, Runnable::run);
}
/** Records GuiGraphicsExtractor calls. */
public static final class Capture extends GuiGraphicsExtractor {
private Capture() { super(null, null, 0, 0); }
@@ -219,18 +279,35 @@ public final class VanillaTabListOracle {
var player = alloc(LocalPlayer.class);
put(player, LocalPlayer.class, "connection", connection);
put(mc, Minecraft.class, "player", player);
var user = alloc(net.minecraft.client.User.class);
put(user, net.minecraft.client.User.class, "uuid", c.get("local").isJsonNull() ? new UUID(0, 0) : UUID.fromString(c.get("local").getAsString()));
put(mc, Minecraft.class, "user", user);
var skins = skinManager(c);
put(mc, Minecraft.class, "skinManager", skins);
for (var p : c.getAsJsonArray("players")) {
var o = p.getAsJsonObject();
var uuid = UUID.fromString(o.get("uuid").getAsString());
var profile = new GameProfile(uuid, o.get("name").getAsString());
var properties = com.google.common.collect.LinkedHashMultimap.<String, Property>create();
if (o.has("textures") && !o.get("textures").isJsonNull()) {
var t = o.getAsJsonObject("textures");
var sig = t.get("signature");
properties.put("textures", sig.isJsonNull()
? new Property("textures", t.get("value").getAsString())
: new Property("textures", t.get("value").getAsString(), sig.getAsString()));
}
var profile = new GameProfile(uuid, o.get("name").getAsString(), new PropertyMap(properties));
// Let the lookup's unpacking and downloads run before the first frame,
// as they would have by the time a player list shows.
try {
skins.get(profile).get(1, java.util.concurrent.TimeUnit.SECONDS);
} catch (java.util.concurrent.TimeoutException pending) {
}
var info = new PlayerInfo(profile, false);
put(info, PlayerInfo.class, "gameMode", GameType.byId(o.get("gameMode").getAsInt()));
put(info, PlayerInfo.class, "latency", o.get("latency").getAsInt());
if (!o.get("displayName").isJsonNull()) info.setTabListDisplayName(component(o.get("displayName")));
info.setTabListOrder(o.get("listOrder").getAsInt());
info.setShowHat(o.get("showHat").getAsBoolean());
var skin = net.minecraft.client.resources.DefaultPlayerSkin.get(uuid);
put(info, PlayerInfo.class, "skinLookup", (java.util.function.Supplier<?>) () -> skin);
listed.add(info);
if (o.get("inLevel").getAsBoolean()) {
var entity = alloc(RemotePlayer.class);
+112 -4
View File
@@ -4,7 +4,8 @@
The Java oracle (VanillaTabListOracle) runs vanilla's own
PlayerTabOverlay.extractRenderState, frame after frame, on a stand-in client
whose connection lists the case's players (game mode, latency, display name,
list order, hat layer, online mode for heads), whose level holds some of
list order, hat layer, online mode for heads, skins from each profile's signed or
unsigned `textures` property through a real SkinManager), whose level holds some of
them (upside-down Dinnerbone and Grumm) and whose real Scoreboard has the
case's teams (colour, prefix, suffix), `list` objective (integer or hearts,
number formats) and scores, with the header, footer, row background option
@@ -12,9 +13,16 @@ and Hud ticks. It records every fill, text (as styled runs), sprite and
face blit. `examples/tab_list_fixture` lays out the same frames with
`horizon_client::tab_list`; the ordered call lists must agree.
Downloaded skin images are compared too: VanillaSkinImageOracle decodes
PNGs as NativeImage does and runs SkinTextureDownloader.processLegacySkin;
`examples/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree.
test_tab_list_parity.py [--count N] [--detail N]
"""
import argparse
import base64
import struct
import zlib
import json
import os
import random
@@ -68,6 +76,45 @@ def number_format(rng):
return {'type': 'fixed', 'value': component(rng, 1)}
TEXTURE_URIS = ['https://textures.minecraft.net/texture/{textureId}', 'http://textures.minecraft.net/texture/{textureId}']
def textures_property(rng, name, hashes):
"""A `textures` profile property: base64 JSON naming skin, cape and
elytra URLs (some outside the allowed domains or malformed), signed
validly, invalidly or not at all."""
def url():
h = rng.choice(hashes)
return rng.choice([
'http://textures.minecraft.net/texture/' + h, 'https://textures.minecraft.net/texture/' + h,
'http://textures.minecraft.net/texture/' + h + '.png', 'https://textures.minecraft.net/texture/' + h + '?v=2',
'https://evil.example.net/texture/' + h, 'http://textures.minecraft.net.evil/texture/' + h,
'http://textures.minecraft.net/texture/a/b/' + h + '#frag'])
textures = {}
if rng.random() < 0.9:
textures['SKIN'] = {'url': url()}
if rng.random() < 0.4:
textures['SKIN']['metadata'] = {'model': 'slim'}
if rng.random() < 0.25:
textures['CAPE'] = {'url': url()}
if rng.random() < 0.08:
textures['ELYTRA'] = {'url': url()}
if rng.random() < 0.03:
textures['SKIN'] = {}
payload = {'timestamp': rng.randint(0, 2**41), 'profileId': uuid.UUID(int=rng.getrandbits(128)).hex,
'profileName': name, 'textures': textures}
if rng.random() < 0.2:
payload['signatureRequired'] = True
text = rng.choice([json.dumps(payload)] * 12 + ['not json', 'null', '', '{"textures": {}}', '[1, 2]'])
value = base64.b64encode(text.encode()).decode()
kind = rng.random()
if kind < 0.05:
value = value.rstrip('=')
elif kind < 0.08:
value = rng.choice(['%%%', 'abc', 'YQ==YQ==', value + '!'])
return {'value': value, 'signature': rng.choice([None, 'valid', 'valid', 'invalid'])}
def cases(count):
rng = random.Random(0x544142)
out = []
@@ -79,6 +126,7 @@ def cases(count):
rng.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') for _ in range(rng.randint(1, 16)))
if name.lower() not in {x.lower() for x in names}:
names.append(name)
hashes = [''.join(rng.choice('0123456789abcdef') for _ in range(64)) for _ in range(rng.randint(1, 12))]
players = []
for name in names:
players.append({
@@ -88,7 +136,9 @@ def cases(count):
'displayName': component(rng, rng.randint(1, 2)) if rng.random() < 0.2 else None,
'listOrder': rng.choice([0, 0, 0, 1, -1, 5, 2147483647, -2147483648]),
'showHat': rng.random() < 0.8, 'inLevel': rng.random() < 0.5,
'textures': textures_property(rng, name, hashes) if rng.random() < 0.75 else None,
})
downloads = {h: rng.choice(['ok'] * 20 + ['fail'] * 3 + ['pending']) for h in hashes if rng.random() < 0.9}
teams = []
for t in range(rng.choice([0, 0, 1, 2, 4])):
members = [p['name'] for p in players if rng.random() < 0.3]
@@ -125,7 +175,45 @@ def cases(count):
out.append({'width': rng.choice([427, 320, 480, 640, 961, 160, 90, 300]), 'onlineMode': rng.random() < 0.7,
'backgroundForChatOnly': rng.random() < 0.8, 'opacity': rng.choice([0.5, 0.0, 1.0, 0.37]),
'header': header, 'footer': footer, 'teams': teams, 'objective': objective, 'players': players,
'frames': frames})
'frames': frames, 'downloads': downloads,
'local': rng.choice(players)['uuid'] if rng.random() < 0.3 else None,
'validUris': rng.choice([TEXTURE_URIS] * 6 + [TEXTURE_URIS[:1], []])})
return out
def png(width, height, color_type, depth, rows):
"""A PNG of the given colour type (0 grey, 2 RGB, 4 grey+alpha, 6 RGBA)."""
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
raw = b''.join(b'\0' + row for row in rows)
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, depth, color_type, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b''))
def skin_images(count):
"""Downloaded skins: 64x32 legacy and 64x64 ones in every 8-bit colour
type (and 16-bit RGBA), with opaque, clear and mixed hat layers, and a
few sizes vanilla refuses."""
rng = random.Random(0x534B494E)
out = []
for _ in range(count):
width, height = rng.choice([(64, 32)] * 5 + [(64, 64)] * 5 + [(32, 32), (64, 48), (128, 64), (64, 128), (1, 1)])
color_type, depth = rng.choice([(6, 8)] * 6 + [(2, 8), (0, 8), (4, 8), (6, 16)])
channels = {0: 1, 2: 3, 4: 2, 6: 4}[color_type]
alpha = rng.choice(['opaque', 'clear', 'mixed', 'random'])
rows = []
for y in range(height):
row = bytearray()
for x in range(width):
px = [rng.randrange(256) for _ in range(channels)]
if color_type in (4, 6):
a = {'opaque': rng.randint(128, 255), 'clear': 0, 'mixed': rng.choice([0, 255, 127, 128]),
'random': rng.randrange(256)}[alpha]
px[-1] = a
for v in px:
row += bytes([v, rng.randrange(256)]) if depth == 16 else bytes([v])
rows.append(bytes(row))
out.append(base64.b64encode(png(width, height, color_type, depth, rows)).decode())
return out
@@ -133,6 +221,7 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=1000)
parser.add_argument('--detail', type=int, default=3)
parser.add_argument('--images', type=int, default=400)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
@@ -149,11 +238,30 @@ def main():
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle'))], 'compile-java')
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle', 'VanillaSkinImageOracle'))], 'compile-java')
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'tab_list_fixture', '--',
resources, inputs, build / 'rust.jsonl'], 'rust')
images = build / 'skins.txt'; images.write_text(''.join(i + '\n' for i in skin_images(args.images)))
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSkinImageOracle',
images, build / 'vanilla-skins.txt'], 'vanilla-skins')
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'skin_image_fixture', '--',
images, build / 'rust-skins.txt'], 'rust-skins')
vanilla_skins = (build / 'vanilla-skins.txt').read_text().splitlines()
rust_skins = (build / 'rust-skins.txt').read_text().splitlines()
assert len(vanilla_skins) == len(rust_skins) == args.images
skin_bad = [i for i, (a, b) in enumerate(zip(vanilla_skins, rust_skins)) if a != b]
for i in skin_bad[:args.detail]:
a, b = vanilla_skins[i], rust_skins[i]
if 'refused' in (a, b):
print(f'SKIN MISMATCH image {i}: vanilla {a[:20]}, horizon {b[:20]}')
else:
a, b = base64.b64decode(a), base64.b64decode(b)
k = next(k for k in range(min(len(a), len(b))) if a[k] != b[k]) // 4
print(f'SKIN MISMATCH image {i}: pixel ({k % 64}, {k // 64}) vanilla {a[k*4:k*4+4].hex()} horizon {b[k*4:k*4+4].hex()}')
print(f'{args.images - len(skin_bad)}/{args.images} processed skin images match '
f'({sum(v == "refused" for v in vanilla_skins)} refused)')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust)
@@ -175,7 +283,7 @@ def main():
print(f' frame {i}, call {k} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}')
print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} player lists match ({frames} frames, {calls} calls); '
f'{len(errors)} oracle errors')
if bad or errors:
if bad or errors or skin_bad:
sys.exit(1)
print('tab list parity ok')