ghast-client 0.5.2

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! The engine replay of a modern version's held-dig golden (`tests/golden/<version>/held_dig.jsonl.gz`,
//! oracle `HeldDig`): per tick a scripted look, the attack / use buttons, hotbar / drop / swap keys
//! and server packets (block updates, our slots, the held slot, teleports, game mode changes, a
//! zombie to attack, as wire bytes); the real client's pick and `handleKeybinds` attack / use part turned them into
//! packets. Here the server packets take the client's route (sim, inventory, engine), the keys are
//! the behaviour's, and every packet the engine sends in a tick, encoded by the version's wire
//! layer, must equal the real client's (name order and body bytes). Mounted once per modern
//! version with that version's modules as `super::*` (as `engine_modern_tests.rs`).

#![allow(clippy::too_many_lines)]

use super::*;
use crate::interest::Interests;
use crate::version::ClientVersion;
use ghast_protocol::packet::PacketFilter;
use serde_json::Value;
use std::io::BufRead;

fn unhex(s: &str) -> bytes::Bytes {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
        .collect::<Vec<u8>>()
        .into()
}

fn hex(b: &[u8]) -> String {
    use std::fmt::Write as _;
    let mut s = String::with_capacity(b.len() * 2);
    for x in b {
        let _ = write!(s, "{x:02x}");
    }
    s
}

/// The clientbound id of a server packet the golden names (official names).
fn cb_id(name: &str) -> i32 {
    use proto::play::clientbound::id;
    match name {
        "block_update" => id::BLOCK_CHANGE,
        "container_set_slot" => id::SET_SLOT,
        "player_position" => id::POSITION,
        "set_held_slot" => id::HELD_ITEM_SLOT,
        "game_event" => id::GAME_STATE_CHANGE,
        "player_abilities" => id::ABILITIES,
        "add_entity" => id::SPAWN_ENTITY,
        other => panic!("clientbound {other}"),
    }
}

/// The official name of a serverbound packet id, for the ids the engine sends here.
fn sb_name(id: i32) -> String {
    use proto::play::serverbound::id as sb;
    let names: &[(i32, &str)] = &[
        (sb::TELEPORT_CONFIRM, "accept_teleportation"),
        (sb::BLOCK_DIG, "player_action"),
        (sb::ATTACK, "attack"),
        (sb::HELD_ITEM_SLOT, "set_carried_item"),
        (sb::USE_ITEM, "use_item"),
        (sb::BLOCK_PLACE, "use_item_on"),
        (sb::FLYING, "move_player_status_only"),
        (sb::POSITION, "move_player_pos"),
        (sb::LOOK, "move_player_rot"),
        (sb::POSITION_LOOK, "move_player_pos_rot"),
        (sb::TICK_END, "client_tick_end"),
        (sb::PLAYER_INPUT, "player_input"),
        (sb::ENTITY_ACTION, "player_command"),
    ];
    if let Some((_, n)) = names.iter().find(|(i, _)| *i == id) {
        return (*n).to_owned();
    }
    if GAME.caps().sends_punch && Some(id) == punch_id() {
        return "punch".to_owned();
    }
    let swing = match GAME {
        GameVersion::V26_1 => Some(ghast_protocol::v26_1::play::serverbound::id::ARM_ANIMATION),
        GameVersion::V26_2 => Some(ghast_protocol::v26_2::play::serverbound::id::ARM_ANIMATION),
        _ => None,
    };
    if swing == Some(id) {
        return "swing".to_owned();
    }
    format!("id_{id:#x}")
}

#[cfg(feature = "v26_3")]
fn punch_id() -> Option<i32> {
    Some(ghast_protocol::v26_3::play::serverbound::id::PUNCH)
}

#[cfg(not(feature = "v26_3"))]
fn punch_id() -> Option<i32> {
    None
}

/// The behaviour of a replay tick: the mouse buttons and this tick's keys, in vanilla's
/// `handleKeybinds` order (hotbar, swap, drop, then the buttons).
struct Keys {
    buttons: Buttons,
    hotbar: Option<u8>,
    swap: bool,
    drop: bool,
}

impl Behavior for Keys {
    fn name(&self) -> &str {
        "held-dig-replay"
    }
    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        if let Some(s) = self.hotbar.take() {
            ctx.select_slot(s);
        }
        if std::mem::take(&mut self.swap) {
            ctx.swap_hands();
        }
        if std::mem::take(&mut self.drop) {
            ctx.drop_held(false);
        }
        ctx.set_buttons(self.buttons);
    }
}

/// The packet filter of a client without entity tracking: the play packets, the world's and the
/// inventory's.
fn filter_of(e: &mut Engine<Box<dyn Sim>>) -> PacketFilter {
    let mut filter = Marker::play_filter(Interests::default());
    for id in e.sim.world_packet_ids() {
        filter.insert(id);
    }
    for id in e.sim.entity_packet_ids() {
        filter.insert(id);
    }
    for &id in Marker::inventory_packet_ids(e.inventory_mut()) {
        filter.insert(id);
    }
    filter
}

