Spicy NoSlow module 2 files, 1006 lines

Spicy NoSlow: Full Source Analysis

Spicy's NoSlow works on two layers. Client-side, the fork's EntityPlayerSP has been modified so the item-use movement damping, the moveForward/moveStrafe *= 0.2 applied while using an item, is gated…

info/spicyclient/modules/movement/NoSlow.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-10-14

Analysis

Overview

Spicy's NoSlow works on two layers. Client-side, the fork's EntityPlayerSP has been modified so the item-use movement damping, the moveForward/moveStrafe *= 0.2 applied while using an item, is gated on the NoSlow module being disabled, so turning the module on removes the local slowdown without touching the item-use state. Server-side, the module runs a release-spam cycle: on every pre-tick while the player is blocking, moving and grounded, with no killaura target, it sends a C07PacketPlayerDigging(RELEASE_USE_ITEM) whose BlockPos coordinates are drawn randomly from the full double range, with EnumFacing.DOWN. Each release clears the server's item-use state, so the server never observes a blocking player. The C08 re-place branch in the same handler is unreachable dead code: the outer guard already requires the pre phase, so the else that would re-arm the use-item placement is never taken.

The client-side half

EntityPlayerSP.onLivingUpdate (line 832) is a modified copy of vanilla's damping: if (isUsingItem() && !isRiding() && !SpicyClient.config.noSlow.isEnabled()) { moveStrafe *= 0.2F; moveForward *= 0.2F; sprintToggleTimer = 0; }. The 0.2 damping is preserved verbatim but conditioned on the module's toggle, so with NoSlow on the client keeps full input speed while still holding the sword up. This half is client-internal: the server only sees its consequence in the C03 stream, which shows full-speed movement while the player appears to block.

The wire cycle

While isBlocking(), isMoving() and isOnGround(0.42) hold, with the killaura target null, every EventUpdate pre sends C07PacketPlayerDigging(RELEASE_USE_ITEM). The position is junk on purpose: each coordinate is RandomUtils.nextDouble(Double.MIN_VALUE, Double.MAX_VALUE), flooring to enormous integers far outside the world. RELEASE_USE_ITEM processing ignores the position anyway, so the payload is harmless noise. The server clears the player's item-use on each release, so its blocking state flaps to false every tick. The else branch that would send C08PacketPlayerBlockPlacement with BlockPos(-1, -1, -1) and face 255 (the vanilla use-item re-arm) is unreachable because the outer condition already requires e.isPre(), making the module release-only as shipped.

source NoSlow.java (module)

NoSlow.java50 lines · JavaOriginal ↗
1
package info.spicyclient.modules.movement;
2
3
import org.apache.commons.lang3.RandomUtils;
4
import org.lwjgl.input.Keyboard;
5
6
import info.spicyclient.SpicyClient;
7
import info.spicyclient.chatCommands.Command;
8
import info.spicyclient.events.Event;
9
import info.spicyclient.events.listeners.EventUpdate;
10
import info.spicyclient.modules.Module;
11
import info.spicyclient.modules.combat.Killaura;
12
import info.spicyclient.util.MovementUtils;
13
import net.minecraft.network.play.client.C07PacketPlayerDigging;
14
import net.minecraft.network.play.client.C07PacketPlayerDigging.Action;
15
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
16
import net.minecraft.util.BlockPos;
17
import net.minecraft.util.EnumFacing;
18
19
public class NoSlow extends Module {
20
21
	public NoSlow() {
22
		super("NoSlow", Keyboard.KEY_NONE, Category.MOVEMENT);
23
	}
24
25
	
26
	public void onEnable() {
27
		
28
	}
29
	
30
	public void onDisable() {
31
		
32
	}
33
	
34
	public void onEvent(Event e) {
35
		
36
		if (e instanceof EventUpdate && e.isPre()) {
37
			
38
	        if (mc.thePlayer.isBlocking() && MovementUtils.isMoving() && MovementUtils.isOnGround(0.42D) && SpicyClient.config.killaura.target == null) {
39
	            if (e.isPre()) {
40
	                mc.getNetHandler().getNetworkManager().sendPacket(new C07PacketPlayerDigging(Action.RELEASE_USE_ITEM, new BlockPos(RandomUtils.nextDouble(4.9E-324D, 1.7976931348623157E308D), RandomUtils.nextDouble(4.9E-324D, 1.7976931348623157E308D), RandomUtils.nextDouble(4.9E-324D, 1.7976931348623157E308D)), EnumFacing.DOWN));
41
	            } else {
42
	                mc.thePlayer.sendQueue.addToSendQueue(new C08PacketPlayerBlockPlacement(new BlockPos(-1, -1, -1), 255, mc.thePlayer.getHeldItem(), 0.0F, 0.0F, 0.0F));
43
	            }
44
	        }
45
			
46
		}
47
		
48
	}
49
	
50
}

What this file does

The module is one pre-update handler gated on isBlocking, isMoving, the 0.42 ground probe and an empty killaura target. The active statement sends the C07 release with the randomly generated BlockPos and EnumFacing.DOWN; the inner else that would send the C08 re-arm is dead code because the outer condition already tests e.isPre(). The Killaura import shows the intended combat integration: NoSlow holds its releases while the aura has no target.

The random-position detail is the giveaway of the technique's age: the release's position is semantically irrelevant to RELEASE_USE_ITEM, so the module randomizes it to look less like a scripted payload, the same habit seen in other Spicy modules.

source EntityPlayerSP.java (damping hook)

EntityPlayerSP.java956 lines · JavaOriginal ↗
1
package net.minecraft.client.entity;
2
3
import info.spicyclient.SpicyClient;
4
import info.spicyclient.events.EventType;
5
import info.spicyclient.events.listeners.EventChatmessage;
6
import info.spicyclient.events.listeners.EventMotion;
7
import info.spicyclient.events.listeners.EventMove;
8
import info.spicyclient.events.listeners.EventUpdate;
9
import net.minecraft.client.Minecraft;
10
import net.minecraft.client.audio.MovingSoundMinecartRiding;
11
import net.minecraft.client.audio.PositionedSoundRecord;
12
import net.minecraft.client.gui.GuiCommandBlock;
13
import net.minecraft.client.gui.GuiEnchantment;
14
import net.minecraft.client.gui.GuiHopper;
15
import net.minecraft.client.gui.GuiMerchant;
16
import net.minecraft.client.gui.GuiRepair;
17
import net.minecraft.client.gui.GuiScreen;
18
import net.minecraft.client.gui.GuiScreenBook;
19
import net.minecraft.client.gui.inventory.GuiBeacon;
20
import net.minecraft.client.gui.inventory.GuiBrewingStand;
21
import net.minecraft.client.gui.inventory.GuiChest;
22
import net.minecraft.client.gui.inventory.GuiCrafting;
23
import net.minecraft.client.gui.inventory.GuiDispenser;
24
import net.minecraft.client.gui.inventory.GuiEditSign;
25
import net.minecraft.client.gui.inventory.GuiFurnace;
26
import net.minecraft.client.gui.inventory.GuiScreenHorseInventory;
27
import net.minecraft.client.network.NetHandlerPlayClient;
28
import net.minecraft.command.server.CommandBlockLogic;
29
import net.minecraft.entity.Entity;
30
import net.minecraft.entity.IMerchant;
31
import net.minecraft.entity.item.EntityItem;
32
import net.minecraft.entity.item.EntityMinecart;
33
import net.minecraft.entity.passive.EntityHorse;
34
import net.minecraft.init.Items;
35
import net.minecraft.inventory.IInventory;
36
import net.minecraft.item.Item;
37
import net.minecraft.item.ItemStack;
38
import net.minecraft.network.play.client.C01PacketChatMessage;
39
import net.minecraft.network.play.client.C03PacketPlayer;
40
import net.minecraft.network.play.client.C07PacketPlayerDigging;
41
import net.minecraft.network.play.client.C0APacketAnimation;
42
import net.minecraft.network.play.client.C0BPacketEntityAction;
43
import net.minecraft.network.play.client.C0CPacketInput;
44
import net.minecraft.network.play.client.C0DPacketCloseWindow;
45
import net.minecraft.network.play.client.C13PacketPlayerAbilities;
46
import net.minecraft.network.play.client.C16PacketClientStatus;
47
import net.minecraft.potion.Potion;
48
import net.minecraft.stats.StatBase;
49
import net.minecraft.stats.StatFileWriter;
50
import net.minecraft.tileentity.TileEntitySign;
51
import net.minecraft.util.BlockPos;
52
import net.minecraft.util.DamageSource;
53
import net.minecraft.util.EnumFacing;
54
import net.minecraft.util.EnumParticleTypes;
55
import net.minecraft.util.IChatComponent;
56
import net.minecraft.util.MovementInput;
57
import net.minecraft.util.ResourceLocation;
58
import net.minecraft.world.IInteractionObject;
59
import net.minecraft.world.World;
60
61
public class EntityPlayerSP extends AbstractClientPlayer
62
{
63
    public final NetHandlerPlayClient sendQueue;
64
    private final StatFileWriter statWriter;
65
66
    /**
67
     * The last X position which was transmitted to the server, used to determine when the X position changes and needs
68
     * to be re-trasmitted
69
     */
70
    private double lastReportedPosX;
71
72
    /**
73
     * The last Y position which was transmitted to the server, used to determine when the Y position changes and needs
74
     * to be re-transmitted
75
     */
76
    public double lastReportedPosY;
77
78
    /**
79
     * The last Z position which was transmitted to the server, used to determine when the Z position changes and needs
80
     * to be re-transmitted
81
     */
82
    private double lastReportedPosZ;
83
84
    /**
85
     * The last yaw value which was transmitted to the server, used to determine when the yaw changes and needs to be
86
     * re-transmitted
87
     */
88
    private float lastReportedYaw;
89
90
    /**
91
     * The last pitch value which was transmitted to the server, used to determine when the pitch changes and needs to
92
     * be re-transmitted
93
     */
94
    public float lastReportedPitch;
95
96
    /** the last sneaking state sent to the server */
97
    private boolean serverSneakState;
98
99
    /** the last sprinting state sent to the server */
100
    private boolean serverSprintState;
101
102
    /**
103
     * Reset to 0 every time position is sent to the server, used to send periodic updates every 20 ticks even when the
104
     * player is not moving.
105
     */
106
    private int positionUpdateTicks;
107
    private boolean hasValidHealth;
108
    private String clientBrand;
109
    public MovementInput movementInput;
110
    protected Minecraft mc;
111
112
    /**
113
     * Used to tell if the player pressed forward twice. If this is at 0 and it's pressed (And they are allowed to
114
     * sprint, aka enough food on the ground etc) it sets this to 7. If it's pressed and it's greater than 0 enable
115
     * sprinting.
116
     */
117
    protected int sprintToggleTimer;
118
119
    /** Ticks left before sprinting is disabled. */
120
    public int sprintingTicksLeft;
121
    public float renderArmYaw;
122
    public float renderArmPitch;
123
    public float prevRenderArmYaw;
124
    public float prevRenderArmPitch;
125
    private int horseJumpPowerCounter;
126
    private float horseJumpPower;
127
128
    /** The amount of time an entity has been in a Portal */
129
    public float timeInPortal;
130
131
    /** The amount of time an entity has been in a Portal the previous tick */
132
    public float prevTimeInPortal;
133
134
    public EntityPlayerSP(Minecraft mcIn, World worldIn, NetHandlerPlayClient netHandler, StatFileWriter statFile)
135
    {
136
        super(worldIn, netHandler.getGameProfile());
137
        this.sendQueue = netHandler;
138
        this.statWriter = statFile;
139
        this.mc = mcIn;
140
        this.dimension = 0;
141
    }
142
143
    /**
144
     * Called when the entity is attacked.
145
     */
146
    public boolean attackEntityFrom(DamageSource source, float amount)
147
    {
148
        return false;
149
    }
150
151
    /**
152
     * Heal living entity (param: amount of half-hearts)
153
     */
154
    public void heal(float healAmount)
155
    {
156
    }
157
158
    /**
159
     * Called when a player mounts an entity. e.g. mounts a pig, mounts a boat.
160
     */
161
    public void mountEntity(Entity entityIn)
162
    {
163
        super.mountEntity(entityIn);
164
165
        if (entityIn instanceof EntityMinecart)
166
        {
167
            this.mc.getSoundHandler().playSound(new MovingSoundMinecartRiding(this, (EntityMinecart)entityIn));
168
        }
169
    }
170
    
171
    @Override
172
	public void moveEntity(double x, double y, double z) {
173
    	EventMove event = new EventMove(z, y, z);
174
    	event.setType(EventType.PRE);
175
    	event.setX(x);
176
    	event.setY(y);
177
    	event.setZ(z);
178
    	SpicyClient.onEvent(event);
179
		super.moveEntity(event.x, event.y, event.z);
180
	}
181
    
182
    /**
183
     * Called to update the entity's position/logic.
184
     */
185
    public void onUpdate()
186
    {
187
        if (this.worldObj.isBlockLoaded(new BlockPos(this.posX, 0.0D, this.posZ)))
188
        {
189
            super.onUpdate();
190
191
            if (this.isRiding())
192
            {
193
                this.sendQueue.addToSendQueue(new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, this.rotationPitch, this.onGround));
194
                this.sendQueue.addToSendQueue(new C0CPacketInput(this.moveStrafing, this.moveForward, this.movementInput.jump, this.movementInput.sneak));
195
            }
196
            else
197
            {
198
                this.onUpdateWalkingPlayer();
199
            }
200
        }
201
    }
