ghast-client 0.5.6

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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! The engine replay of a modern version's entity click golden
//! (`tests/golden/<version>/entity_clicks.jsonl.gz`, oracle `EntityClicks`): per case an entity
//! spawned in front of the player with its state (entity data, equipment, riders, leash,
//! effects) and the player's hands, all as the server's wire bytes; one tick, then a right
//! click on the entity. Every packet of the click the engine sends, encoded by the version's
//! wire layer, must equal the real client's (names and bytes), and both hands must hold what
//! the real client's hands hold after it. 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 {
        "add_entity" => id::SPAWN_ENTITY,
        "set_entity_data" => id::ENTITY_METADATA,
        "set_equipment" => id::ENTITY_EQUIPMENT,
        "set_passengers" => id::SET_PASSENGERS,
        "set_entity_link" => id::ATTACH_ENTITY,
        "update_mob_effect" => id::ENTITY_EFFECT,
        "player_info_update" => id::PLAYER_INFO,
        "container_set_slot" => id::SET_SLOT,
        other => panic!("clientbound {other}"),
    }
}

/// The official name of a serverbound packet of a click (`None`: not one: movement, input,
/// tick end).
fn click_packet(id: i32) -> Option<String> {
    use proto::play::serverbound::id as sb;
    let names: &[(i32, &str)] = &[
        (sb::USE_ENTITY, "interact"),
        (sb::USE_ITEM, "use_item"),
        (sb::BLOCK_PLACE, "use_item_on"),
        (sb::HELD_ITEM_SLOT, "set_carried_item"),
        (sb::BLOCK_DIG, "player_action"),
    ];
    if let Some((_, n)) = names.iter().find(|(i, _)| *i == id) {
        return Some((*n).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,
    };
    (swing == Some(id)).then(|| "swing".to_owned())
}

/// The behaviour of a replay tick: the sneak key, then (the click tick) the right button.
struct Keys {
    sneak: bool,
    right: bool,
}

impl Behavior for Keys {
    fn name(&self) -> &str {
        "entity-click-replay"
    }
    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        ctx.set_controls(Controls {
            sneak: self.sneak,
            ..Controls::default()
        });
        ctx.set_buttons(Buttons {
            left: false,
            right: self.right,
        });
    }
}

/// The packet filter: the play packets, the world's, the entity tracker'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 play login packet of player entity 1 in the overworld (26.3: the game modes as VarInts).
fn login() -> RawPacket {
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let mut b = bytes::BytesMut::new();
    b.put_i32(1);
    b.put_u8(0);
    b.put_varint(1);
    b.put_string("minecraft:overworld").unwrap();
    b.put_varint(20);
    b.put_varint(12);
    b.put_varint(12);
    b.put_u8(0);
    b.put_u8(1);
    b.put_u8(0);
    b.put_varint(0);
    b.put_string("minecraft:overworld").unwrap();
    b.put_i64(0);
    if GAME == GameVersion::V26_1 || GAME == GameVersion::V26_2 {
        b.put_i8(0);
        b.put_u8(0xFF);
    } else {
        b.put_varint(0);
        b.put_varint(-1);
    }
    b.put_u8(0);
    b.put_u8(0);
    b.put_u8(0);
    b.put_varint(0);
    b.put_varint(63);
    b.put_u8(0);
    // 26.2+: online mode.
    if GAME != GameVersion::V26_1 {
        b.put_u8(0);
    }
    RawPacket::new(proto::play::clientbound::id::LOGIN, b.freeze())
}

/// A hand's stack as the golden writes it: `[item, count, damage, named]` or null.
fn stack_of(v: &Value) -> Option<(i32, i32)> {
    let a = v.as_array()?;
    let id = data::Item::from_name(a[0].as_str().unwrap())
        .unwrap_or_else(|| panic!("item {}", a[0]))
        .id();
    Some((i32::from(id), a[1].as_i64().unwrap() as i32))
}

/// Where a case's first difference comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Diff {
    /// The entity's answer or its stack change (this table).
    Entity,
    /// The crosshair pick: another target or hit point.
    Pick,
    /// After an item use the entity did not prevent: the item's use in the air.
    ItemUse,
}

/// The result of a replay: cases and packets compared, the failures by origin.
#[derive(Default)]
pub(super) struct ClickSummary {
    pub cases: usize,
    pub packets: usize,
    pub consumed: usize,
    pub failed: Vec<String>,
    pub pick: Vec<String>,
    pub item_use: Vec<String>,
}

/// One case through a fresh engine; `Err`: the first difference.
/// A case's click through a fresh engine: the click's packets (names, bodies), both hands
/// after it, and the engine's own packets.
type Replayed = (
    Vec<(String, String)>,
    [Option<(i32, i32)>; 2],
    Vec<Outbound>,
);

