LiquidSense Dev AutoPot module 2 files, 600 lines

LiquidSense Dev AutoPot: Full Source Analysis

AutoPot is a health-gated splash healer that routes instant healing potions from the inventory into the hotbar and throws them through a rotation-gated use-item ceremony.

net/ccbluex/liquidbounce/features/module/modules/combat/AutoPot.kt · GitHub source ↗

Published 2026-08-13 · Updated 2026-08-13

Analysis

Overview

AutoPot is a health-gated splash healer that routes instant healing potions from the inventory into the hotbar and throws them through a rotation-gated use-item ceremony. The handler runs on the PRE stage of MotionEvent and bails while the player is flying, in creative mode, while any container window is open, or while Aura holds a target, so a throw never competes with combat rotations. findPotion scans the hotbar (slots 36-45) first and then the inventory (9-36) for splash potions carrying instant health, regeneration when the effect is not active, or move speed when the buff is missing; the heal scan only runs while health is at or below the Health threshold (default 15). The hotbar path swaps to the potion with C09, arms a throw rotation with a random 80-90 pitch via RotationUtils, waits until serverRotation.pitch reaches 80, then sends the C08 use-item packet and a C09 restore in the same tick. The inventory path refills the hotbar with a simulated open-inventory ceremony: C16 OPEN_INVENTORY_ACHIEVEMENT, a window-0 shift-click C0E, and C0D close.

Gate chain and slot finder

onMotion rejects the whole routine while mc.thePlayer.capabilities has allowFlying and isFlying both set, while playerController.isInCreativeMode, while msTimer.hasTimePassed(delayValue) is false (Delay 500-1000, default 500, a real period because the timer is reset after every action), while the open container's windowId differs from 0, and while Aura.target is non-null. findPotion(36, 45) walks the hotbar container range and findPotion(9, 36) the main inventory, returning the first splash potion (ItemPotion.isSplash) whose effects match the priority list: instant heal when health <= Health, regeneration when the player is not already affected, then move speed when the buff is absent. The scan returns the container index or -1, and the hotbar index for the C09 is the container index minus 36.

Rotation-gated throw ceremony

With a hotbar potion and no GuiInventory open, the PRE stage records potion = slot - 36 and queues C09(potion). If the current pitch is at or below 80 degrees, RotationUtils.setTargetRotation is armed with the current yaw and a pitch drawn uniformly from 80 to 90 (RandomUtils.nextFloat); the actual C08PacketPlayerBlockPlacement(itemStack) fires only once RotationUtils.serverRotation.pitch has reached 80. serverRotation is refreshed from the last rotating C03/C06 the client actually sent (RotationUtils line 411), so the throw waits until the look change is on the wire rather than firing from the local aim. The single-argument C08 constructor serializes BlockPos.ORIGIN with face 255, the protocol's use-item form that routes to ItemPotion.onItemRightClick. Immediately after, C09(mc.thePlayer.inventory.currentItem) restores the held slot, potion resets to -1 and msTimer.reset() starts the cooldown. The Jump and Port modes modify the throw: onGround gates thePlayer.jump() or moveEntity(0.0, 0.42, 0.0) so the splash lands under a rising player instead of at the feet.

Simulated inventory refill

When a potion sits in the inventory (9-36) and the hotbar has space, the module refills it: with OpenInv on it returns unless a real GuiInventory is open, while with SimulateInventory on it fabricates the window. The fabrication sends C16PacketClientStatus(OPEN_INVENTORY_ACHIEVEMENT), performs mc.playerController.windowClick(0, slot, 0, 1), the C0E mode-1 shift-click, and closes with C0DPacketCloseWindow. The client never renders a GUI, so the window exists only in the server's container ledger. Whether the fork's windowClick also syncs the held slot with a C09 cannot be verified here: the LiquidSense Dev snapshot ships no net/minecraft tree, so the vanilla sync contract is the only claim.

source AutoPot.kt

AutoPot.kt146 lines · JavaOriginal ↗
1
/*
2
 * LiquidBounce Hacked Client
3
 * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
4
 * https://github.com/CCBlueX/LiquidBounce/
5
 */