202
203
    /**
204
     * called every tick when the player is on foot. Performs all the things that normally happen during movement.
205
     */
206
    public void onUpdateWalkingPlayer()
207
    {
208
    	
209
    	EventUpdate e = new EventUpdate();
210
    	e.setType(EventType.PRE);
211
    	SpicyClient.onEvent(e);
212
    	
213
    	EventMotion event = new EventMotion(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.motionX, this.motionY, this.motionZ, this.rotationYaw, this.rotationPitch, this.onGround);
214
    	event.setType(EventType.PRE);
215
    	SpicyClient.onEvent(event);
216
    	
217
    	this.motionX = event.motionX;
218
    	this.motionY = event.motionY;
219
    	this.motionZ = event.motionZ;
220
    	
221
        boolean flag = this.isSprinting();
222
223
        if (flag != this.serverSprintState)
224
        {
225
            if (flag)
226
            {
227
                this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.START_SPRINTING));
228
            }
229
            else
230
            {
231
                this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.STOP_SPRINTING));
232
            }
233
234
            this.serverSprintState = flag;
235
        }
236
237
        boolean flag1 = this.isSneaking();
238
239
        if (flag1 != this.serverSneakState)
240
        {
241
            if (flag1)
242
            {
243
                this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.START_SNEAKING));
244
            }
245
            else
246
            {
247
                this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.STOP_SNEAKING));
248
            }
249
250
            this.serverSneakState = flag1;
251
        }
252
253
        if (this.isCurrentViewEntity())
254
        {
255
            double d0 = event.getX() - this.lastReportedPosX;
256
            double d1 = event.getY() - this.lastReportedPosY;
257
            double d2 = event.getZ() - this.lastReportedPosZ;
258
            double d3 = (double)(event.getYaw() - this.lastReportedYaw);
259
            double d4 = (double)(event.getPitch() - this.lastReportedPitch);
260
            boolean flag2 = d0 * d0 + d1 * d1 + d2 * d2 > 9.0E-4D || this.positionUpdateTicks >= 20;
261
            boolean flag3 = d3 != 0.0D || d4 != 0.0D;
262
263
            if (this.ridingEntity == null)
264
            {
265
                if (flag2 && flag3)
266
                {
267
                    this.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(event.getX(), event.getY(), event.getZ(), event.getYaw(), event.getPitch(), event.isOnGround()));
268
                }
269
                else if (flag2)
270
                {
271
                    this.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(event.getX(), event.getY(), event.getZ(), event.isOnGround()));
272
                }
273
                else if (flag3)
274
                {
275
                    this.sendQueue.addToSendQueue(new C03PacketPlayer.C05PacketPlayerLook(event.getYaw(), event.getPitch(), event.isOnGround()));
276
                }
277
                else
278
                {
279
                    this.sendQueue.addToSendQueue(new C03PacketPlayer(event.isOnGround()));
280
                }
281
            }
282
            else
283
            {
284
                this.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(event.motionX, -999.0D, event.motionZ, event.getYaw(), event.getPitch(), event.isOnGround()));
285
                flag2 = false;
286
            }
287
288
            ++this.positionUpdateTicks;
289
290
            if (flag2)
291
            {
292
                this.lastReportedPosX = event.getX();
293
                this.lastReportedPosY = event.getY();
294
                this.lastReportedPosZ = event.getZ();
295
                this.positionUpdateTicks = 0;
296
            }
297
298
            if (flag3)
299
            {
300
                this.lastReportedYaw = event.getYaw();;
301
                this.lastReportedPitch = event.getPitch();;
302
            }
303
        }
304
        
305
        event.setType(EventType.POST);
306
    	SpicyClient.onEvent(event);
307
        
308
    }
309
310
    /**
311
     * Called when player presses the drop item key
312
     */
313
    public EntityItem dropOneItem(boolean dropAll)
314
    {
315
        C07PacketPlayerDigging.Action c07packetplayerdigging$action = dropAll ? C07PacketPlayerDigging.Action.DROP_ALL_ITEMS : C07PacketPlayerDigging.Action.DROP_ITEM;
316
        this.sendQueue.addToSendQueue(new C07PacketPlayerDigging(c07packetplayerdigging$action, BlockPos.ORIGIN, EnumFacing.DOWN));
317
        return null;
318
    }
319
320
    /**
321
     * Joins the passed in entity item with the world. Args: entityItem
322
     */
323
    protected void joinEntityItemWithWorld(EntityItem itemIn)
324
    {
325
    }
326
327
    /**
328
     * Sends a chat message from the player. Args: chatMessage
329
     */
330
    public void sendChatMessage(String message)
331
    {
332
    	EventChatmessage chat = new EventChatmessage();
333
    	chat.setType(EventType.PRE);
334
    	chat.setMessage(message);
335
    	SpicyClient.onEvent(chat);
336
    	message = chat.getMessage();
337
    	
338
    	if (chat.isCanceled()) {
339
    		
340
    	}else {
341
    		this.sendQueue.addToSendQueue(new C01PacketChatMessage(message));
342
    	}
343
    }
344
345
    /**
346
     * Swings the item the player is holding.
347
     */
348
    public void swingItem()
349
    {
350
        super.swingItem();
351
        this.sendQueue.addToSendQueue(new C0APacketAnimation());
352
    }
353
354
    public void respawnPlayer()
355
    {
356
        this.sendQueue.addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN));
357
    }
358
359
    /**
360
     * Deals damage to the entity. If its a EntityPlayer then will take damage from the armor first and then health
361
     * second with the reduced value. Args: damageAmount
362
     */
363
    protected void damageEntity(DamageSource damageSrc, float damageAmount)
364
    {
365
        if (!this.isEntityInvulnerable(damageSrc))
366
        {
367
            this.setHealth(this.getHealth() - damageAmount);
368
        }
369
    }
370
371
    /**
372
     * set current crafting inventory back to the 2x2 square
373
     */
374
    public void closeScreen()
375
    {
376
        this.sendQueue.addToSendQueue(new C0DPacketCloseWindow(this.openContainer.windowId));
377
        this.closeScreenAndDropStack();
378
    }
379
380
    public void closeScreenAndDropStack()
381
    {
382
        this.inventory.setItemStack((ItemStack)null);
383
        super.closeScreen();
384
        this.mc.displayGuiScreen((GuiScreen)null);
385
    }
386
387
    /**
388
     * Updates health locally.
389
     */
390
    public void setPlayerSPHealth(float health)
