ghast-client 0.5.5

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! 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 `modern.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,
        "cooldown" => id::SET_COOLDOWN,
        "set_health" => id::UPDATE_HEALTH,
        "entity_event" => id::ENTITY_STATUS,
        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,
    /// Queued left presses (`clicks` events: [`TickContext::press`]).
    presses: u8,
}

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);
        for _ in 0..std::mem::take(&mut self.presses) {
            assert!(ctx.press(crate::hands::Button::Left));
        }
    }
}

/// 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 {
    replay("held_dig.jsonl.gz", 7, false)
}

/// The item cooldowns after a tick as the oracle records them (`cooldowns.jsonl.gz`): group,
/// ticks left, duration, sorted by group.
fn cooldowns_of(e: &Engine<Box<dyn Sim>>) -> Vec<(String, i64, i64)> {
    let mut v: Vec<(String, i64, i64)> = e
        .core
        .cooldowns
        .iter()
        .map(|c| match c.key {
            crate::cooldown::CooldownKey::Group(g) => {
                (g, i64::from(c.ticks_left), i64::from(c.duration))
            }
            k => panic!("modern cooldown under {k:?}"),
        })
        .collect();
    v.sort();
    v
}

/// The hands' stacks as the oracle records them: `[item id, count]` or none.
fn hands_of(e: &Engine<Box<dyn Sim>>) -> [Option<(i64, i64)>; 2] {
    let of =
        |s: Option<&ghast_inventory::Stack>| s.map(|s| (i64::from(s.id()), i64::from(s.count())));
    [of(e.core.inv.held()), of(e.core.inv.offhand())]
}

/// Replays a held-dig format golden (`file` under the version's golden directory; our entity
/// id `own_id`). Records with `cooldowns` / `hands` (`cooldowns.jsonl.gz`) are compared too.
/// `aim`: each tick's look arrives as the tick's turn (toward the behaviour's aim) instead of
/// being set before the key handling.
fn replay(file: &str, own_id: i32, aim: bool) -> DigSummary {
    use golden::{ext_of, player_of};
    use proto::play::clientbound as cb;
    let path = format!(
        "{}/../../tests/golden/{GOLDEN}/{file}",
        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;
        }
        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: own_id,
            game_mode: GameMode::Survival,
            dimension: "0".into(),
            hardcore: false,
            dimension_nbt: None,
            respawn_screen: true,
        }));
        e.sim.test_set_own_id(own_id);
        // 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,
                presses: 0,
            };
            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,
                    "clicks" => b.presses = ev["n"].as_u64().unwrap() as u8,
                    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"),
            };
            let look = (f32v(&input["yaw"]), f32v(&input["pitch"]));
            if aim {
                e.core.forced_look = Some(look);
                e.core.forced_aim = true;
                e.core.aimed = true;
            } else {
                e.core.forced_look = Some(look);
            }
            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;
            }
            if let Some(cds) = rec["cooldowns"].as_array() {
                let want: Vec<(String, i64, i64)> = cds
                    .iter()
                    .map(|c| {
                        (
                            c[0].as_str().unwrap().to_owned(),
                            c[1].as_i64().unwrap(),
                            c[2].as_i64().unwrap(),
                        )
                    })
                    .collect();
                let got = cooldowns_of(&e);
                if only.is_some() {
                    eprintln!("    cooldowns {got:?} want {want:?}");
                }
                if got != want {
                    sum.failed
                        .push(format!("{name} tick {k}: cooldowns {got:?} want {want:?}"));
                    break;
                }
                let of = |v: &Value| {
                    v.as_array()
                        .map(|a| (a[0].as_i64().unwrap(), a[1].as_i64().unwrap()))
                };
                let want = [of(&rec["hands"][0]), of(&rec["hands"][1])];
                let got = hands_of(&e);
                if got != want {
                    sum.failed
                        .push(format!("{name} tick {k}: hands {got:?} want {want:?}"));
                    break;
                }
            }
            sum.packets += want.len();
            sum.ticks += 1;
        }
    }
    sum
}

/// The item cooldown cases (`cooldowns.jsonl.gz`, oracle `Cooldowns`): every tick's packets,
/// cooldowns and hands as the real client's.
#[test]
fn cooldowns_match_the_oracle() {
    let s = replay("cooldowns.jsonl.gz", 1, false);
    let first: Vec<&String> = s.failed.iter().take(8).collect();
    eprintln!(
        "cooldowns {GOLDEN}: {} cases, {} ticks, {} packets, {} failed",
        s.cases,
        s.ticks,
        s.packets,
        s.failed.len()
    );
    assert!(s.failed.is_empty(), "{} failed: {first:#?}", s.failed.len());
    assert!(s.cases >= 12, "{} cases", s.cases);
}

/// 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);
}

/// [`held_dig_matches_the_oracle`] with each tick's look as the tick's turn: vanilla's key
/// handling picks with the look the frames turned to before the tick, so the held buttons
/// pick with the turned look (the look the movement packet carries).
#[test]
fn held_buttons_pick_with_the_turned_look() {
    let s = replay("held_dig.jsonl.gz", 7, true);
    let first: Vec<&String> = s.failed.iter().take(8).collect();
    eprintln!(
        "held_dig {GOLDEN} (aimed): {} cases, {} ticks, {} failed",
        s.cases,
        s.ticks,
        s.failed.len()
    );
    assert!(s.failed.is_empty(), "{} failed: {first:#?}", s.failed.len());
    assert!(s.cases >= 250, "{} cases", s.cases);
}