6
package net.ccbluex.liquidbounce.features.module.modules.combat
7
8
import net.ccbluex.liquidbounce.LiquidBounce
9
import net.ccbluex.liquidbounce.event.EventState.POST
10
import net.ccbluex.liquidbounce.event.EventState.PRE
11
import net.ccbluex.liquidbounce.event.EventTarget
12
import net.ccbluex.liquidbounce.event.MotionEvent
13
import net.ccbluex.liquidbounce.features.module.Module
14
import net.ccbluex.liquidbounce.features.module.ModuleCategory
15
import net.ccbluex.liquidbounce.features.module.ModuleInfo
16
import net.ccbluex.liquidbounce.utils.*
17
import net.ccbluex.liquidbounce.utils.misc.FallingPlayer
18
import net.ccbluex.liquidbounce.utils.misc.RandomUtils
19
import net.ccbluex.liquidbounce.utils.timer.MSTimer
20
import net.ccbluex.liquidbounce.value.BoolValue
21
import net.ccbluex.liquidbounce.value.FloatValue
22
import net.ccbluex.liquidbounce.value.IntegerValue
23
import net.ccbluex.liquidbounce.value.ListValue
24
import net.minecraft.client.gui.inventory.GuiInventory
25
import net.minecraft.item.ItemPotion
26
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement
27
import net.minecraft.network.play.client.C09PacketHeldItemChange
28
import net.minecraft.network.play.client.C0DPacketCloseWindow
29
import net.minecraft.network.play.client.C16PacketClientStatus
30
import net.minecraft.potion.Potion
31
32
@ModuleInfo(name = "AutoPot", description = "Automatically throws healing potions.", category = ModuleCategory.COMBAT)
33
class AutoPot : Module() {
34
35
    private val healthValue = FloatValue("Health", 15F, 1F, 20F)
36
    private val delayValue = IntegerValue("Delay", 500, 500, 1000)
37
38
    private val openInventoryValue = BoolValue("OpenInv", false)
39
    private val simulateInventory = BoolValue("SimulateInventory", true)
40
41
    private val groundDistanceValue = FloatValue("GroundDistance", 2F, 0F, 5F)
42
    private val modeValue = ListValue("Mode", arrayOf("Normal", "Jump", "Port"), "Normal")
43
44
    private val msTimer = MSTimer()
45
    private var potion = -1
46
47
    @EventTarget
48
    fun onMotion(motionEvent: MotionEvent) {
49
        val killAura = LiquidBounce.moduleManager.getModule(Aura::class.java) as Aura
50
51
        if ((mc.thePlayer!!.capabilities.allowFlying && mc.thePlayer!!.capabilities.isFlying) || !msTimer.hasTimePassed(delayValue.get().toLong()) || mc.playerController.isInCreativeMode || (mc.thePlayer!!.openContainer != null && mc.thePlayer!!.openContainer!!.windowId != 0) || killAura.target != null)
52
            return
53
54
        val thePlayer = mc.thePlayer ?: return
55
        val potionInHotbar = findPotion(36, 45)
56
        // Inventory Potion -> Hotbar Potion
57
        val potionInInventory = findPotion(9, 36)
58
59
60
        when (motionEvent.eventState) {
61
            PRE -> {
62
                // Hotbar Potion
63
64
                if (potionInHotbar != -1 && mc.currentScreen !is GuiInventory) {
65
                    if (thePlayer.onGround) {
66
                        when (modeValue.get().toLowerCase()) {
67
                            "jump" -> thePlayer.jump()
68
                            "port" -> thePlayer.moveEntity(0.0, 0.42, 0.0)
69
                        }
70
                    }
71
72
                    potion = potionInHotbar - 36
73
                    mc.netHandler.addToSendQueue(C09PacketHeldItemChange(potion))
74
75
                    if (thePlayer.rotationPitch <= 80F) {
76
77
                        RotationUtils.setTargetRotation(Rotation(thePlayer.rotationYaw, RandomUtils.nextFloat(80F, 90F)))
78
                        if (potion != -1 && RotationUtils.serverRotation.pitch >= 80F) {
79
                            val itemStack = thePlayer.inventory.getStackInSlot(potion)
80
81
                            if (itemStack != null) {
82
                                mc.netHandler.addToSendQueue(C08PacketPlayerBlockPlacement(itemStack))
83
                                mc.netHandler.addToSendQueue(C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem))
84
                            }
85
                            potion = -1
86
                            msTimer.reset()
87
                        }
88
                    }
89
                }
90
91
                if ((potionInInventory != -1 && potion == -1) && InventoryUtils.hasSpaceHotbar()) {
92
                    if (openInventoryValue.get() && mc.currentScreen !is GuiInventory)
93
                        return
94
95
                    val openInventory = mc.currentScreen !is GuiInventory && simulateInventory.get()
96
97
                    if (openInventory)
98
                        mc.netHandler.addToSendQueue(
99
                                C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT))
100
101
                    mc.playerController.windowClick(0, potionInInventory, 0, 1, thePlayer)
102
103
                    if (openInventory)
104
                        mc.netHandler.addToSendQueue(C0DPacketCloseWindow())
105
106
                    msTimer.reset()
107
                }
108
            }
109
        }
110
    }
111
112
    private fun findPotion(startSlot: Int, endSlot: Int): Int {
113
        val thePlayer = mc.thePlayer!!
114
115
        for (i in startSlot until endSlot) {
116
            val stack = thePlayer.inventoryContainer.getSlot(i).stack
117
118
            if (stack == null || stack.item !is ItemPotion || !ItemPotion.isSplash(stack.itemDamage))
119
                continue
120
121
            val itemPotion = stack.item as ItemPotion
122
123
            if (thePlayer.health <= healthValue.get()) {
124
                for (potionEffect in itemPotion.getEffects(stack))
125
                    if (potionEffect.potionID == Potion.heal.id)
126
                        return i
127
128
                if (!thePlayer.isPotionActive(Potion.regeneration.id))
129
                    for (potionEffect in itemPotion.getEffects(stack))
130
                        if (potionEffect.potionID == Potion.regeneration.id)
131
                            return i
132
            }
133
134
            if (!thePlayer.isPotionActive(Potion.moveSpeed.id))
135
                for (potionEffect in itemPotion.getEffects(stack))
136
                    if (potionEffect.potionID == Potion.moveSpeed.id)
137
                        return i
138
        }
139
140
        return -1
141
    }
142
143
    /*  override val tag: String?
144
        get() = healthValue.get().toString()*/
145
146
}

What this file does

The whole module: the gate chain, findPotion's heal/regen/speed scan, the C09-C08-C09 throw ceremony gated on serverRotation.pitch, and the C16-C0E-C0D simulated refill. The brief pins C08 and C09; the refill path additionally emits C0E, C16 and C0D, and the throw rides the C03 look stream via RotationUtils. The mode switch between Normal, Jump and Port only alters the local motion before the C08, never the packet shape.

source RotationUtils.java (throw gate)

RotationUtils.java454 lines · JavaOriginal ↗
1
/*
2
 * LiquidBounce Hacked Client
3
 * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
4
 * https://github.com/CCBlueX/LiquidBounce/
5
 */