391
    {
392
        if (this.hasValidHealth)
393
        {
394
            float f = this.getHealth() - health;
395
396
            if (f <= 0.0F)
397
            {
398
                this.setHealth(health);
399
400
                if (f < 0.0F)
401
                {
402
                    this.hurtResistantTime = this.maxHurtResistantTime / 2;
403
                }
404
            }
405
            else
406
            {
407
                this.lastDamage = f;
408
                this.setHealth(this.getHealth());
409
                this.hurtResistantTime = this.maxHurtResistantTime;
410
                this.damageEntity(DamageSource.generic, f);
411
                this.hurtTime = this.maxHurtTime = 10;
412
            }
413
        }
414
        else
415
        {
416
            this.setHealth(health);
417
            this.hasValidHealth = true;
418
        }
419
    }
420
421
    /**
422
     * Adds a value to a statistic field.
423
     */
424
    public void addStat(StatBase stat, int amount)
425
    {
426
        if (stat != null)
427
        {
428
            if (stat.isIndependent)
429
            {
430
                super.addStat(stat, amount);
431
            }
432
        }
433
    }
434
435
    /**
436
     * Sends the player's abilities to the server (if there is one).
437
     */
438
    public void sendPlayerAbilities()
439
    {
440
        this.sendQueue.addToSendQueue(new C13PacketPlayerAbilities(this.capabilities));
441
    }
442
443
    /**
444
     * returns true if this is an EntityPlayerSP, or the logged in player.
445
     */
446
    public boolean isUser()
447
    {
448
        return true;
449
    }
450
451
    protected void sendHorseJump()
452
    {
453
        this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.RIDING_JUMP, (int)(this.getHorseJumpPower() * 100.0F)));
454
    }
455
456
    public void sendHorseInventory()
457
    {
458
        this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.OPEN_INVENTORY));
459
    }
460
461
    public void setClientBrand(String brand)
462
    {
463
        this.clientBrand = brand;
464
    }
465
466
    public String getClientBrand()
467
    {
468
        return this.clientBrand;
469
    }
470
471
    public StatFileWriter getStatFileWriter()
472
    {
473
        return this.statWriter;
474
    }
475
476
    public void addChatComponentMessage(IChatComponent chatComponent)
477
    {
478
        this.mc.ingameGUI.getChatGUI().printChatMessage(chatComponent);
479
    }
480
481
    protected boolean pushOutOfBlocks(double x, double y, double z)
482
    {
483
        if (this.noClip)
484
        {
485
            return false;
486
        }
487
        else
488
        {
489
            BlockPos blockpos = new BlockPos(x, y, z);
490
            double d0 = x - (double)blockpos.getX();
491
            double d1 = z - (double)blockpos.getZ();
492
493
            if (!this.isOpenBlockSpace(blockpos))
494
            {
495
                int i = -1;
496
                double d2 = 9999.0D;
497
498
                if (this.isOpenBlockSpace(blockpos.west()) && d0 < d2)
499
                {
500
                    d2 = d0;
501
                    i = 0;
502
                }
503
504
                if (this.isOpenBlockSpace(blockpos.east()) && 1.0D - d0 < d2)
505
                {
506
                    d2 = 1.0D - d0;
507
                    i = 1;
508
                }
509
510
                if (this.isOpenBlockSpace(blockpos.north()) && d1 < d2)
511
                {
512
                    d2 = d1;
513
                    i = 4;
514
                }
515
516
                if (this.isOpenBlockSpace(blockpos.south()) && 1.0D - d1 < d2)
517
                {
518
                    d2 = 1.0D - d1;
519
                    i = 5;
520
                }
521
522
                float f = 0.1F;
523
524
                if (i == 0)
525
                {
526
                    this.motionX = (double)(-f);
527
                }
528
529
                if (i == 1)
530
                {
531
                    this.motionX = (double)f;
532
                }
533
534
                if (i == 4)
535
                {
536
                    this.motionZ = (double)(-f);
537
                }
538
539
                if (i == 5)
540
                {
541
                    this.motionZ = (double)f;
542
                }
543
            }
544
545
            return false;
546
        }
547
    }
548
549
    /**
550
     * Returns true if the block at the given BlockPos and the block above it are NOT full cubes.
551
     */
552
    private boolean isOpenBlockSpace(BlockPos pos)
553
    {
554
        return !this.worldObj.getBlockState(pos).getBlock().isNormalCube() && !this.worldObj.getBlockState(pos.up()).getBlock().isNormalCube();
555
    }
556
557
    /**
558
     * Set sprinting switch for Entity.
559
     */
560
    public void setSprinting(boolean sprinting)
561
    {
562
        super.setSprinting(sprinting);
563
        this.sprintingTicksLeft = sprinting ? 600 : 0;
564
    }
565
566
    /**
567
     * Sets the current XP, total XP, and level number.
568
     */
569
    public void setXPStats(float currentXP, int maxXP, int level)
570
    {
571
        this.experience = currentXP;
572
        this.experienceTotal = maxXP;
573
        this.experienceLevel = level;
574
    }
575
576
    /**
577
     * Send a chat message to the CommandSender
578
     */
579
    public void addChatMessage(IChatComponent component)
580
    {
581
        this.mc.ingameGUI.getChatGUI().printChatMessage(component);
582
    }
583
584
    /**
585
     * Returns {@code true} if the CommandSender is allowed to execute the command, {@code false} if not
586
     */
587
    public boolean canCommandSenderUseCommand(int permLevel, String commandName)
588
    {
589
        return permLevel <= 0;
590
    }
591
592
    /**
593
     * Get the position in the world. <b>{@code null} is not allowed!</b> If you are not an entity in the world, return
594
     * the coordinates 0, 0, 0
595
     */
596
    public BlockPos getPosition()
597
    {
598
        return new BlockPos(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D);
599
    }
600
601
    public void playSound(String name, float volume, float pitch)
602
    {
603
        this.worldObj.playSound(this.posX, this.posY, this.posZ, name, volume, pitch, false);
604
    }
605
606
    /**
607
     * Returns whether the entity is in a server world
608
     */
609
    public boolean isServerWorld()
610
    {
611
        return true;
612
    }
613
614
    public boolean isRidingHorse()
615
    {
616
        return this.ridingEntity != null && this.ridingEntity instanceof EntityHorse && ((EntityHorse)this.ridingEntity).isHorseSaddled();
617
    }
618
619
    public float getHorseJumpPower()
620
    {
621
        return this.horseJumpPower;
622
    }
623
624
    public void openEditSign(TileEntitySign signTile)
625
    {
626
        this.mc.displayGuiScreen(new GuiEditSign(signTile));
627
    }
628
629
    public void openEditCommandBlock(CommandBlockLogic cmdBlockLogic)
630
    {
631
        this.mc.displayGuiScreen(new GuiCommandBlock(cmdBlockLogic));
632
    }
633
634
    /**
635
     * Displays the GUI for interacting with a book.
636
     */
637
    public void displayGUIBook(ItemStack bookStack)
638
    {
639
        Item item = bookStack.getItem();
640
641
        if (item == Items.writable_book)
642
        {
643
            this.mc.displayGuiScreen(new GuiScreenBook(this, bookStack, true));
644
        }
645
    }
646
647
    /**
648
     * Displays the GUI for interacting with a chest inventory. Args: chestInventory
649
     */
650
    public void displayGUIChest(IInventory chestInventory)
651
    {
652
        String s = chestInventory instanceof IInteractionObject ? ((IInteractionObject)chestInventory).getGuiID() : "minecraft:container";
653
654
        if ("minecraft:chest".equals(s))
655
        {
656
            this.mc.displayGuiScreen(new GuiChest(this.inventory, chestInventory));
657
        }
658
        else if ("minecraft:hopper".equals(s))
659
        {
660
            this.mc.displayGuiScreen(new GuiHopper(this.inventory, chestInventory));
661
        }
662
        else if ("minecraft:furnace".equals(s))
663
        {
664
            this.mc.displayGuiScreen(new GuiFurnace(this.inventory, chestInventory));
665
        }
666
        else if ("minecraft:brewing_stand".equals(s))
667
        {
668
            this.mc.displayGuiScreen(new GuiBrewingStand(this.inventory, chestInventory));
669
        }
670
        else if ("minecraft:beacon".equals(s))
671
        {
672
            this.mc.displayGuiScreen(new GuiBeacon(this.inventory, chestInventory));
673
        }
674
        else if (!"minecraft:dispenser".equals(s) && !"minecraft:dropper".equals(s))
675
        {
676
            this.mc.displayGuiScreen(new GuiChest(this.inventory, chestInventory));
677
        }
678
        else
679
        {
680
            this.mc.displayGuiScreen(new GuiDispenser(this.inventory, chestInventory));
681
        }
682
    }
683
684
    public void displayGUIHorse(EntityHorse horse, IInventory horseInventory)
685
    {
686
        this.mc.displayGuiScreen(new GuiScreenHorseInventory(this.inventory, horseInventory, horse));
687
    }
688
689
    public void displayGui(IInteractionObject guiOwner)
690
    {
691
        String s = guiOwner.getGuiID();
692
693
        if ("minecraft:crafting_table".equals(s))
694
        {
695
            this.mc.displayGuiScreen(new GuiCrafting(this.inventory, this.worldObj));
696
        }
697
        else if ("minecraft:enchanting_table".equals(s))
698
        {
699
            this.mc.displayGuiScreen(new GuiEnchantment(this.inventory, this.worldObj, guiOwner));
700
        }
701
        else if ("minecraft:anvil".equals(s))
702
        {
703
            this.mc.displayGuiScreen(new GuiRepair(this.inventory, this.worldObj));
704
        }
705
    }
706
707
    public void displayVillagerTradeGui(IMerchant villager)
708
    {
709
        this.mc.displayGuiScreen(new GuiMerchant(this.inventory, villager, this.worldObj));
710
    }
711
712
    /**
713
     * Called when the player performs a critical hit on the Entity. Args: entity that was hit critically
714
     */
715
    public void onCriticalHit(Entity entityHit)