/// A server packet through the client's route (as `Client` routes it).
fn feed(e: &mut Engine<Box<dyn Sim>>, filter: &PacketFilter, wire: &mut Wire, raw: &RawPacket) {
    if !filter.contains(raw.id) {
        return;
    }
    e.sim.world_packet(raw).unwrap();
    if let Some(o) = Marker::inventory_packet(e.inventory_mut(), raw).unwrap() {
        e.outbound().push(Outbound::Inventory(o));
    }
    if let Some(p) = Marker::decode_play(raw, wire).unwrap() {
        e.handle(p);
    }
}

/// The result of a replay: cases, ticks and packets compared, the failures (first per case).
#[derive(Default)]
pub(super) struct DigSummary {
    pub cases: usize,
    pub ticks: usize,
    pub packets: usize,
    pub failed: Vec<String>,
    pub skipped: Vec<String>,
}

/// Replays `held_dig.jsonl.gz` (`GHAST_DIG_CASE=<name>`: that case alone, every tick printed).
pub(super) fn held_dig_replay() -> DigSummary {
    use golden::{ext_of, player_of};
    use proto::play::clientbound as cb;
    let path = format!(
        "{}/../../tests/golden/{GOLDEN}/held_dig.jsonl.gz",
        env!("CARGO_MANIFEST_DIR")
    );
    let f = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
    let lines: Vec<Value> = std::io::BufReader::new(flate2::read::GzDecoder::new(f))
        .lines()
        .map(|l| serde_json::from_str(&l.unwrap()).unwrap())
        .collect();
    let f64v = |v: &Value| f64::from_bits(u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap());
    let f32v = |v: &Value| f32::from_bits(u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap());
    let only = std::env::var("GHAST_DIG_CASE").ok();
    let mut sum = DigSummary::default();
    let mut i = 0;
    while i < lines.len() {
        let sc = &lines[i];
        let name = sc["name"].as_str().unwrap().to_owned();
        let mut ticks = Vec::new();
        i += 1;
        while i < lines.len() && lines[i]["type"] == "tick" {
            ticks.push(&lines[i]);
            i += 1;
        }
        if only.as_ref().is_some_and(|o| *o != name) {
            continue;
        }
        // Known gap, 26.1 / 26.2: a thrown item's use in the air swings the arm there
        // (`InteractionResult.SUCCESS`, a client swing); the modern held-item facts have no
        // per-item use result yet (26.3 sends no use swing, so the case runs there).
        if only.is_none() && GAME.caps().sends_swing && name == "swings_use_air" {
            sum.skipped.push(name);
            continue;
        }
        sum.cases += 1;
        let setup = &sc["setup"];
        let mut o = opts(GAME);
        o.inventory = INVENTORY;
        let mut e: Engine<Box<dyn Sim>> = Engine::new(o, Box::new(ModernSim::test_overworld()));
        e.handle(Inbound::JoinGame(JoinGame {
            entity_id: 7,
            game_mode: GameMode::Survival,
            dimension: "0".into(),
            hardcore: false,
            dimension_nbt: None,
            respawn_screen: true,
        }));
        e.sim.test_set_own_id(7);
        // Entity tracking: the attack cases' zombie is picked.
        e.sim.set_entities(Some(
            ghast_entity::Config::default()
                .with_equipment(false)
                .with_effects(false)
                .with_events(false),
        ));
        let filter = filter_of(&mut e);
        let mut wire = Wire::default();
        let (cx, cz) = (
            (f64v(&setup["pos"][0]).floor() as i32) >> 4,
            (f64v(&setup["pos"][2]).floor() as i32) >> 4,
        );
        let body_view = {
            let mut b = bytes::BytesMut::new();
            ghast_protocol::codec::McWrite::put_varint(&mut b, cx);
            ghast_protocol::codec::McWrite::put_varint(&mut b, cz);
            b.freeze()
        };
        e.sim
            .world_packet(&RawPacket::new(cb::id::UPDATE_VIEW_POSITION, body_view))
            .unwrap();
        for r in sc["loaded_chunks"].as_array().unwrap() {
            let r: Vec<i32> = (0..4).map(|k| r[k].as_i64().unwrap() as i32).collect();
            for x in r[0]..=r[2] {
                for z in r[1]..=r[3] {
                    e.sim.world_packet(&chunk(x, z)).unwrap();
                    for bx in x * 16..x * 16 + 16 {
                        for bz in z * 16..z * 16 + 16 {
                            e.sim.predict_air(bx, 63, bz);
                        }
                    }
                }
            }
        }
        for fill in sc["fills"].as_array().unwrap() {
            let v: Vec<i64> = (0..7).map(|k| fill[k].as_i64().unwrap()).collect();
            for x in v[0]..=v[3] {
                for y in v[1]..=v[4] {
                    for z in v[2]..=v[5] {
                        let pos = ((x & 0x3FF_FFFF) << 38) | ((z & 0x3FF_FFFF) << 12) | (y & 0xFFF);
                        let mut b = bytes::BytesMut::from(&pos.to_be_bytes()[..]);
                        ghast_protocol::codec::McWrite::put_varint(&mut b, v[6] as i32);
                        e.sim
                            .world_packet(&RawPacket::new(cb::id::BLOCK_CHANGE, b.freeze()))
                            .unwrap();
                    }
                }
            }
        }
        e.handle(Inbound::Teleport(Teleport {
            x: f64v(&setup["pos"][0]),
            y: f64v(&setup["pos"][1]),
            z: f64v(&setup["pos"][2]),
            yaw: f32v(&setup["yaw"]),
            pitch: f32v(&setup["pitch"]),
            teleport_id: None,
            ..Default::default()
        }));
        let p = player_of(sc, ticks[0]);
        e.sim.test_set_modern(p, ext_of(sc, ticks[0]));
        e.core.pose.pos = Vec3::new(p.pos[0], p.pos[1], p.pos[2]);
        e.core.pose.yaw = p.yaw;
        e.core.pose.pitch = p.pitch;
        e.core.level_load_started = true;
        e.core.client_loaded = true;
        e.core.ready = true;
        e.outbound().clear();
        let t0 = Instant::now();
        for (k, rec) in ticks.iter().enumerate().skip(1) {
            let input = &rec["input"];
            let mut b = Keys {
                buttons: Buttons::default(),
                hotbar: None,
                swap: false,
                drop: false,
            };
            for ev in input["events"].as_array().into_iter().flatten() {
                match ev["type"].as_str().unwrap() {
                    "wire" => {
                        let raw = RawPacket::new(
                            cb_id(ev["name"].as_str().unwrap()),
                            unhex(ev["hex"].as_str().unwrap()),
                        );
                        feed(&mut e, &filter, &mut wire, &raw);
                    }
                    "hotbar" => b.hotbar = Some(ev["slot"].as_u64().unwrap() as u8),
                    "drop" => b.drop = true,
                    "swap" => b.swap = true,
                    other => panic!("{name}: event {other}"),
                }
            }
            let keys = input["keys"].as_str().unwrap();
            let has = |n: &str| keys.split(',').any(|x| x == n);
            b.buttons = Buttons {
                left: has("attack"),
                right: has("use"),
            };
            e.core.forced_look = Some((f32v(&input["yaw"]), f32v(&input["pitch"])));
            e.note_inbound(t0);
            e.tick(&mut b, t0);
            let out = std::mem::take(e.outbound());
            Marker::prepare_play(&out, &mut wire);
            let mut enc = ghast_protocol::FrameEncoder::new();
            for o in &out {
                Marker::write_play(&mut enc, o, &mut wire).unwrap();
            }
            let bytes = enc.take();
            let mut dec = ghast_protocol::frame::FrameDecoder::new();
            dec.push(&bytes);
            let mut got = Vec::new();
            while let Some(p) = dec.next_packet().unwrap() {
                got.push((sb_name(p.id), hex(&p.body)));
            }
            let want: Vec<(String, String)> = rec["wire"]
                .as_array()
                .unwrap()
                .iter()
                .map(|p| {
                    (
                        p[0].as_str().unwrap().to_owned(),
                        p[1].as_str().unwrap().to_owned(),
                    )
                })
                .collect();
            if only.is_some() {
                eprintln!(
                    "t{k} keys {keys} ours {out:?}\n    got  {got:?}\n    want {want:?}\n    mining {:?}",
                    e.core.hands.mining()
                );
            }
            if got != want {
                sum.failed.push(format!(
                    "{name} tick {k}: packets {got:?} want {want:?} (ours {out:?})"
                ));
                break;
            }
            sum.packets += want.len();
            sum.ticks += 1;
        }
    }
    sum
}

/// Every held-dig case of the version through the engine: 0 diffs.
#[test]
fn held_dig_matches_the_oracle() {
    let s = held_dig_replay();
    if std::env::var_os("GHAST_DIG_LIST").is_some() {
        for f in &s.failed {
            eprintln!("FAIL {GOLDEN} {f}");
        }
    }
    let first: Vec<&String> = s.failed.iter().take(8).collect();
    eprintln!(
        "held_dig {GOLDEN}: {} cases, {} ticks, {} packets, {} failed, skipped {:?}",
        s.cases,
        s.ticks,
        s.packets,
        s.failed.len(),
        s.skipped
    );
    assert!(s.failed.is_empty(), "{} failed: {first:#?}", s.failed.len());
    assert!(s.cases >= 250, "{} cases", s.cases);
}