6
package net.ccbluex.liquidbounce.utils;
7
8
import net.ccbluex.liquidbounce.LiquidBounce;
9
import net.ccbluex.liquidbounce.event.EventTarget;
10
import net.ccbluex.liquidbounce.event.Listenable;
11
import net.ccbluex.liquidbounce.event.PacketEvent;
12
import net.ccbluex.liquidbounce.event.TickEvent;
13
import net.ccbluex.liquidbounce.features.module.modules.combat.FastBow;
14
import net.minecraft.client.entity.EntityPlayerSP;
15
import net.minecraft.entity.Entity;
16
import net.minecraft.entity.EntityLivingBase;
17
import net.minecraft.network.Packet;
18
import net.minecraft.network.play.client.C03PacketPlayer;
19
import net.minecraft.util.*;
20
import net.minecraftforge.fml.relauncher.Side;
21
import net.minecraftforge.fml.relauncher.SideOnly;
22
import org.jetbrains.annotations.NotNull;
23
import net.minecraft.util.Vec3;
24
25
import java.util.Random;
26
27
@SideOnly(Side.CLIENT)
28
public final class RotationUtils extends MinecraftInstance implements Listenable {
29
30
    private static Random random = new Random();
31
32
    private static int keepLength;
33
34
    public static Rotation targetRotation;
35
    public static Rotation serverRotation;
36
37
    public static boolean keepCurrentRotation = false;
38
39
    private static double x = random.nextDouble();
40
    private static double y = random.nextDouble();
41
    private static double z = random.nextDouble();
42
43
    public static float getRotations(EntityLivingBase ent ,float otPos) {
44
        double x = ent.posX + Math.sin(otPos);
45
        double z = ent.posZ + Math.cos(otPos);
46
        return getRotationFromPosition(x, z);
47
    }
48
49
    public static float getRotationFromPosition(double x, double z) {
50
        double xDiff = x - mc.thePlayer.posX;
51
        double zDiff = z - mc.thePlayer.posZ;
52
53
        float yaw = (float) (Math.atan2(zDiff, xDiff) * 180.0D / 3.141592653589793D) - 90.0F;
54
        return yaw;
55
    }
56
57
58
    public static float[] getRotationFromPosition(double x, double z, double y) {
59
        double xDiff = x - mc.thePlayer.posX;
60
        double zDiff = z - mc.thePlayer.posZ;
61
        double yDiff = y - mc.thePlayer.posY - 1.2;
62
63
        double dist = MathHelper.sqrt_double(xDiff * xDiff + zDiff * zDiff);
64
        float yaw = (float) (Math.atan2(zDiff, xDiff) * 180.0D / 3.141592653589793D) - 90.0F;
65
        float pitch = (float) -(Math.atan2(yDiff, dist) * 180.0D / 3.141592653589793D);
66
        return new float[]{yaw, pitch};
67
    }
68
69
    public static VecRotation faceBlock(final BlockPos blockPos) {
70
        if (blockPos == null)
71
            return null;
72
73
        VecRotation vecRotation = null;
74
75
        for(double xSearch = 0.1D; xSearch < 0.9D; xSearch += 0.1D) {
76
            for(double ySearch = 0.1D; ySearch < 0.9D; ySearch += 0.1D) {
77
                for (double zSearch = 0.1D; zSearch < 0.9D; zSearch += 0.1D) {
78
                    final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
79
                    final Vec3 posVec = new Vec3(blockPos).addVector(xSearch, ySearch, zSearch);
80
                    final double dist = eyesPos.distanceTo(posVec);
81
82
                    final double diffX = posVec.xCoord - eyesPos.xCoord;
83
                    final double diffY = posVec.yCoord - eyesPos.yCoord;
84
                    final double diffZ = posVec.zCoord - eyesPos.zCoord;
85
86
                    final double diffXZ = MathHelper.sqrt_double(diffX * diffX + diffZ * diffZ);
87
88
                    final Rotation rotation = new Rotation(
89
                            MathHelper.wrapAngleTo180_float((float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F),
90
                            MathHelper.wrapAngleTo180_float((float) -Math.toDegrees(Math.atan2(diffY, diffXZ)))
91
                    );
92
93
                    final Vec3 rotationVector = getVectorForRotation(rotation);
94
                    final Vec3 vector = eyesPos.addVector(rotationVector.xCoord * dist, rotationVector.yCoord * dist,
95
                            rotationVector.zCoord * dist);
96
                    final MovingObjectPosition obj = mc.theWorld.rayTraceBlocks(eyesPos, vector, false,
97
                            false, true);
98
99
                    if (obj.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
100
                        final VecRotation currentVec = new VecRotation(posVec, rotation);
101
102
                        if (vecRotation == null || getRotationDifference(currentVec.getRotation()) < getRotationDifference(vecRotation.getRotation()))
103
                            vecRotation = currentVec;
104
                    }
105
                }
106
            }
107
        }
108
109
        return vecRotation;
110
    }
111
112
113
114
    /**
115
     * Face target with bow
116
     *
117
     * @param target your enemy
118
     * @param silent client side rotations
119
     * @param predict predict new enemy position
120
     * @param predictSize predict size of predict
121
     */
122
    public static void faceBow(final Entity target, final boolean silent, final boolean predict, final float predictSize) {
123
        final EntityPlayerSP player = mc.thePlayer;
124
125
        final double posX = target.posX + (predict ? (target.posX - target.prevPosX) * predictSize : 0) - (player.posX + (predict ? (player.posX - player.prevPosX) : 0));
126
        final double posY = target.getEntityBoundingBox().minY + (predict ? (target.getEntityBoundingBox().minY - target.prevPosY) * predictSize : 0) + target.getEyeHeight() - 0.15 - (player.getEntityBoundingBox().minY + (predict ? (player.posY - player.prevPosY) : 0)) - player.getEyeHeight();
127
        final double posZ = target.posZ + (predict ? (target.posZ - target.prevPosZ) * predictSize : 0) - (player.posZ + (predict ? (player.posZ - player.prevPosZ) : 0));
128
        final double posSqrt = Math.sqrt(posX * posX + posZ * posZ);
129
130
        float velocity = LiquidBounce.moduleManager.getModule(FastBow.class).getState() ? 1F : player.getItemInUseDuration() / 20F;
131
        velocity = (velocity * velocity + velocity * 2) / 3;
132
133
        if(velocity > 1) velocity = 1;
134
135
        final Rotation rotation = new Rotation(
136
                (float) (Math.atan2(posZ, posX) * 180 / Math.PI) - 90,
137
                (float) -Math.toDegrees(Math.atan((velocity * velocity - Math.sqrt(velocity * velocity * velocity * velocity - 0.006F * (0.006F * (posSqrt * posSqrt) + 2 * posY * (velocity * velocity)))) / (0.006F * posSqrt)))
138
        );
139
140
        if(silent)
141
            setTargetRotation(rotation);
142
        else
143
            limitAngleChange(new Rotation(player.rotationYaw, player.rotationPitch), rotation,10 +
144
                    new Random().nextInt(6)).toPlayer(mc.thePlayer);
145
    }
146
    /**
147
     * Search good center
148
     *
149
     * @param bb enemy box
150
     * @param outborder outborder option
151
     * @param random random option
152
     * @param predict predict option
153
     * @param throughWalls throughWalls option
154
     * @return center
155
     */
156
    public static VecRotation searchCenter(final AxisAlignedBB bb, final boolean outborder, final boolean random,
157
                                           final boolean predict, final boolean throughWalls, final float distance) {
158
        if(outborder) {
159
            final Vec3 vec3 = new Vec3(bb.minX + (bb.maxX - bb.minX) * (x * 0.3 + 1.0), bb.minY + (bb.maxY - bb.minY) * (y * 0.3 + 1.0), bb.minZ + (bb.maxZ - bb.minZ) * (z * 0.3 + 1.0));
160
            return new VecRotation(vec3, toRotation(vec3, predict));
161
        }
162
163
        final Vec3 randomVec = new Vec3(bb.minX + (bb.maxX - bb.minX) * x * 0.8, bb.minY + (bb.maxY - bb.minY) * y * 0.8, bb.minZ + (bb.maxZ - bb.minZ) * z * 0.8);
164
        final Rotation randomRotation = toRotation(randomVec, predict);
165
166
        final Vec3 eyes = mc.thePlayer.getPositionEyes(1F);
167
168
        VecRotation vecRotation = null;
169
170
        for(double xSearch = 0.15D; xSearch < 0.85D; xSearch += 0.1D) {
171
            for (double ySearch = 0.15D; ySearch < 1D; ySearch += 0.1D) {
172
                for (double zSearch = 0.15D; zSearch < 0.85D; zSearch += 0.1D) {
173
                    final Vec3 vec3 = new Vec3(bb.minX + (bb.maxX - bb.minX) * xSearch,
174
                            bb.minY + (bb.maxY - bb.minY) * ySearch, bb.minZ + (bb.maxZ - bb.minZ) * zSearch);
175
                    final Rotation rotation = toRotation(vec3, predict);
176
                    final double vecDist = eyes.distanceTo(vec3);
177
178
                    if (vecDist > distance)
179
                        continue;
180
181
                    if(throughWalls || isVisible(vec3)) {
182
                        final VecRotation currentVec = new VecRotation(vec3, rotation);
183
184
                        if (vecRotation == null || (random ? getRotationDifference(currentVec.getRotation(), randomRotation) < getRotationDifference(vecRotation.getRotation(), randomRotation) : getRotationDifference(currentVec.getRotation()) < getRotationDifference(vecRotation.getRotation())))
185
                            vecRotation = currentVec;
186
                    }
187
                }
188
            }
189
        }
190
191
        return vecRotation;
192
    }
193
194
    /**
195
     * Translate vec to rotation
196
     *
197
     * @param vec target vec
198
     * @param predict predict new location of your body
199
     * @return rotation
200
     */
201
202
203
    public static Rotation toRotation(final Vec3 vec, final boolean predict) {
204
        final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY +
205
                mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
206
207
        if(predict) eyesPos.addVector(mc.thePlayer.motionX, mc.thePlayer.motionY, mc.thePlayer.motionZ);
208
209
        final double diffX = vec.xCoord - eyesPos.xCoord;
210
        final double diffY = vec.yCoord - eyesPos.yCoord;
211
        final double diffZ = vec.zCoord - eyesPos.zCoord;
212
213
        return new Rotation(MathHelper.wrapAngleTo180_float(
214
                (float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F
215
        ), MathHelper.wrapAngleTo180_float(
216
                (float) (-Math.toDegrees(Math.atan2(diffY, Math.sqrt(diffX * diffX + diffZ * diffZ))))
217
        ));
218
    }
219
220
    /*
221
    sb
222
     */
223
224
225
    public static Rotation OtherRotation(final AxisAlignedBB bb,final Vec3 vec, final boolean predict,final boolean throughWalls, final float distance) {
226
        final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY +
227
                mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
228
        final Vec3 eyes = mc.thePlayer.getPositionEyes(1F);
229
        VecRotation vecRotation = null;
230
        for(double xSearch = 0.15D; xSearch < 0.85D; xSearch += 0.1D) {
231
            for (double ySearch = 0.15D; ySearch < 1D; ySearch += 0.1D) {
232
                for (double zSearch = 0.15D; zSearch < 0.85D; zSearch += 0.1D) {
233
                    final Vec3 vec3 = new Vec3(bb.minX + (bb.maxX - bb.minX) * xSearch,
234
                            bb.minY + (bb.maxY - bb.minY) * ySearch, bb.minZ + (bb.maxZ - bb.minZ) * zSearch);
235
                    final Rotation rotation = toRotation(vec3, predict);
236
                    final double vecDist = eyes.distanceTo(vec3);
237
238
                    if (vecDist > distance)
239
                        continue;
240
241
                    if(throughWalls || isVisible(vec3)) {
242
                        final VecRotation currentVec = new VecRotation(vec3, rotation);
243
244
                        if (vecRotation == null)
245
                            vecRotation = currentVec;
246
                    }
247
                }
248
            }
249
        }
250
251
        if(predict) eyesPos.addVector(mc.thePlayer.motionX, mc.thePlayer.motionY, mc.thePlayer.motionZ);
252
253
        final double diffX = vec.xCoord - eyesPos.xCoord;
254
        final double diffY = vec.yCoord - eyesPos.yCoord;
255
        final double diffZ = vec.zCoord - eyesPos.zCoord;
256
257
        return new Rotation(MathHelper.wrapAngleTo180_float(
258
                (float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F
259
        ), MathHelper.wrapAngleTo180_float(
260
                (float) (-Math.toDegrees(Math.atan2(diffY, Math.sqrt(diffX * diffX + diffZ * diffZ))))
261
        ));
262
263
264
    }
265
266
    /**
267
     * Get the center of a box
268
     *
269
     * @param bb your box
270
     * @return center of box
271
     */
272
    public static Vec3 getCenter(final AxisAlignedBB bb) {
273
        return new Vec3(bb.minX + (bb.maxX - bb.minX) * 0.5, bb.minY + (bb.maxY - bb.minY) * 0.5, bb.minZ + (bb.maxZ - bb.minZ) * 0.5);
274
    }
275
276
277
    /**
278
     * Calculate difference between the client rotation and your entity
279
     *
280
     * @param entity your entity
281
     * @return difference between rotation
282
     */
283
    public static double getRotationDifference(final Entity entity) {
284
        final Rotation rotation = toRotation(getCenter(entity.getEntityBoundingBox()), true);
285
286
        return getRotationDifference(rotation, new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch));
287
    }
288
289
    /**
290
     * Calculate difference between the server rotation and your rotation
291
     *
292
     * @param rotation your rotation
293
     * @return difference between rotation
294
     */
295
    public static double getRotationDifference(final Rotation rotation) {
296
        return serverRotation == null ? 0D : getRotationDifference(rotation, serverRotation);
297
    }
298
299
    /**
300
     * Calculate difference between two rotations
301
     *
302
     * @param a rotation
303
     * @param b rotation
304
     * @return difference between rotation
305
     */
306
    public static double getRotationDifference(final Rotation a, final Rotation b) {
307
        return Math.hypot(getAngleDifference(a.getYaw(), b.getYaw()), a.getPitch() - b.getPitch());
308
    }
309
310
    /**
311
     * Limit your rotation using a turn speed
312
     *
313
     * @param currentRotation your current rotation
314
     * @param targetRotation your goal rotation
315
     * @param turnSpeed your turn speed
316
     * @return limited rotation
317
     */
318
    @NotNull
319
    public static Rotation limitAngleChange(final Rotation currentRotation, final Rotation targetRotation, final float turnSpeed) {
320
        final float yawDifference = getAngleDifference(targetRotation.getYaw(), currentRotation.getYaw());
321
        final float pitchDifference = getAngleDifference(targetRotation.getPitch(), currentRotation.getPitch());
322
323
        return new Rotation(
324
                currentRotation.getYaw() + (yawDifference > turnSpeed ? turnSpeed : Math.max(yawDifference, -turnSpeed)),
325
                currentRotation.getPitch() + (pitchDifference > turnSpeed ? turnSpeed : Math.max(pitchDifference, -turnSpeed)
326
        ));
327
    }
328
329
    /**
330
     * Calculate difference between two angle points
331
     *
332
     * @param a angle point
333
     * @param b angle point
334
     * @return difference between angle points
335
     */
336
    private static float getAngleDifference(final float a, final float b) {
337
        return ((((a - b) % 360F) + 540F) % 360F) - 180F;
338
    }
339
340
    /**
341
     * Calculate rotation to vector
342
     *
343
     * @param rotation your rotation
344
     * @return target vector
345
     */
346
    public static Vec3 getVectorForRotation(final Rotation rotation) {
347
        float yawCos = MathHelper.cos(-rotation.getYaw() * 0.017453292F - (float) Math.PI);
348
        float yawSin = MathHelper.sin(-rotation.getYaw() * 0.017453292F - (float) Math.PI);
349
        float pitchCos = -MathHelper.cos(-rotation.getPitch() * 0.017453292F);
350
        float pitchSin = MathHelper.sin(-rotation.getPitch() * 0.017453292F);
351
        return new Vec3(yawSin * pitchCos, pitchSin, yawCos * pitchCos);
352
    }
353
354
    /**
355
     * Allows you to check if your crosshair is over your target entity
356
     *
357
     * @param targetEntity your target entity
358
     * @param blockReachDistance your reach
359
     * @return if crosshair is over target
360
     */
361
    public static boolean isFaced(final Entity targetEntity, double blockReachDistance) {
362
        return RaycastUtils.raycastEntity(blockReachDistance, entity -> entity == targetEntity) != null;
363
    }
364
365
    /**
366
     * Allows you to check if your enemy is behind a wall
367
     */
368
    public static boolean isVisible(final Vec3 vec3) {
369
        final Vec3 eyesPos = new Vec3(mc.thePlayer.posX, mc.thePlayer.getEntityBoundingBox().minY + mc.thePlayer.getEyeHeight(), mc.thePlayer.posZ);
370
371
        return mc.theWorld.rayTraceBlocks(eyesPos, vec3) == null;
372
    }
373
374
    /**
375
     * Handle minecraft tick
376
     *
377
     * @param event Tick event
378
     */
379
    @EventTarget
380
    public void onTick(final TickEvent event) {
381
        if(targetRotation != null) {
382
            keepLength--;
383
384
            if (keepLength <= 0)
385
                reset();
386
        }
387
388
        if(random.nextGaussian() > 0.8D) x = Math.random();
389
        if(random.nextGaussian() > 0.8D) y = Math.random();
390
        if(random.nextGaussian() > 0.8D) z = Math.random();
391
    }
392
393
    /**
394
     * Handle packet
395
     *
396
     * @param event Packet Event
397
     */
398
    @EventTarget
399
    public void onPacket(final PacketEvent event) {
400
        final Packet<?> packet = event.getPacket();
401
402
        if(packet instanceof C03PacketPlayer) {
403
            final C03PacketPlayer packetPlayer = (C03PacketPlayer) packet;
404
405
            if(targetRotation != null && !keepCurrentRotation && (targetRotation.getYaw() != serverRotation.getYaw() || targetRotation.getPitch() != serverRotation.getPitch())) {
406
                packetPlayer.yaw = targetRotation.getYaw();
407
                packetPlayer.pitch = targetRotation.getPitch();
408
                packetPlayer.rotating = true;
409
            }
410
411
            if(packetPlayer.rotating) serverRotation = new Rotation(packetPlayer.yaw, packetPlayer.pitch);
412
        }
413
    }
414
415
    /**
416
     * Set your target rotation
417
     *
418
     * @param rotation your target rotation
419
     */
420
    public static void setTargetRotation(final Rotation rotation) {
421
        setTargetRotation(rotation, 0);
422
    }
423
424
    /**
425
     * Set your target rotation
426
     *
427
     * @param rotation your target rotation
428
     */
429
    public static void setTargetRotation(final Rotation rotation, final int keepLength) {
430
        if(Double.isNaN(rotation.getYaw()) || Double.isNaN(rotation.getPitch())
431
                || rotation.getPitch() > 90 || rotation.getPitch() < -90)
432
            return;
433
434
        rotation.fixedSensitivity(mc.gameSettings.mouseSensitivity);
435
        targetRotation = rotation;
436
        RotationUtils.keepLength = keepLength;
437
    }
438
439
    /**
440
     * Reset your target rotation
441
     */
442
    public static void reset() {
443
        keepLength = 0;
444
        targetRotation = null;
445
    }
446
447
    /**
448
     * @return YESSSS!!!
449
     */
450
    @Override
451
    public boolean handleEvents() {
452
        return true;
453
    }
454
}

What this file does

setTargetRotation stores the throw aim and the rotation system eases the server-side look toward it; serverRotation is updated only when a rotating C03/C06 is actually sent (line 411), and the module's pitch >= 80 test reads exactly that field. This is what turns a local aim into a wire-visible look change before the C08 leaves, and it is the same RotationUtils that Aura uses, which is why the module refuses to throw while Aura holds a target.

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 ItemSwitchSpeed (same-tick switch after use)

ItemSwitchSpeed.java80 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
package me.islandscout.hawk.check.interaction.item;
19
20
import me.islandscout.hawk.HawkPlayer;
21
import me.islandscout.hawk.check.Cancelless;
22
import me.islandscout.hawk.check.CustomCheck;
23
import me.islandscout.hawk.event.Event;
24
import me.islandscout.hawk.event.InteractItemEvent;
25
import me.islandscout.hawk.event.InteractWorldEvent;
26
import me.islandscout.hawk.event.ItemSwitchEvent;
27
import org.bukkit.entity.Player;
28
29
import java.util.*;
30
31
public class ItemSwitchSpeed extends CustomCheck implements Cancelless {
32
33
    private Map<UUID, Long> lastSwitchTicks;
34
    private Set<UUID> usedSomething;
35
    private int MIN_SWITCH_TICKS;
36
37
    //might rename this to "AutoUse"
38
    public ItemSwitchSpeed() {
39
        super("itemswitchspeed", true, -1, 1, 0.999, 5000, "%player% failed item switch speed, VL: %vl%", null);
40
        lastSwitchTicks = new HashMap<>();
41
        usedSomething = new HashSet<>();
42
        MIN_SWITCH_TICKS = (int)customSetting("minSwitchTicks", "", 1);
43
    }
44
45
    //For future reference, if you try to verify that the item-switch packet points to a different slot, beware of falses.
46
    //The client can send item-switch packets regardless if the slot switched or not.
47
48
    @Override
49
    protected void check(Event event) {
50
        if(event instanceof InteractItemEvent || event instanceof InteractWorldEvent) {
51
            usedSomething.add(event.getPlayer().getUniqueId());
52
        }
53
        else if(event instanceof ItemSwitchEvent) {
54
55
            HawkPlayer pp = event.getHawkPlayer();
56
            UUID uuid = pp.getUuid();
57
58
            if(usedSomething.contains(uuid)) {
59
                long lastSwitchTick = lastSwitchTicks.getOrDefault(uuid, 0L);
60
                if(pp.getCurrentTick() - lastSwitchTick < MIN_SWITCH_TICKS) {
61
                    punish(pp, 1, false, event);
62
                }
63
                else {
64
                    reward(pp);
65
                }
66
67
                usedSomething.remove(uuid);
68
            }
69
70
            lastSwitchTicks.put(pp.getUuid(), pp.getCurrentTick());
71
        }
72
    }
73
74
    @Override
75
    public void removeData(Player p) {
76
        UUID uuid = p.getUniqueId();
77
        lastSwitchTicks.remove(uuid);
78
        usedSomething.remove(uuid);
79
    }
80
}

How it counteracts this module

The direct counter to the ceremony: an InteractItemEvent from the C08 use adds the player to usedSomething, and the restore C09 arrives as an ItemSwitchEvent with currentTick - lastSwitchTick equal to 0, under the default minSwitchTicks of 1, so every throw cycle punishes. The module has no margin here: potion switch, use and restore all queue in one PRE motion tick, so raising the setting only widens the net. The check is cancelless, so the punish is pure VL accumulation.

anticheat UseItemAdapter (face-255 use classification)

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

The adapter classifies the throw: handleBlockPlacePacket treats any pre-1.9 face index above 5, and the single-argument C08 serializes face 255, so data.mightUseItem is set. Every C09, both the potion-in and the restore, hits onChangeSlot and calls requestItemUseResync, forcibly releasing the server-side item use each cycle. The honest gap: splash potions skip setItemInUse at the pre-1.9 durability guard (> 16384), so the consume half never registers and the pressure is the resync churn rather than a completion ledger.

anticheat FastConsume (splash completion gap)

FastConsume.java117 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.inventory;
16
17
import org.bukkit.Material;
18
import org.bukkit.entity.Player;
19
import org.bukkit.inventory.ItemStack;
20
21
import fr.neatmonster.nocheatplus.actions.ParameterName;
22
import fr.neatmonster.nocheatplus.checks.Check;
23
import fr.neatmonster.nocheatplus.checks.CheckType;
24
import fr.neatmonster.nocheatplus.checks.ViolationData;
25
import fr.neatmonster.nocheatplus.players.IPlayerData;
26
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
27
import fr.neatmonster.nocheatplus.utilities.TickTask;
28
29
/**
30
 * Replaces the former InstantEat check (pre 1.5). Will be disabled from 1.8 and higher versions.<br>
31
 * @author asofold
32
 *
33
 */
34
public class FastConsume extends Check {
35
36
    public FastConsume() {
37
        super(CheckType.INVENTORY_FASTCONSUME);
38
    }
39
    
40
    /**
41
     * Checks a player
42
     * 
43
     * @param player
44
     * @param stack
45
     * @param time
46
     * @param data
47
     * @param pData
48
     * @return True, if to cancel the event. In that case, the inventory will be updated as well.
49
     */
50
    public boolean check(final Player player, final ItemStack stack, final long time, final InventoryData data, final IPlayerData pData) {
51
        // Consistency checks...
52
        if (stack == null) { // || stack.getType() != data.fastConsumeFood){
53
            // TODO: Strict version should prevent other material (?).
54
            return false;
55
        }
56
        final long ref = data.fastConsumeInteract == 0 ? 0 : Math.max(data.fastConsumeInteract, data.lastClickTime);
57
        if (time < ref) {
58
            // Time ran backwards.
59
            data.fastConsumeInteract = data.lastClickTime = time;
60
            return false;
61
        }
62
        // Check exceptions.
63
        final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
64
        final Material mat = stack == null ? null : stack.getType();
65
        if (mat != null) {
66
            if (cc.fastConsumeWhitelist) {
67
                if (!cc.fastConsumeItems.contains(mat)) {
68
                    return false;
69
                }
70
            }
71
            else if (cc.fastConsumeItems.contains(mat)) {
72
                return false;
73
            }
74
        }
75
        // Actually check.
76
        final long timeSpent = ref == 0 ? 0 : (time - ref); // Not interact = instant.
77
        final long expectedDuration = cc.fastConsumeDuration;
78
        boolean cancel = false;
79
        if (timeSpent < expectedDuration) {
80
            // TODO: Might have to do a specialized check for lag spikes here instead.
81
            final float lag = TickTask.getLag(expectedDuration, true);
82
            if (timeSpent * lag < expectedDuration) {
83
                final double difference = (expectedDuration - timeSpent * lag) / 100.0;
84
                data.fastConsumeVL += difference;
85
                final ViolationData vd = new ViolationData(this, player, data.fastConsumeVL, difference, cc.fastConsumeActions);
86
                vd.setParameter(ParameterName.FOOD, "" + mat);
87
                if (data.fastConsumeFood != mat) {
88
                    vd.setParameter(ParameterName.TAGS, "inconsistent(" + data.fastConsumeFood + ")");
89
                }
90
                else {
91
                    vd.setParameter(ParameterName.TAGS, "");
92
                }
93
                if (executeActions(vd).willCancel()){
94
                    cancel = true;
95
                }
96
            }
97
        }
98
        else {
99
            data.fastConsumeVL *= 0.6; 
100
        }
101
        // Reset interaction.
102
        if (cancel) {
103
            // Fake interaction to prevent violation loops with false positives.
104
            final ItemStack actualStack = InventoryUtil.getFirstConsumableItemInHand(player);
105
            data.fastConsumeFood = actualStack == null ? null : actualStack.getType();
106
            // TODO: Allows some abuse: 1. try instantly eat (cancelled) 2. consume item directly when needed.
107
        }
108
        else  {
109
            if (pData.isDebugActive(type)) {
110
                debug(player, "PlayerItemConsumeEvent, reset fastconsume: " + data.fastConsumeFood);
111
            }
112
            data.fastConsumeFood = null;
113
        }
114
        data.fastConsumeInteract = time;
115
        return cancel;
116
    }
117
}

How it counteracts this module

NCP stamps the consume start on a consumable right-click and completes it on PlayerItemConsumeEvent, which a splash throw never fires, so only the start half of the ledger engages. The restore C09 resets the ledger through onItemHeldChange on every cycle, so the module churns the stamp without ever violating the interval. This entry is an honest boundary: FastConsume cannot see the throw complete, and the module's real exposure stays in the C0E refill and movement layers.

anticheat PacketListener (soup-gated inventory feed)

PacketListener.java215 lines · Java
1
package me.vrekt.arc.listener.packet;
2
3
import com.comphenix.packetwrapper.WrapperPlayClientBlockPlace;
4
import com.comphenix.packetwrapper.WrapperPlayClientFlying;
5
import com.comphenix.packetwrapper.WrapperPlayClientHeldItemSlot;
6
import com.comphenix.packetwrapper.WrapperPlayClientPosition;
7
import com.comphenix.packetwrapper.WrapperPlayClientPositionLook;
8
import com.comphenix.packetwrapper.WrapperPlayClientUseEntity;
9
import com.comphenix.protocol.PacketType;
10
import com.comphenix.protocol.ProtocolLibrary;
11
import com.comphenix.protocol.ProtocolManager;
12
import com.comphenix.protocol.events.ListenerPriority;
13
import com.comphenix.protocol.events.PacketAdapter;
14
import com.comphenix.protocol.events.PacketEvent;
15
import com.comphenix.protocol.wrappers.EnumWrappers;
16
import me.vrekt.arc.Arc;
17
import me.vrekt.arc.check.CheckType;
18
import me.vrekt.arc.check.combat.KillAura;
19
import me.vrekt.arc.check.inventory.AutoHeal;
20
import me.vrekt.arc.check.moving.MorePackets;
21
import me.vrekt.arc.data.combat.FightData;
22
import me.vrekt.arc.data.inventory.InventoryData;
23
import me.vrekt.arc.data.moving.MovingData;
24
import me.vrekt.arc.listener.ACheckListener;
25
import org.bukkit.Material;
26
import org.bukkit.entity.Player;
27
import org.bukkit.inventory.ItemStack;
28
import org.bukkit.plugin.Plugin;
29
30
public class PacketListener implements ACheckListener {
31
    private final MorePackets MORE_PACKETS = (MorePackets) Arc.getCheckManager().getCheck(CheckType.MOREPACKETS);
32
    private final KillAura KILL_AURA = (KillAura) Arc.getCheckManager().getCheck(CheckType.KILLAURA);
33
    private final AutoHeal AUTO_HEAL = (AutoHeal) CHECK_MANAGER.getCheck(CheckType.AUTOHEAL);
34
35
    private boolean listening = false;
36
37
    /**
38
     * Stop listening.
39
     */
40
    public void stopListening() {
41
        ProtocolLibrary.getProtocolManager().removePacketListeners(Arc.getPlugin());
42
    }
43
44
    public void startListening(Plugin plugin, ProtocolManager manager) {
45
        listening = true;
46
47
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.FLYING) {
48
            @Override
49
            public void onPacketReceiving(PacketEvent event) {
50
                Player player = event.getPlayer();
51
                MovingData data = MovingData.getData(player);
52
53
                if (data.cancelMovingPackets()) {
54
                    event.setCancelled(true);
55
                }
56
57
                // Update ground info.
58
                WrapperPlayClientFlying flying = new WrapperPlayClientFlying(event.getPacket());
59
                data.setFlyingClientOnGround(flying.getOnGround());
60
61
                // Update packet info.
62
                data.setFlyingPackets(data.getFlyingPackets() + 1);
63
                boolean cancel = updateAndCheck(player, data);
64
                if (cancel) {
65
                    event.setCancelled(true);
66
                }
67
68
            }
69
        });
70
71
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.POSITION,
72
                PacketType.Play.Client.POSITION_LOOK) {
73
            @Override
74
            public void onPacketReceiving(PacketEvent event) {
75
                Player player = event.getPlayer();
76
                MovingData data = MovingData.getData(player);
77
78
                if (data.cancelMovingPackets()) {
79
                    event.setCancelled(true);
80
                }
81
82
                // Update ground info.
83
                if (event.getPacket().getType().equals(PacketType.Play.Client.POSITION)) {
84
                    WrapperPlayClientPosition position = new WrapperPlayClientPosition(event.getPacket());
85
                    data.setPositionClientOnGround(position.getOnGround());
86
                } else {
87
                    WrapperPlayClientPositionLook position = new WrapperPlayClientPositionLook(event.getPacket());
88
                    data.setPositionClientOnGround(position.getOnGround());
89
                }
90
91
                // Update packet info.
92
                data.setPositionPackets(data.getPositionPackets() + 1);
93
                boolean cancel = updateAndCheck(player, data);
94
                if (cancel) {
95
                    event.setCancelled(true);
96
                }
97
            }
98
        });