716
    {
717
        this.mc.effectRenderer.emitParticleAtEntity(entityHit, EnumParticleTypes.CRIT);
718
    }
719
720
    public void onEnchantmentCritical(Entity entityHit)
721
    {
722
        this.mc.effectRenderer.emitParticleAtEntity(entityHit, EnumParticleTypes.CRIT_MAGIC);
723
    }
724
725
    /**
726
     * Returns if this entity is sneaking.
727
     */
728
    public boolean isSneaking()
729
    {
730
        boolean flag = this.movementInput != null ? this.movementInput.sneak : false;
731
        return flag && !this.sleeping;
732
    }
733
734
    public void updateEntityActionState()
735
    {
736
        super.updateEntityActionState();
737
738
        if (this.isCurrentViewEntity())
739
        {
740
            this.moveStrafing = this.movementInput.moveStrafe;
741
            this.moveForward = this.movementInput.moveForward;
742
            this.isJumping = this.movementInput.jump;
743
            this.prevRenderArmYaw = this.renderArmYaw;
744
            this.prevRenderArmPitch = this.renderArmPitch;
745
            this.renderArmPitch = (float)((double)this.renderArmPitch + (double)(this.rotationPitch - this.renderArmPitch) * 0.5D);
746
            this.renderArmYaw = (float)((double)this.renderArmYaw + (double)(this.rotationYaw - this.renderArmYaw) * 0.5D);
747
        }
748
    }
749
750
    protected boolean isCurrentViewEntity()
751
    {
752
        return this.mc.getRenderViewEntity() == this;
753
    }
754
755
    /**
756
     * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
757
     * use this to react to sunlight and start to burn.
758
     */
759
    public void onLivingUpdate()
760
    {
761
        if (this.sprintingTicksLeft > 0)
762
        {
763
            --this.sprintingTicksLeft;
764
765
            if (this.sprintingTicksLeft == 0)
766
            {
767
                this.setSprinting(false);
768
            }
769
        }
770
771
        if (this.sprintToggleTimer > 0)
772
        {
773
            --this.sprintToggleTimer;
774
        }
775
776
        this.prevTimeInPortal = this.timeInPortal;
777
778
        if (this.inPortal)
779
        {
780
            if (this.mc.currentScreen != null && !this.mc.currentScreen.doesGuiPauseGame())
781
            {
782
                this.mc.displayGuiScreen((GuiScreen)null);
783
            }
784
785
            if (this.timeInPortal == 0.0F)
786
            {
787
                this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("portal.trigger"), this.rand.nextFloat() * 0.4F + 0.8F));
788
            }
789
790
            this.timeInPortal += 0.0125F;
791
792
            if (this.timeInPortal >= 1.0F)
793
            {
794
                this.timeInPortal = 1.0F;
795
            }
796
797
            this.inPortal = false;
798
        }
799
        else if (this.isPotionActive(Potion.confusion) && this.getActivePotionEffect(Potion.confusion).getDuration() > 60)
800
        {
801
            this.timeInPortal += 0.006666667F;
802
803
            if (this.timeInPortal > 1.0F)
804
            {
805
                this.timeInPortal = 1.0F;
806
            }
807
        }
808
        else
809
        {
810
            if (this.timeInPortal > 0.0F)
811
            {
812
                this.timeInPortal -= 0.05F;
813
            }
814
815
            if (this.timeInPortal < 0.0F)
816
            {
817
                this.timeInPortal = 0.0F;
818
            }
819
        }
820
821
        if (this.timeUntilPortal > 0)
822
        {
823
            --this.timeUntilPortal;
824
        }
825
826
        boolean flag = this.movementInput.jump;
827
        boolean flag1 = this.movementInput.sneak;
828
        float f = 0.8F;
829
        boolean flag2 = this.movementInput.moveForward >= f;
830
        this.movementInput.updatePlayerMoveState();
831
832
        if (this.isUsingItem() && !this.isRiding() && !SpicyClient.config.noSlow.isEnabled())
833
        {
834
        	
835
    		this.movementInput.moveStrafe *= 0.2F;
836
            this.movementInput.moveForward *= 0.2F;
837
            this.sprintToggleTimer = 0;
838
        	
839
        }
840
841
        this.pushOutOfBlocks(this.posX - (double)this.width * 0.35D, this.getEntityBoundingBox().minY + 0.5D, this.posZ + (double)this.width * 0.35D);
842
        this.pushOutOfBlocks(this.posX - (double)this.width * 0.35D, this.getEntityBoundingBox().minY + 0.5D, this.posZ - (double)this.width * 0.35D);
843
        this.pushOutOfBlocks(this.posX + (double)this.width * 0.35D, this.getEntityBoundingBox().minY + 0.5D, this.posZ - (double)this.width * 0.35D);
844
        this.pushOutOfBlocks(this.posX + (double)this.width * 0.35D, this.getEntityBoundingBox().minY + 0.5D, this.posZ + (double)this.width * 0.35D);
845
        boolean flag3 = (float)this.getFoodStats().getFoodLevel() > 6.0F || this.capabilities.allowFlying;
846
847
        if (this.onGround && !flag1 && !flag2 && this.movementInput.moveForward >= f && !this.isSprinting() && flag3 && !this.isUsingItem() && !this.isPotionActive(Potion.blindness))
848
        {
849
            if (this.sprintToggleTimer <= 0 && !this.mc.gameSettings.keyBindSprint.isKeyDown())
850
            {
851
                this.sprintToggleTimer = 7;
852
            }
853
            else
854
            {
855
                this.setSprinting(true);
856
            }
857
        }
858
859
        if (!this.isSprinting() && this.movementInput.moveForward >= f && flag3 && !this.isUsingItem() && !this.isPotionActive(Potion.blindness) && this.mc.gameSettings.keyBindSprint.isKeyDown())
860
        {
861
            this.setSprinting(true);
862
        }
863
864
        if (this.isSprinting() && (this.movementInput.moveForward < f || this.isCollidedHorizontally || !flag3))
865
        {
866
            this.setSprinting(false);
867
        }
868
869
        if (this.capabilities.allowFlying)
870
        {
871
            if (this.mc.playerController.isSpectatorMode())
872
            {
873
                if (!this.capabilities.isFlying)
874
                {
875
                    this.capabilities.isFlying = true;
876
                    this.sendPlayerAbilities();
877
                }
878
            }
879
            else if (!flag && this.movementInput.jump)
880
            {
881
                if (this.flyToggleTimer == 0)
882
                {
883
                    this.flyToggleTimer = 7;
884
                }
885
                else
886
                {
887
                    this.capabilities.isFlying = !this.capabilities.isFlying;
888
                    this.sendPlayerAbilities();
889
                    this.flyToggleTimer = 0;
890
                }
891
            }
892
        }
893
894
        if (this.capabilities.isFlying && this.isCurrentViewEntity())
895
        {
896
            if (this.movementInput.sneak)
897
            {
898
                this.motionY -= (double)(this.capabilities.getFlySpeed() * 3.0F);
899
            }
900
901
            if (this.movementInput.jump)
902
            {
903
                this.motionY += (double)(this.capabilities.getFlySpeed() * 3.0F);
904
            }
905
        }
906
907
        if (this.isRidingHorse())
908
        {
909
            if (this.horseJumpPowerCounter < 0)
910
            {
911
                ++this.horseJumpPowerCounter;
912
913
                if (this.horseJumpPowerCounter == 0)
914
                {
915
                    this.horseJumpPower = 0.0F;
916
                }
917
            }
918
919
            if (flag && !this.movementInput.jump)
920
            {
921
                this.horseJumpPowerCounter = -10;
922
                this.sendHorseJump();
923
            }
924
            else if (!flag && this.movementInput.jump)
925
            {
926
                this.horseJumpPowerCounter = 0;
927
                this.horseJumpPower = 0.0F;
928
            }
929
            else if (flag)
930
            {
931
                ++this.horseJumpPowerCounter;
932
933
                if (this.horseJumpPowerCounter < 10)
934
                {
935
                    this.horseJumpPower = (float)this.horseJumpPowerCounter * 0.1F;
936
                }
937
                else
938
                {
939
                    this.horseJumpPower = 0.8F + 2.0F / (float)(this.horseJumpPowerCounter - 9) * 0.1F;
940
                }
941
            }
942
        }
943
        else
944
        {
945
            this.horseJumpPower = 0.0F;
946
        }
947
948
        super.onLivingUpdate();
949
950
        if (this.onGround && this.capabilities.isFlying && !this.mc.playerController.isSpectatorMode())
951
        {
952
            this.capabilities.isFlying = false;
953
            this.sendPlayerAbilities();
954
        }
955
    }
956
}

What this file does

Line 832 is the fork's modification of vanilla's item-use damping: the move input is multiplied by 0.2 only while the NoSlow module is disabled, which is the entire client-side effect of the module. The same method also carries the vanilla sprint gates (the foodLevel > 6 flag3 check, the double-tap timer, the key-hold path) that the sibling Sprint module overrides.

Reading the file also shows the emission path the module's C07 rides: onUpdateWalkingPlayer dispatches EventUpdate PRE at the top of every movement tick, so the release lands before the tick's C03, and the C03 itself is sent unconditionally. That ordering is what makes the release-then-move cycle deterministic: the server always processes the release before the move it is meant to legitimize.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat UseItemAdapter (release-interval ledger)