/// The tracker configuration of a replay: the full one, or the one a client with these
/// interests runs (`client::entity_config`: equipment and effects only of the kept types).
fn entity_config(interests: Option<Interests>) -> ghast_entity::Config {
    match interests {
        None => ghast_entity::Config::default().with_events(false),
        Some(i) => crate::client::entity_config(i, GAME.caps()).expect("entity tracking"),
    }
}

fn replay_with(case: &Value, interests: Option<Interests>) -> Replayed {
    let f32v = |v: &Value| f32::from_bits(u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap());
    let mode = match case["mode"].as_str().unwrap() {
        "creative" => GameMode::Creative,
        "adventure" => GameMode::Adventure,
        "spectator" => GameMode::Spectator,
        _ => GameMode::Survival,
    };
    let mut o = opts(GAME);
    o.inventory = INVENTORY;
    o.name = "oracle".into();
    let mut e: Engine<Box<dyn Sim>> = Engine::new(o, Box::new(ModernSim::test_overworld()));
    e.sim.set_entities(Some(entity_config(interests)));
    e.handle(Inbound::JoinGame(JoinGame {
        entity_id: 1,
        game_mode: mode,
        dimension: "0".into(),
        hardcore: false,
        dimension_nbt: None,
        respawn_screen: true,
    }));
    e.sim.test_set_own_id(1);
    // The tracker learns the player's entity id from the login packet (the leash holder 1).
    e.sim.world_packet(&login()).unwrap();
    let filter = filter_of(&mut e);
    let mut wire = Wire::default();
    {
        use proto::play::clientbound as cb;
        let mut b = bytes::BytesMut::new();
        ghast_protocol::codec::McWrite::put_varint(&mut b, 0);
        ghast_protocol::codec::McWrite::put_varint(&mut b, 0);
        e.sim
            .world_packet(&RawPacket::new(cb::id::UPDATE_VIEW_POSITION, b.freeze()))
            .unwrap();
    }
    for x in -1..=1 {
        for z in -1..=1 {
            e.sim.world_packet(&chunk(x, z)).unwrap();
        }
    }
    e.handle(Inbound::Teleport(Teleport {
        x: 0.5,
        y: 64.0,
        z: 0.5,
        yaw: 0.0,
        pitch: 0.0,
        teleport_id: None,
        ..Default::default()
    }));
    e.core.level_load_started = true;
    e.core.client_loaded = true;
    e.core.ready = true;
    for p in case["packets"].as_array().unwrap() {
        let raw = RawPacket::new(cb_id(p[0].as_str().unwrap()), unhex(p[1].as_str().unwrap()));
        feed(&mut e, &filter, &mut wire, &raw);
    }
    e.outbound().clear();
    let sneak = case["sneak"].as_bool().unwrap();
    let look = (f32v(&case["look"][0]), f32v(&case["look"][1]));
    let t0 = Instant::now();
    // One tick with the keys (the sneak) held, then the click.
    for right in [false, true] {
        let mut b = Keys { sneak, right };
        e.core.forced_look = Some(look);
        e.note_inbound(t0);
        e.tick(&mut b, t0);
        if !right {
            // Through the wire layer (it keeps the look the server has), then dropped.
            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 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() {
        if let Some(n) = click_packet(p.id) {
            got.push((n, hex(&p.body)));
        }
    }
    let inv = &e.core.inv;
    let have = [
        inv.held().map(|s| (s.id(), s.count())),
        inv.offhand().map(|s| (s.id(), s.count())),
    ];
    (got, have, out)
}

fn one(case: &Value, verbose: bool, interests: Option<Interests>) -> Result<usize, (Diff, String)> {
    let (got, have, out) = replay_with(case, interests);
    let want: Vec<(String, String)> = case["sent"]
        .as_array()
        .unwrap()
        .iter()
        .map(|p| {
            (
                p[0].as_str().unwrap().to_owned(),
                p[1].as_str().unwrap().to_owned(),
            )
        })
        .collect();
    if verbose {
        eprintln!("ours {out:?}\n  got  {got:?}\n  want {want:?}");
    }
    if got != want {
        let first = got.iter().zip(&want).take_while(|(a, b)| a == b).count();
        // The crosshair pick (ghast-entity's boxes) took another target or point.
        let pick = want.first().is_some_and(|w| w.0 == "interact")
            && got
                .first()
                .is_none_or(|g| g.0 != "interact" || g.1 != want[0].1);
        // Equal up to an item use, different after it: the item's own use in the air (the
        // air-use prediction), not the entity's answer.
        let item_use = !pick && first > 0 && want[..first].iter().any(|w| w.0 == "use_item");
        let kind = if pick {
            Diff::Pick
        } else if item_use {
            Diff::ItemUse
        } else {
            Diff::Entity
        };
        return Err((
            kind,
            format!("packets {got:?} want {want:?} (ours {out:?})"),
        ));
    }
    let after = &case["after"];
    let want_hands = [stack_of(&after[0]), stack_of(&after[1])];
    if have != want_hands {
        // After an item use: what the use did to its stack (a knowledge book's use).
        let used = want.iter().any(|w| w.0 == "use_item");
        return Err((
            if used { Diff::ItemUse } else { Diff::Entity },
            format!("hands after {have:?} want {want_hands:?}"),
        ));
    }
    Ok(want.len())
}

/// Replays `entity_clicks.jsonl.gz` (`GHAST_CLICK_CASE=<k>`: that case alone, printed).
pub(super) fn entity_clicks_replay(interests: Option<Interests>) -> ClickSummary {
    let path = format!(
        "{}/../../tests/golden/{GOLDEN}/entity_clicks.jsonl.gz",
        env!("CARGO_MANIFEST_DIR")
    );
    let f = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
    let only: Option<u64> = std::env::var("GHAST_CLICK_CASE")
        .ok()
        .and_then(|s| s.parse().ok());
    let mut sum = ClickSummary::default();
    for l in std::io::BufReader::new(flate2::read::GzDecoder::new(f)).lines() {
        let case: Value = serde_json::from_str(&l.unwrap()).unwrap();
        let k = case["k"].as_u64().unwrap();
        if only.is_some_and(|o| o != k) {
            continue;
        }
        sum.cases += 1;
        let sent = case["sent"].as_array().unwrap();
        // Consumed: the off hand's interact never followed the main hand's.
        if sent.len() == 1 {
            sum.consumed += 1;
        }
        match one(&case, only.is_some(), interests) {
            Ok(n) => sum.packets += n,
            Err((kind, d)) => {
                let line = format!(
                    "case {k} ({} {} held {} dims {}): {d}",
                    case["entity"].as_str().unwrap(),
                    case["mode"].as_str().unwrap(),
                    case["held"],
                    case["dims"]
                );
                match kind {
                    Diff::Entity => sum.failed.push(line),
                    Diff::Pick => sum.pick.push(line),
                    Diff::ItemUse => sum.item_use.push(line),
                }
            }
        }
    }
    sum
}

/// Every entity click case of the version through the engine: 0 differences.
#[test]
fn entity_clicks_match_the_oracle() {
    check_clicks(None);
}

/// The same cases with the tracker a default client runs (`Interests::ENTITIES`: metadata, the
/// names-only tab list, equipment and effects only of the types the table reads them for).
#[test]
fn entity_clicks_match_the_oracle_default_client() {
    check_clicks(Some(Interests::ENTITIES));
}

/// The same cases with lean tracking (`Interests::ENTITY_TRACKING`: no metadata store). Only
/// the cases whose answer depends on an entity data entry may differ; they are counted, and the
/// rest must match.
#[test]
fn entity_clicks_lean_tracking() {
    let s = entity_clicks_replay(Some(Interests::ENTITY_TRACKING));
    eprintln!(
        "entity_clicks {GOLDEN} lean: {} cases, {} differ in the entity's answer (entity data \
         unknown), {} pick, {} item use",
        s.cases,
        s.failed.len(),
        s.pick.len(),
        s.item_use.len()
    );
    if std::env::var_os("GHAST_CLICK_LIST").is_some() {
        for f in &s.failed {
            eprintln!("LEAN {GOLDEN} {f}");
        }
    }
    // A case may differ only when an entity data dim (not the hand, sneak, other hand,
    // riders, leash, equipment or effect) is away from 0.
    let first: Vec<&String> = s
        .failed
        .iter()
        .filter(|f| {
            let Some(d) = f.split(" dims ").nth(1).and_then(|d| d.split(')').next()) else {
                return true;
            };
            let Ok(Value::Object(m)) = serde_json::from_str::<Value>(d) else {
                return true;
            };
            !m.iter().any(|(k, v)| {
                !matches!(
                    k.as_str(),
                    "hand" | "sneak" | "dandelion" | "passengers" | "leash"
                ) && !k.starts_with("equip_")
                    && !k.starts_with("effect_")
                    && v.as_u64() != Some(0)
            })
        })
        .take(6)
        .collect();
    assert!(first.is_empty(), "{} unexplained: {first:#?}", first.len());
}

/// A replay line whose case holds a spear (an item with an attack range component) in the main
/// hand.
fn main_hand_spear(line: &str) -> bool {
    line.split("held [[\"")
        .nth(1)
        .and_then(|r| r.split('"').next())
        .is_some_and(|name| name.ends_with("_spear"))
}

fn check_clicks(interests: Option<Interests>) {
    let s = entity_clicks_replay(interests);
    if std::env::var_os("GHAST_CLICK_LIST").is_some() {
        for f in &s.failed {
            eprintln!("FAIL {GOLDEN} {f}");
        }
        for f in &s.pick {
            eprintln!("PICK {GOLDEN} {f}");
        }
        for f in &s.item_use {
            eprintln!("USE {GOLDEN} {f}");
        }
    }
    let first: Vec<&String> = s.failed.iter().take(6).collect();
    eprintln!(
        "entity_clicks {GOLDEN}: {} cases ({} consumed by the main hand), {} packets, {} failed; \
         outside the entity's answer: {} pick, {} item use in the air",
        s.cases,
        s.consumed,
        s.packets,
        s.failed.len(),
        s.pick.len(),
        s.item_use.len()
    );
    assert!(s.failed.is_empty(), "{} failed: {first:#?}", s.failed.len());
    // The crosshair pick: every type's box and the spectator's eye are exact. Left: a main hand
    // with an attack range component (spears) picks with `AttackRange.getClosesetHit`, which the
    // engine does not model.
    let pick: Vec<&String> = s.pick.iter().filter(|l| !main_hand_spear(l)).collect();
    assert!(
        pick.is_empty(),
        "{} pick differences: {:#?}",
        pick.len(),
        &pick[..pick.len().min(6)]
    );
    // The hand's item use after a click the entity passed (`sim::modern::air`).
    assert!(
        s.item_use.is_empty(),
        "{} item use differences: {:#?}",
        s.item_use.len(),
        &s.item_use[..s.item_use.len().min(6)]
    );
    if std::env::var_os("GHAST_CLICK_CASE").is_none() {
        assert!(s.cases >= 1500, "{} cases", s.cases);
    }
}

/// The lab's finding (2026-11-28): boarding a saddled pig with a carrot on a stick in the main
/// hand. The pig consumes the click (`Pig.mobInteract`: SUCCESS, the player starts riding on the
/// server): vanilla sends the main hand's interact only (26.1 / 26.2 also the swing), no item
/// use (which would boost the pig at once and cost the stick durability) and no off-hand
/// interact.
#[test]
fn saddled_pig_with_a_stick_is_boarded_without_an_item_use() {
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let pig = data::entity_by_name("pig").unwrap().id;
    let saddle = data::Item::from_name("saddle").unwrap().id();
    let stick = data::Item::from_name("carrot_on_a_stick").unwrap().id();
    let mut spawn = bytes::BytesMut::new();
    spawn.put_varint(500);
    spawn.put_u128(0x0070_6967);
    spawn.put_varint(i32::from(pig));
    for v in [0.5f64, 64.0, 2.1] {
        spawn.put_f64(v);
    }
    // No velocity (LpVec3 zero), pitch, yaw, head yaw, data.
    spawn.put_slice(&[0, 0, 0, 0, 0]);
    let mut equip = bytes::BytesMut::new();
    equip.put_varint(500);
    equip.put_u8(7); // saddle slot, the last entry
    equip.put_varint(1);
    equip.put_varint(i32::from(saddle));
    equip.put_slice(&[0, 0]);
    let mut slot = bytes::BytesMut::new();
    slot.put_varint(0);
    slot.put_varint(0);
    slot.put_i16(36);
    slot.put_varint(1);
    slot.put_varint(i32::from(stick));
    slot.put_slice(&[0, 0]);
    let case = serde_json::json!({
        "mode": "survival",
        "sneak": false,
        // At the pig's middle (yaw 0 faces +z).
        "look": [[0.0, "00000000"], [35.0, "420c0000"]],
        "packets": [
            ["add_entity", hex(&spawn)],
            ["set_equipment", hex(&equip)],
            ["container_set_slot", hex(&slot)],
        ],
    });
    let want: &[&str] = if GAME.caps().sends_swing {
        &["interact", "swing"]
    } else {
        &["interact"]
    };
    // The full tracker, a default client's and a lean one's (the saddle is kept for the click).
    for interests in [
        None,
        Some(Interests::ENTITIES),
        Some(Interests::ENTITY_TRACKING),
    ] {
        let (got, hands, out) = replay_with(&case, interests);
        let names: Vec<&str> = got.iter().map(|g| g.0.as_str()).collect();
        assert_eq!(names, want, "{interests:?}: {out:?}");
        assert_eq!(hands, [Some((i32::from(stick), 1)), None]);
    }
}