99
100
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Client.USE_ENTITY) {
101
            @Override
102
            public void onPacketReceiving(PacketEvent event) {
103
                Player player = event.getPlayer();
104
                FightData data = FightData.getData(player);
105
                data.setTotalAttacks(data.getTotalAttacks() + 1);
106
107
            }
108
        });
109
110
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.ARM_ANIMATION) {
111
            @Override
112
            public void onPacketReceiving(PacketEvent event) {
113
                Player player = event.getPlayer();
114
                FightData data = FightData.getData(player);
115
                data.setLastArmSwing(System.currentTimeMillis());
116
            }
117
        });
118
119
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.HELD_ITEM_SLOT) {
120
            @Override
121
            public void onPacketReceiving(PacketEvent event) {
122
                Player player = event.getPlayer();
123
                InventoryData data = InventoryData.getData(player);
124
                WrapperPlayClientHeldItemSlot itemSlotChange = new WrapperPlayClientHeldItemSlot(event.getPacket());
125
                int slot = itemSlotChange.getSlot();
126
                ItemStack item = player.getInventory().getItem(slot);
127
                if (item != null && item.getType() == Material.MUSHROOM_SOUP) {
128
                    data.setLastItemSwitch(System.currentTimeMillis());
129
                }
130
131
            }
132
        });