UseItemAdapter.java438 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.net.protocollib;
16
17
import java.util.Arrays;
18
import java.util.LinkedList;
19
import java.util.List;
20
21
import org.bukkit.GameMode;
22
import org.bukkit.Material;
23
import org.bukkit.entity.HumanEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.event.Event;
26
import org.bukkit.event.EventHandler;
27
import org.bukkit.event.EventPriority;
28
import org.bukkit.event.block.Action;
29
import org.bukkit.event.entity.PlayerDeathEvent;
30
import org.bukkit.event.inventory.InventoryOpenEvent;
31
import org.bukkit.event.player.PlayerInteractEvent;
32
import org.bukkit.event.player.PlayerItemConsumeEvent;
33
import org.bukkit.event.player.PlayerItemHeldEvent;
34
import org.bukkit.event.player.PlayerRespawnEvent;
35
import org.bukkit.event.player.PlayerRiptideEvent;
36
import org.bukkit.inventory.EquipmentSlot;
37
import org.bukkit.inventory.ItemStack;
38
import org.bukkit.inventory.meta.CrossbowMeta;
39
import org.bukkit.plugin.Plugin;
40
41
import com.comphenix.protocol.PacketType;
42
import com.comphenix.protocol.events.ListenerPriority;
43
import com.comphenix.protocol.events.PacketContainer;
44
import com.comphenix.protocol.events.PacketEvent;
45
import com.comphenix.protocol.reflect.StructureModifier;
46
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerDigType;
47
48
import fr.neatmonster.nocheatplus.NCPAPIProvider;
49
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
50
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
51
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
52
import fr.neatmonster.nocheatplus.compat.Bridge1_13;
53
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
54
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeEnchant;
55
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeMaterial;
56
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
57
import fr.neatmonster.nocheatplus.compat.versions.ClientVersion;
58
import fr.neatmonster.nocheatplus.compat.versions.ServerVersion;
59
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
60
import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder;
61
import fr.neatmonster.nocheatplus.event.mini.MiniListener;
62
import fr.neatmonster.nocheatplus.logging.StaticLog;
63
import fr.neatmonster.nocheatplus.players.DataManager;
64
import fr.neatmonster.nocheatplus.players.IPlayerData;
65
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
66
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
67
import fr.neatmonster.nocheatplus.utilities.map.MaterialUtil;
68
69
/**
70
 * <p>Adapter for listening to packets and Bukkit events relevant to item use.</p>
71
 *
72
 * On versions 1.17 and above, the adapter will only register events related to a specific item-use exploit, 
73
 * as Bukkit provides the {@link HumanEntity#getItemInUse()} method.<br>
74
 *
75
 * <p>On versions 1.12 and above, up to 1.17, all listeners will be registered because Bukkit does not offer a way to 
76
 * determine <em>which</em> item is in use; we can only detect if a player is using an item through {@link HumanEntity#isHandRaised()}.</p>
77
 *
78
 * The {@link PlayerRespawnEvent} is always listened to in order to fix a specific item desynchronization issue.
79
 */
80
public class UseItemAdapter extends BaseAdapter {
81
    
82
    private final static String dftag = "system.nocheatplus.useitemadapter";
83
        
84
    // All relevant Bukkit events for item-use.
85
    private final static MiniListener<?>[] miniListeners = new MiniListener<?>[] {
86
        new MiniListener<PlayerItemConsumeEvent>() {
87
            @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
88
            @RegisterMethodWithOrder(tag = dftag)
89
            @Override
90
            public void onEvent(final PlayerItemConsumeEvent event) {
91
                onItemConsume(event);
92
            }
93
        },
94
        new MiniListener<PlayerInteractEvent>() {
95
            @EventHandler(priority = EventPriority.MONITOR)
96
            @RegisterMethodWithOrder(tag = dftag)
97
            @Override
98
            public void onEvent(final PlayerInteractEvent event) {
99
                onItemInteract(event);
100
            }
101
        },
102
        new MiniListener<InventoryOpenEvent>() {
103
            @EventHandler(priority = EventPriority.LOWEST)
104
            @RegisterMethodWithOrder(tag = dftag)
105
            @Override
106
            public void onEvent(final InventoryOpenEvent event) {
107
                onInventoryOpen(event);
108
            }
109
        },
110
        new MiniListener<PlayerDeathEvent>() {
111
            @EventHandler(priority = EventPriority.MONITOR)
112
            @RegisterMethodWithOrder(tag = dftag)
113
            @Override
114
            public void onEvent(final PlayerDeathEvent event) {
115
                onDeath(event);
116
            }
117
        },
118
        new MiniListener<PlayerItemHeldEvent>() {
119
            @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
120
            @RegisterMethodWithOrder(tag = dftag)
121
            @Override
122
            public void onEvent(final PlayerItemHeldEvent event) {
123
                onChangeSlot(event);
124
            }
125
        },
126
    };
127
128
    private static int timeBetweenRL = 70;
129
130
    private static PacketType[] initPacketTypes() {
131
        // Only interested in these two packets.
132
        final List<PacketType> types = new LinkedList<PacketType>(Arrays.asList(PacketType.Play.Client.BLOCK_DIG, PacketType.Play.Client.BLOCK_PLACE));
133
        return types.toArray(new PacketType[types.size()]);
134
    }
135
136
    public UseItemAdapter(Plugin plugin) {
137
        super(plugin, ListenerPriority.MONITOR, initPacketTypes());
138
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
139
        if (!BridgeMisc.hasGetItemInUseMethod()) {
140
            // getItemInUse() isn't there, register all events
141
            if (Bridge1_13.hasPlayerRiptideEvent()) {
142
                // Only register this one if available.
143
                final MiniListener<?> riptideListener = new MiniListener<PlayerRiptideEvent>() {
144
                    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
145
                    @RegisterMethodWithOrder(tag = dftag)
146
                    @Override
147
                    public void onEvent(final PlayerRiptideEvent event) {
148
                        onTridentRelease(event);
149
                   }
150
                };
151
                api.addComponent(riptideListener, false);
152
            }
153
            // ...All the other listeners
154
            for (final MiniListener<?> listener : miniListeners) {
155
                api.addComponent(listener, false);
156
            }
157
        }
158
        // Always register this event, because it is used to fix an MC/Bukkit glitch, not for item-use setting.
159
        final MiniListener<?> respawningListener = new MiniListener<PlayerRespawnEvent>() {
160
            @EventHandler(priority = EventPriority.MONITOR)
161
            @RegisterMethodWithOrder(tag = dftag)
162
            @Override
163
            public void onEvent(final PlayerRespawnEvent event) {
164
                onRespawning(event);
165
            }
166
        };
167
        api.addComponent(respawningListener, false);
168
    }
169
170
    @Override
171
    public void onPacketReceiving(final PacketEvent event) {
172
        // Fast return tests first.
173
        try {
174
            if (event.isPlayerTemporary()) return;
175
        } 
176
        catch (NoSuchMethodError e) {
177
            if (event.getPlayer() == null) {
178
                counters.add(ProtocolLibComponent.idNullPlayer, 1);
179
                return;
180
            }
181
            if (DataManager.getPlayerDataSafe(event.getPlayer()) == null) {
182
                StaticLog.logWarning("Failed to fetch player data with " + event.getPacketType() + " for: " + event.getPlayer().toString());
183
                return;
184
            }
185
        }
186
        if (BridgeMisc.hasGetItemInUseMethod()) {
187
            // getItemInUse() is already there. Only check the digging packet for exploitation prevention purposes.
188
            if (event.getPacketType().equals(PacketType.Play.Client.BLOCK_DIG)) {
189
                handleDiggingPacket(event);
190
            }
191
            // Don't need to do anything else.
192
            return;
193
        }
194
        
195
        // getItemInUse() ins't there: do the ordinary stuff.
196
        if (event.getPacketType().equals(PacketType.Play.Client.BLOCK_DIG)) {
197
            handleDiggingPacket(event);
198
        }
199
        else handleBlockPlacePacket(event);
200
    }
201
    
202
    /** Attempt to fix server-side-only blocking after respawn. */
203
    private static void onRespawning(final PlayerRespawnEvent e) {
204
        final IPlayerData pData = DataManager.getPlayerData(e.getPlayer());
205
        // Patch up issues on Bukkit's (Minecraft's ?) side (item has been reset already on death).
206
        if (Bridge1_9.hasGetItemInOffHand() && e.getPlayer().isBlocking()) {
207
            pData.requestItemUseResync();
208
        }
209
    }
210
211
    private static void onTridentRelease(final PlayerRiptideEvent e) {
212
        final IPlayerData pData = DataManager.getPlayerData(e.getPlayer());
213
        // This event is called on releasing the trident (See ItemTrident.java), so the item is not in use anymore.
214
        pData.setItemInUse(null);
215
    }
216
217
    private static void onItemConsume(final PlayerItemConsumeEvent e) {
218
        final Player p = e.getPlayer();
219
        final IPlayerData pData = DataManager.getPlayerData(p);
220
        // Consume(d) (!!), so the player isn't using the item anymore
221
        pData.setItemInUse(null);   
222
    }
223
224
    private static void onInventoryOpen(final InventoryOpenEvent e) {
225
        if (e.isCancelled()) return;
226
        final Player p = (Player) e.getPlayer();
227
        final IPlayerData pData = DataManager.getPlayerData(p);
228
        // Can't use item with an inventory open.
229
        pData.setItemInUse(null);
230
    }
231
232
    private static void onDeath(final PlayerDeathEvent e) {
233
        final IPlayerData pData = DataManager.getPlayerData((Player) e.getEntity());
234
        // Can't use item if dead
235
        pData.setItemInUse(null);  
236
    }
237
238
    @SuppressWarnings("deprecation")
239
	private static void onItemInteract(final PlayerInteractEvent e) {
240
        if (e.getAction() != Action.RIGHT_CLICK_AIR && e.getAction() != Action.RIGHT_CLICK_BLOCK) {
241
            return;
242
        }
243
        final Player p = e.getPlayer();
244
        final IPlayerData pData = DataManager.getPlayerData(p);
245
        final MovingConfig mCC = pData.getGenericInstance(MovingConfig.class);
246
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
247
        data.offHandUse = false;
248
        if (!data.mightUseItem) {
249
            // Player did not send the block-placement packet, so they are for sure not using anything, return.
250
            return;
251
        }
252
        // Do reset the flag at the start (!)
253
        data.mightUseItem = false;
254
255
        if (e.useItemInHand().equals(Event.Result.DENY)) {
256
            // A plugin denied the item-use.
257
            return;
258
        }
259
260
        if (p.getGameMode() == GameMode.CREATIVE) {
261
            // TODO: If merging SurvivalFly and CreativeFly, creative mode needs to be taken into consideration as well.
262
            pData.setItemInUse(null);
263
            return;
264
        }
265
        
266
        // Proceed to check...
267
        if (e.hasItem()) {
268
            final ItemStack item = e.getItem();
269
            final Material m = item.getType();
270
            if (Bridge1_9.hasElytra() && p.hasCooldown(m)) {
271
                // Item is in cooldown so it cannot be used.
272
                return;
273
            }
274
            
275
            // Edible / consumable items...
276
            if (InventoryUtil.isConsumable(item)) {
277
                if (!Bridge1_9.hasElytra() && item.getDurability() > 16384) {
278
                    // pre1.9 splash potion edge case.
279
                    return;
280
                }
281
                if (m == Material.POTION || m == Material.MILK_BUCKET || m.toString().endsWith("_APPLE") || m.name().startsWith("HONEY_BOTTLE")) {
282
                    // Can be consumed regardless of hunger level
283
                    pData.setItemInUse(m);
284
                    data.offHandUse = Bridge1_9.hasGetItemInOffHand() && e.getHand() == EquipmentSlot.OFF_HAND;
285
                    return;
286
                }
287
                if (item.getType().isEdible() && p.getFoodLevel() < 20) {
288
                    // Hunger level dependant consumables.
289
                    pData.setItemInUse(m); 
290
                    data.offHandUse = Bridge1_9.hasGetItemInOffHand() && e.getHand() == EquipmentSlot.OFF_HAND;
291
                    return;
292
                }
293
            }
294
            // Bows...
295
            if (m == Material.BOW && InventoryUtil.hasArrow(p.getInventory(), false)) {
296
                pData.setItemInUse(m);
297
                data.offHandUse = Bridge1_9.hasGetItemInOffHand() && e.getHand() == EquipmentSlot.OFF_HAND;
298
                return;
299
            }
300
            // Shields and swords (legacy)... Bukkit takes care here, but set anyway.
301
            if (ServerVersion.isAtLeast("1.9") && pData.getClientVersion().isAtLeast(ClientVersion.V_1_9)) {
302
                // Both server and client are on a version that support shield (thus, sword-blocking is not possible)
303
            	if (m == Material.SHIELD) {
304
            	    pData.setItemInUse(m);
305
                    data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
306
                    return;
307
            	}
308
            }
309
            else if (MaterialUtil.isSword(m) && (ServerVersion.isLowerThan("1.9") || pData.getClientVersion().isAtMost(ClientVersion.V_1_8))) {
310
            	// Legacy server. Or legacy client on a modern server. Blocking is done with swords in both cases.
311
            	pData.setItemInUse(m);
312
            	// (Off hand doesn't exist)
313
            	return;
314
            }
315
            
316
            // Crosswbows...
317
            if (m.toString().equals("CROSSBOW")) {
318
                if (!((CrossbowMeta) item.getItemMeta()).hasChargedProjectiles() && InventoryUtil.hasArrow(p.getInventory(), true)) {
319
                    pData.setItemInUse(m);
320
                    data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
321
                }
322
            }
323
            // Tridents (1.13)... 
324
            if (m == BridgeMaterial.TRIDENT && item.getDurability() < m.getMaxDurability() - 1 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_13)
325
            	&& (
326
                    // 1: If the trident has riptide enchant, it can only be used in rain or water 
327
            		BridgeEnchant.getRiptideLevel(p) > 0.0
328
                    && (
329
                        // 2: In water
330
                        BlockProperties.isInWater(p, p.getLocation(), mCC.yOnGround)
331
                        // 2: Always check raining first, since canSeeSky is a much more expensive call. Needs optimization.
332
                        || p.getLocation().getWorld().hasStorm() && BlockProperties.canSeeSky(p, p.getLocation(), mCC.yOnGround) 
333
                    ) 
334
                    // 1: Otherwise, the trident can be used and thrown anywhere
335
                    || BridgeEnchant.getRiptideLevel(p) <= 0.0
336
                )) {
337
                pData.setItemInUse(m);
338
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
339
                return;
340
            }
341
            // Spyglass (1.17)...
342
            if (BridgeMisc.hasIsFrozen() && m == Material.SPYGLASS) {
343
                pData.setItemInUse(m);
344
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
345
                return;
346
            }
347
            // Lastly, goat horns (1.19)...
348
            if (m.toString().equals("GOAT_HORN")) {
349
                pData.setItemInUse(m);
350
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
351
                return;
352
            }
353
            // 1.21.11: Spears...
354
            if (MaterialUtil.isSpear(m)) {
355
                pData.setItemInUse(m);
356
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
357
            }
358
        } 
359
        else {
360
            // No item in hands, no deal.
361
            pData.setItemInUse(null);  
362
        }
363
    }
364
    
365
    // NOTE: Bukkit takes care of invalid slot values (< 0 or > 8. PlayerConnection.java), so we don't need to check for this as well.
366
    private static void onChangeSlot(final PlayerItemHeldEvent e) {
367
        final Player p = e.getPlayer();
368
        final IPlayerData pData = DataManager.getPlayerData(p);
369
        // Switching a slot, so the item use status is reset.
370
        final MovingData mData = pData.getGenericInstance(MovingData.class);
371
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
372
        if (e.getPreviousSlot() != e.getNewSlot()) {
373
            /*if ((pData.getItemInUse() != null || p.isBlocking()) && mData.playerMoves.getCurrentMove() != null) {
374
                p.getInventory().setHeldItemSlot(e.getPreviousSlot());
375
                cData.invalidItemUse = true;
376
            }*/
377
            // To avoid any more potential bypasses, let Minecraft forcibly release the item.
378
            pData.requestItemUseResync();
379
        }
380
    }
381
382
    private void handleBlockPlacePacket(PacketEvent event) {
383
        final Player p = event.getPlayer();
384
        final IPlayerData pData = DataManager.getPlayerData(p);
385
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
386
        final PacketContainer packet = event.getPacket();
387
        final StructureModifier<Integer> ints = packet.getIntegers();
388
        // Legacy: pre 1.9
389
        if (ints.size() > 0 && !ServerVersion.isAtLeast("1.9")) {
390
            final int faceIndex = ints.read(0); // arg 3 if 1.7.10 below
391
            if (faceIndex <= 5) {
392
                data.mightUseItem = false;
393
                return;
394
            }
395
        }
396
        // Player sends a block-placement item when right-clicking, so they might be actually using an item. Set the flag.
397
        if (!event.isCancelled()) data.mightUseItem = true;
398
    }
399
400
    private void handleDiggingPacket(PacketEvent event) {
401
        Player p = event.getPlayer();       
402
        final IPlayerData pData = DataManager.getPlayerDataSafe(p);
403
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
404
        PlayerDigType digtype = event.getPacket().getPlayerDigTypes().read(0);
405
        if (!BridgeMisc.hasGetItemInUseMethod()) {
406
            // DROP_ALL_ITEMS when dead?
407
            if (digtype == PlayerDigType.DROP_ALL_ITEMS || digtype == PlayerDigType.DROP_ITEM) {
408
                pData.setItemInUse(null);
409
            }
410
        }
411
        
412
        if (digtype == PlayerDigType.RELEASE_USE_ITEM) {
413
            pData.setItemInUse(null);
414
            long now = System.currentTimeMillis();
415
            if (data.releaseItemTime != 0) {
416
                if (now < data.releaseItemTime) {
417
                    data.releaseItemTime = now;
418
                    return;
419
                }
420
                if (data.releaseItemTime + timeBetweenRL > now) {
421
                    data.isHackingRI = true;
422
                }
423
            }
424
            data.releaseItemTime = now;
425
        }
426
    }
427
428
    /**
429
     * Set Minimum time between RELEASE_USE_ITEM packet is sent.
430
     * If time lower this value, A check will flag
431
     * Should be set from 51-100. Larger number, more protection more false-positive
432
     * 
433
     * @param time milliseconds
434
     */ 
435
    public static void setuseRLThreshold(int time) {
436
        timeBetweenRL = time;
437
    }   
438
}

How it counteracts this module

NCP's ProtocolLib adapter tracks the item-use lifecycle at the packet level. handleDiggingPacket, on RELEASE_USE_ITEM, clears the player's item-in-use and compares the release timestamp against the previous one: if the gap is under timeBetweenRL = 70ms, CombinedData.isHackingRI is set true (line 421). The comment documents the threshold intent: minimum time between release packets, 51-100ms, higher meaning more protection.

The module's cycle sends exactly one release per tick, 50ms apart, so every release after the first lands inside the 70ms window and isHackingRI stays armed. SurvivalFly consumes the flag at the top of its horizontal prediction (line 877): it tags the move 'noslowpacket', feeds Improbable with 'moving.survivalfly.noslow', resets the horizontal data and returns a violation, so the release spam converts directly into a movement violation on the very next C03. This is the one check in the set that fires deterministically on the module.

anticheat NoSlowCheck (1.9+ protocol state machine)

NoSlowCheck.java51 lines · Java
1
package better.anticheat.core.check.broken;
2
3
import better.anticheat.core.BetterAnticheat;
4
import better.anticheat.core.check.Check;
5
import better.anticheat.core.check.CheckInfo;
6
import better.anticheat.core.player.Player;
7
import com.github.retrooper.packetevents.event.simple.PacketPlayReceiveEvent;
8
import com.github.retrooper.packetevents.protocol.player.DiggingAction;
9
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientEntityAction;
10
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPlayerDigging;
11
12
@CheckInfo(name = "NoSlow", category = "combat")
13
public class NoSlowCheck extends Check {
14
    private boolean blocking = false, sprinting = false;
15
16
    public NoSlowCheck(BetterAnticheat plugin, Player player) {
17
        super(plugin, player);
18
    }
19
20
    @Override
21
    public void handleReceivePlayPacket(PacketPlayReceiveEvent event) {
22
23
        /*
24
         * This check is intended to detect starting sprinting while using an item (like blocking a shield, shooting a
25
         * bow, or eating food). However, this check has unexplainable falses.
26
         */
27
28
        switch (event.getPacketType()) {
29
            case USE_ITEM:
30
                blocking = true;
31
                sprinting = false;
32
                break;
33
            case ENTITY_ACTION:
34
                WrapperPlayClientEntityAction actionWrapper = new WrapperPlayClientEntityAction(event);
35
                if (actionWrapper.getAction().equals(WrapperPlayClientEntityAction.Action.START_SPRINTING)) {
36
                    sprinting = true;
37
                }
38
                break;
39
            case PLAYER_DIGGING:
40
                WrapperPlayClientPlayerDigging diggingWrapper = new WrapperPlayClientPlayerDigging(event);
41
                if (diggingWrapper.getAction() != DiggingAction.RELEASE_USE_ITEM) return;
42
43
                // Only flag on use item release as previously we don't know if the player is actually blocking.
44
45
                if (blocking && sprinting) fail();
46
                blocking = false;
47
48
                break;
49
        }
50
    }
51
}