133
134
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.BLOCK_PLACE) {
135
            @Override
136
            public void onPacketReceiving(PacketEvent event) {
137
                Player player = event.getPlayer();
138
                InventoryData data = InventoryData.getData(player);
139
                WrapperPlayClientBlockPlace blockPlace = new WrapperPlayClientBlockPlace(event.getPacket());
140
                ItemStack item = blockPlace.getHeldItem();
141
142
                if (item != null && item.getType() == Material.MUSHROOM_SOUP) {
143
                    AUTO_HEAL.check(data, player);
144
                }
145
            }
146
        });
147
148
        manager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.USE_ENTITY) {
149
            @Override
150
            public void onPacketReceiving(PacketEvent event) {
151
                Player player = event.getPlayer();
152
                FightData data = FightData.getData(player);
153
                WrapperPlayClientUseEntity useEntity = new WrapperPlayClientUseEntity(event.getPacket());
154
                if (useEntity.getType() == EnumWrappers.EntityUseAction.ATTACK) {
155
                    // we attacked, lets update our data and check.
156
                    data.setAttackPackets(data.getAttackPackets() + 1);
157
                    boolean canCheckKillAura = Arc.getCheckManager().canCheckPlayer(player, CheckType.KILLAURA);
158
                    if (canCheckKillAura) {
159
                        boolean failed = KILL_AURA.checkFrequency(data, player);
160
                        if (failed) {
161
                            event.setCancelled(true);
162
                        }
163
                    }
164
                }
165
            }
166
        });