How it counteracts this module

BetterAnticheat's NoSlowCheck arms a blocking flag on the 1.9+ USE_ITEM packet, arms sprinting on an ENTITY_ACTION START_SPRINTING, and fails when a RELEASE_USE_ITEM arrives while both are set: the signature of starting a sprint while using an item. The class comment notes it is 'intended to detect starting sprinting while using an item... however, this check has unexplainable falses.'

Against this module it is a documented miss on protocol grounds: on a 1.8.9 client the blocking start arrives as a C08 BlockPlace packet, which the check does not track as USE_ITEM, and this module's C08 re-arm is dead code, so blocking is never armed and the release stream cannot fail the check. It is the modern-protocol counterpart of the same exploit: the check that the C07+C08 re-arm cycle of other clients is designed against.

anticheat RepeatedReleaseCheck (release-without-use)

RepeatedReleaseCheck.java57 lines · Java
1
package better.anticheat.core.check.broken;
2
3
import better.anticheat.core.BetterAnticheat;
4
import better.anticheat.core.check.Check;
5
import better.anticheat.core.check.CheckInfo;
6
import better.anticheat.core.player.Player;
7
import com.github.retrooper.packetevents.event.simple.PacketPlayReceiveEvent;
8
import com.github.retrooper.packetevents.protocol.player.DiggingAction;
9
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPlayerDigging;
10
11
/*
12
 * NOTE: This check is currenlty not enabled due to false flag issues.
13
 * Use Item mechanics may have changed since this was originally designed?
14
 */
15
@CheckInfo(name = "RepeatedRelease", category = "dig")
16
public class RepeatedReleaseCheck extends Check {
17
    private boolean useItem = true;
18
19
    public RepeatedReleaseCheck(BetterAnticheat plugin, Player player) {
20
        super(plugin, player);
21
    }
22
23
    @Override
24
    public void handleReceivePlayPacket(PacketPlayReceiveEvent event) {
25
26
        /*
27
         * For some reason you can send multiple releases? Needs debugging.
28
         */
29
30
        switch (event.getPacketType()) {
31
            //Keep track of whether the player sent an initial use item packet.
32
            case USE_ITEM:
33
                useItem = true;
34
35
                break;
36
            case PLAYER_DIGGING:
37
                WrapperPlayClientPlayerDigging wrapper = new WrapperPlayClientPlayerDigging(event);
38
39
                /*
40
                 * In 1.9 and above using an item works as the following:
41
                 * First, the client initiates it by sending a use item packet.
42
                 * Second, the client releases it by sending a block dig packet.
43
                 *
44
                 * This means that between all release use item digs there must be a use item.
45
                 * From my testing, it does not appear like there must be a release between uses as there are edge
46
                 * cases that make UseItem seem to de-sync.
47
                 */
48
                if (wrapper.getAction() == DiggingAction.RELEASE_USE_ITEM) {
49
                    if (!useItem) fail();
50
51
                    useItem = false;
52
                }
53
54
                break;
55
        }
56
    }
57
}

How it counteracts this module

RepeatedReleaseCheck encodes the 1.9+ item-use contract: a USE_ITEM packet must sit between every pair of RELEASE_USE_ITEM packets. It tracks useItem, sets it on USE_ITEM, and fails any RELEASE_USE_ITEM that arrives with useItem false, then clears the flag. The file's own header notes the check is not currently enabled due to false-flag issues.

When enabled it is a direct hit on this module: the initial field value true lets the first release through, but no USE_ITEM ever follows (the C08 re-arm is dead code), so every release after the first arrives with useItem false and fails. The module's release-only cycle is exactly the stream the check was written to reject. The module simply predates the protocol change the check assumes.

anticheat Speed (item-use slowdown branch)

Speed.java280 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.check.movement.position;
20
21
import me.islandscout.hawk.Hawk;
22
import me.islandscout.hawk.HawkPlayer;
23
import me.islandscout.hawk.check.MovementCheck;
24
import me.islandscout.hawk.event.Event;
25
import me.islandscout.hawk.event.HawkEventListener;
26
import me.islandscout.hawk.event.ItemSwitchEvent;
27
import me.islandscout.hawk.event.MoveEvent;
28
import me.islandscout.hawk.util.*;
29
import me.islandscout.hawk.wrap.entity.WrappedEntity;
30
import org.bukkit.ChatColor;
31
import org.bukkit.Material;
32
import org.bukkit.enchantments.Enchantment;
33
import org.bukkit.entity.Player;
34
import org.bukkit.event.Listener;
35
import org.bukkit.util.Vector;
36
37
import java.util.*;
38
39
public class Speed extends MovementCheck implements Listener {
40
41
    //I legit hate this game's movement.
42
    //Do you realize how much easier it would be if
43
    //the server handled movement?
44
45
    //TODO False flag with pistons
46
47
    //Basically, this check is doing, "if your previous speed was X then your current speed must not exceed f(X)"
48
49
    private static final double EPSILON = 0.000001;
50
    //Now what we can do is predict how far a player could have travelled
51
    //if the move doesn't have a deltaPos due to insignificance.
52
    private static final double MAX_NO_MOVE_DISTANCE = 0.03;
53
    private final double DISCREPANCY_THRESHOLD;
54
    private final double VL_FAIL_DISCREPANCY_FACTOR;
55
    private final boolean RESET_DISCREPANCY_ON_FAIL;
56
    private final int RELEASE_ITEM_OVER_VL;
57
    private final boolean CHECK_FLYING;
58
    private final boolean DEBUG;
59
60
    private final Map<UUID, Double> prevSpeed;
61
    private final Map<UUID, Double> discrepancies;
62
    private final Map<UUID, Integer> noMovesMap;
63
    private final Map<UUID, Double> lastNegativeDiscrepancies;
64
    private final Map<UUID, Double> negativeDiscrepanciesCumulative;
65
    private final Map<UUID, Integer> slotSwitchQuirkTicksMap; //I hate this game.
66
    private final Map<UUID, Long> lastSlotSwitchTickMap;
67
68
    public Speed() {
69
        super("speed", true, 0, 5, 0.99, 5000, "%player% failed movement speed, VL: %vl%", null);
70
        prevSpeed = new HashMap<>();
71
        discrepancies = new HashMap<>();
72
        noMovesMap = new HashMap<>();
73
        lastNegativeDiscrepancies = new HashMap<>();
74
        negativeDiscrepanciesCumulative = new HashMap<>();
75
        slotSwitchQuirkTicksMap = new HashMap<>();
76
        lastSlotSwitchTickMap = new HashMap<>();
77
        DISCREPANCY_THRESHOLD = (double) customSetting("discrepancyThreshold", "", 0.1D);
78
        VL_FAIL_DISCREPANCY_FACTOR = (double) customSetting("vlFailDiscrepancyFactor", "", 10D);
79
        RESET_DISCREPANCY_ON_FAIL = (boolean) customSetting("resetDiscrepancyOnFail", "", true);
80
        RELEASE_ITEM_OVER_VL = (int) customSetting("releaseItemOverVl", "", 4);
81
        CHECK_FLYING = (boolean) customSetting("checkFlying", "", true);
82
        DEBUG = (boolean) customSetting("debug", "", false);
83
    }
84
85
    @Override
86
    protected void check(MoveEvent event) {
87
        Player p = event.getPlayer();
88
        HawkPlayer pp = event.getHawkPlayer();
89
90
        int noMoves = noMovesMap.getOrDefault(p.getUniqueId(), 0);
91
        double lastSpeed;
92
        double speed;
93
        if(event.isUpdatePos()) {
94
            lastSpeed = prevSpeed.getOrDefault(p.getUniqueId(), 0D);
95
            if(noMoves > 0) {
96
                //Players don't update position unless they've moved at least 0.03 blocks (or if 20 ticks passed)
97
                lastSpeed = Math.min(lastSpeed, MAX_NO_MOVE_DISTANCE);
98
            }
99
            speed = MathPlus.distance2d(event.getTo().getX() - event.getFrom().getX(), event.getTo().getZ() - event.getFrom().getZ());
100
        }
101
        else {
102
            speed = prevSpeed.getOrDefault(p.getUniqueId(), 0D) - (lastNegativeDiscrepancies.getOrDefault(p.getUniqueId(), 0D) + EPSILON);
103
            lastSpeed = speed;
104
        }
105
106
        if(event.isUpdatePos())
107
            noMoves = 0;
108
        else
109
            noMoves++;
110
111
        boolean flying = pp.isFlying();
112
        boolean swimming = pp.isInWater(); //this needs improvement
113
        //it is possible that the player has pressed the jump key even if this move is "stepped" (only while sprinting)
114
        boolean jump = event.isJump() || (event.isStep() && pp.isOnGround() && pp.isSprinting());
115
116
        float friction = event.getFriction();
117
        float maxForce = event.getMaxExpectedInputForce();
118
        float maxForceNoItemUse = event.getMaxExpectedInputForceNoItemUse();
119
120
        //It represents the previous location. Block collision is done after moving the entity.
121
        Set<Material> touchedBlocks = WrappedEntity.getWrappedEntity(p).getCollisionBox(event.getFrom().toVector()).getMaterials(pp.getWorld());
122
123
        //handle any pending knockbacks
124
        if(event.hasAcceptedKnockback() || (flying && !CHECK_FLYING)) {
125
            prepareNextMove(pp, noMoves, speed, touchedBlocks);
126
            return;
127
        }
128
129
        double lastSpeedCompare = lastSpeed;
130
        //Handle other things in the game that multiply velocity.
131
        //These affect velocity first (coincidentally, these are all multiplication operations)
132
        double handleMultipliers = 1;
133
        if(event.hasHitSlowdown())
134
            handleMultipliers *= 0.6;
135
        if(touchedBlocks.contains(Material.SOUL_SAND) && !flying)
136
            handleMultipliers *= 0.4;
137
        if(touchedBlocks.contains(Material.WEB) && !flying)
138
            handleMultipliers *= 0.25;
139
        if(Hawk.getServerVersion() > 7 && touchedBlocks.contains(Material.SLIME_BLOCK)) {
140
            //TODO I believe webs affect this mot Y too.
141
            if (Math.abs(pp.getVelocity().getY()) < 0.1 && !pp.isSneaking()) {
142
                handleMultipliers *= 0.4 + Math.abs(pp.getVelocity().getY()) * 0.2;
143
            }
144
        }
145
        //Handle other things in the game that add to velocity.
146
        //These affect velocity later (coincidentally, these are all addition operations)
147
        double handleAdders = 0;
148
        if(pp.isSprinting() && jump) {
149
            handleAdders += 0.2;
150
        }
151
        if(swimming && !flying) { //This is actually a terrible way of handling horizontal water flow.
152
            Vector move = new Vector(event.getTo().getX() - event.getFrom().getX(), 0, event.getTo().getZ() - event.getFrom().getZ());
153
            Vector waterForce = event.getWaterFlowForce().clone().setY(0);
154
            double waterForceLength = waterForce.length() + 0.003; //add epsilon to allow room for error
155
            double moveLength = move.length();
156
            double computedForce = moveLength == 0 ? waterForceLength : (move.dot(waterForce) / moveLength);
157
158
            handleAdders += computedForce;
159
        }
160
161
        //Finally, the expected speed calculation. There's another "expected" because of a dumb quirk when switching slots while using an item.
162
        //Optimize later.
163
        double expected = friction * lastSpeedCompare * handleMultipliers + (maxForce + handleAdders + EPSILON);
164
        double expectedNoItemUse = friction * lastSpeedCompare * handleMultipliers + (maxForceNoItemUse + handleAdders + EPSILON);
165
166
        //I hate this game. Handle slot switching quirk. The slot switch packet is delayed by a tick.
167
        //This sort of "event listening" must be done because Hawk's MoveEvents can be skipped under certain conditions.
168
        long slotSwitchTick = pp.getLastSlotSwitchTick();
169
        boolean switchedSlot = slotSwitchTick != lastSlotSwitchTickMap.getOrDefault(p.getUniqueId(), slotSwitchTick);
170
        int slotSwitchQuirkTicks = slotSwitchQuirkTicksMap.getOrDefault(p.getUniqueId(), 0);
171
        if(switchedSlot) {
172
            slotSwitchQuirkTicks = 0;
173
        }
174
        lastSlotSwitchTickMap.put(p.getUniqueId(), slotSwitchTick);
175
176
        //Calculate discrepancy.
177
        Discrepancy discrepancy; //This is the one that will be used for final comparison. It is the value of either discrepancyBase or discrepancyNoItemUse.
178
        Discrepancy discrepancyBase; //Used for pretty much 99.99% of moves.
179
        Discrepancy discrepancyNoItemUse; //Similar to discrepancyBase, but doesn't consider item-use slowdown.
180
181
        discrepancyBase = new Discrepancy(expected, speed);
182
        discrepancyNoItemUse = new Discrepancy(expectedNoItemUse, speed);
183
        if((pp.isBlocking() || pp.isConsumingItem() || pp.isPullingBow()) && Math.abs(discrepancyNoItemUse.value) < Math.abs(discrepancyBase.value)) {
184
            //This means that they're using an item, but they're moving at normal speed. This COULD be due to that
185
            //dumb item switch quirk, so we'll grant them only one extra tick. It resets when they switch their slot.
186
            if(slotSwitchQuirkTicks < 1) {
187
                //Allow them to move at normal speed for 1 tick.
188
                discrepancy = discrepancyNoItemUse;
189
                slotSwitchQuirkTicks++;
190
            } else {
191
                discrepancy = discrepancyBase;
192
            }
193
        } else {
194
            discrepancy = discrepancyBase;
195
        }
196
197
        //Client told server that it updated its position. Checking time.
198
        if (event.isUpdatePos()) {
199
            double haltDistanceExpected = negativeDiscrepanciesCumulative.getOrDefault(p.getUniqueId(), 0D);
200
            lastNegativeDiscrepancies.put(p.getUniqueId(), 0D);
201
            if(discrepancy.value < 0 || speed > haltDistanceExpected)
202
                discrepancies.put(p.getUniqueId(), Math.max(discrepancies.getOrDefault(p.getUniqueId(), 0D) + discrepancy.value, 0));
203
            double totalDiscrepancy = discrepancies.getOrDefault(p.getUniqueId(), 0D);
204
205
            if(DEBUG) {
206
                p.sendMessage((totalDiscrepancy > DISCREPANCY_THRESHOLD ? ChatColor.RED : ChatColor.GREEN) + "" + totalDiscrepancy);
207
            }
208
209
            if(discrepancy.value > 0 && totalDiscrepancy > DISCREPANCY_THRESHOLD && !event.isPossiblePistonPush()) {
210
                punishAndTryRubberband(pp, discrepancy.value * VL_FAIL_DISCREPANCY_FACTOR, event);
211
                if(RESET_DISCREPANCY_ON_FAIL)
212
                    discrepancies.put(p.getUniqueId(), 0D);
213
                if(RELEASE_ITEM_OVER_VL > -1 && (pp.isPullingBow() || pp.isConsumingItem() || pp.isBlocking()) && pp.getVL(this) > RELEASE_ITEM_OVER_VL)
214
                    pp.releaseItem();
215
            }
216
            else {
217
                reward(pp);
218
            }
219
220
            lastNegativeDiscrepancies.put(p.getUniqueId(), 0D);
221
            negativeDiscrepanciesCumulative.put(p.getUniqueId(), 0D);
222
        }
223
        //Client sent a flying packet, but didn't update position.
224
        //The move might have not been significant enough, so we need
225
        //to prepare for when the client decides it's time to update
226
        //position.
227
        else {
228
            lastNegativeDiscrepancies.put(p.getUniqueId(), discrepancy.value);
229
230
            //TODO improve these two lines...
231
            double val = negativeDiscrepanciesCumulative.getOrDefault(p.getUniqueId(), 0D);
232
            negativeDiscrepanciesCumulative.put(p.getUniqueId(), Math.min(val + speed, MAX_NO_MOVE_DISTANCE + speed));
233
            //negativeDiscrepanciesCumulative.put(p.getUniqueId(), negativeDiscrepanciesCumulative.getOrDefault(p.getUniqueId(), 0D) + speed);
234
        }
235
236
        slotSwitchQuirkTicksMap.put(p.getUniqueId(), slotSwitchQuirkTicks);
237
        prepareNextMove(pp, noMoves, speed, touchedBlocks);
238
    }
239
240
    private void prepareNextMove(HawkPlayer pp, int noMoves, double currentSpeed, Set<Material> touchedBlocks) {
241
        if(touchedBlocks.contains(Material.WEB) && !pp.isFlying()) {
242
            currentSpeed = 0;
243
        }
244
        UUID uuid = pp.getUuid();
245
        prevSpeed.put(uuid, currentSpeed);
246
        noMovesMap.put(uuid, noMoves);
247
    }
248
249
    public void removeData(Player p) {
250
        UUID uuid = p.getUniqueId();
251
        prevSpeed.remove(uuid);
252
        discrepancies.remove(uuid);
253
        noMovesMap.remove(uuid);
254
        lastNegativeDiscrepancies.remove(uuid);
255
        negativeDiscrepanciesCumulative.remove(uuid);
256
        slotSwitchQuirkTicksMap.remove(uuid);
257
        lastSlotSwitchTickMap.remove(uuid);
258
    }
259
260
    //speed potions do not affect swimming
261
    private Discrepancy waterMapping(double lastSpeed, double currentSpeed, double waterFlowForce) {
262
        double expected = 0.800001 * lastSpeed + 0.020001 + waterFlowForce;
263
        return new Discrepancy(expected, currentSpeed);
264
    }
265
266
    private Discrepancy lavaMapping(double lastSpeed, double currentSpeed) {
267
        double expected = 0.500001 * lastSpeed + 0.020001;
268
        return new Discrepancy(expected, currentSpeed);
269
    }
270
271
    private class Discrepancy {
272
273
        double value;
274
275
        Discrepancy(double expectedSpeed, double currentSpeed) {
276
            value = currentSpeed - expectedSpeed;
277
        }
278
279
    }
280
}

How it counteracts this module

Hawk's Speed computes two expected speeds per move: one with the item-use slowdown (maxForce) and one without (maxForceNoItemUse). While the server believes the player is blocking, consuming or pulling a bow, the item-use expectation is used unless the player is moving at full speed, in which case they are granted exactly one extra tick for the slot-switch quirk, then judged against the slowed expectation. A discrepancy over 0.1 at a position update triggers the rubberband, and at VL above RELEASE_ITEM_OVER_VL (default 4) the check force-releases the item via pp.releaseItem().

For this module the branch only bites in the window where the server still believes the player is blocking: the release spam clears the server-side item-use on the first packet, so after one tick Hawk treats the player as a normal non-blocking mover and the full-speed C03s pass. The check is the counter to the C08-re-arming NoSlow variants that keep the server-side blocking state alive, the behavior this module's dead re-arm deliberately avoids.

← Back to Analysis Hub