167
168
    }
169
170
    /**
171
     * Checks MorePackets and updates/resets data.
172
     *
173
     * @param player the player
174
     * @param data   the MovingData
175
     * @return true if we should cancel.
176
     */
177
    private boolean updateAndCheck(Player player, MovingData data) {
178
        if (data.getLastPacketUpdate() == 0) {
179
            data.setLastPacketUpdate(System.currentTimeMillis());
180
            return false;
181
        }
182
183
        boolean canCheckMorePackets = Arc.getCheckManager().canCheckPlayer(player, CheckType.MOREPACKETS);
184
185
        // if we cant check reset data and return.
186
        if (!canCheckMorePackets) {
187
            data.setLastPacketUpdate(System.currentTimeMillis());
188
            data.setPositionPackets(0);
189
            data.setFlyingPackets(0);
190
191
            data.setCancelMovingPackets(false);
192
            return false;
193
        }
194
195
        long timeElapsed = System.currentTimeMillis() - data.getLastPacketUpdate();
196
        if (timeElapsed >= 1000) {
197
            data.setCancelMovingPackets(false);
198
            // its been a second lets check.
199
            boolean check = MORE_PACKETS.check(player, data);
200
201
            data.setPositionPackets(0);
202
            data.setFlyingPackets(0);
203
            data.setLastPacketUpdate(System.currentTimeMillis());
204
            return check;
205
        }
206
        return false;
207
    }
208
209
    /**
210
     * @return if we are listening for packets.
211
     */
212
    public boolean isListening() {
213
        return listening;
214
    }
215
}

How it counteracts this module

Arc v2's HELD_ITEM_SLOT and BLOCK_PLACE handlers are both gated on Material.MUSHROOM_SOUP, so the potion C09 and the face-255 C08 bypass the AutoHeal inventory feed entirely; the InventoryListener stamps consumeTime for POTION right-clicks, but FastConsume compares it on PlayerItemConsumeEvent, which splash throws never produce. The potion throw is invisible to Arc v2's inventory layer by construction, and its movement layer is where any real pressure would have to come from.

← Back to Analysis Hub