Nekoware v1 private Velocity module 2 files, 521 lines

Nekoware v1 private Velocity: Full Source Analysis

Nekoware v1's private-client Velocity is the mode-gated sibling of Memeware's bare cancel module, sharing the same event API (me.hippo.api.lwjeb @Handler, the identical Event.cancel()/isCancelled()…

me/nekoWare/client/module/combat/Velocity.java · GitHub source ↗

Published 2026-08-12 · Updated 2026-08-12

Analysis

Overview

Nekoware v1's private-client Velocity is the mode-gated sibling of Memeware's bare cancel module, sharing the same event API (me.hippo.api.lwjeb @Handler, the identical Event.cancel()/isCancelled() base class, and the same patched NetworkManager receive path). The constructor registers a single mode string, 'Packet', via addModes, and the entire @Handler Consumer body sits inside an isMode("Packet") gate: when the mode is selected the handler cancels S27PacketExplosion unconditionally and cancels S12PacketEntityVelocity when the entity id matches the player; when the mode is not selected the module is fully inert even while enabled. Both cancels are complete - no scaling, no modification, no state beyond the mode check.

The behavioral difference from Memeware is the gate: Memeware eats explosions and knockback the moment the module is enabled, Nekoware only while the Packet mode is active, so a user can carry the module enabled with interception switched off.

Architecture

The module's constructor calls this.addModes("Packet") to create the mode list, and the handler field is declared exactly like Memeware's: a Consumer<PacketInEvent> annotated with @Handler, invoked by the LWJEB bus for every incoming packet. The entire body - the mc.thePlayer null guard, the S27 cancel, the S12 entity comparison and cancel - is nested inside if (this.isMode("Packet")). The canceled flag is honored by the patched NetworkManager.channelRead0, which fires PacketInEvent before processPacket and drops the packet when isCancelled() is true.

The gate is the entire state machine. There are no counters, no stored vectors, no per-mode behaviors other than on/off; isMode("Packet") is the only branch in the handler. The shared lineage with Memeware is visible in the identical event classes and network patch - the two clients differ only in the gate and the package names.

Cancellation surface

Inside the mode gate the surface is identical to Memeware's: S27PacketExplosion is cancelled unconditionally (no entity check - explosions carry no entity id), and S12PacketEntityVelocity is cancelled when func_149412_c() equals the player's entity id. Both are full cancels dropped before the vanilla handler.

Outside the gate nothing happens: with the module enabled and the mode deselected, the handler returns on the first isMode check, so both S12 and S27 reach processPacket untouched. That conditional behavior is the only real difference from Memeware's always-on cancel - and it is the detail the countering checks below key on, since the mode-off state produces no interception signal at all.

source Velocity.java (module)

Velocity.java45 lines · JavaOriginal ↗
1
2
package me.nekoWare.client.module.combat;
3
4
import me.hippo.api.lwjeb.annotation.Handler;
5
import me.nekoWare.client.event.events.PacketInEvent;
6
import me.nekoWare.client.module.Module;
7
import net.minecraft.network.play.server.S12PacketEntityVelocity;
8
import net.minecraft.network.play.server.S27PacketExplosion;
9
10
import java.util.function.Consumer;
11
12
public class Velocity extends Module {
13
    public Velocity(final String name, final int key, final Module.Category category) {
14
        super(name, key, category);
15
        this.addModes("Packet");
16
    }
17
18
    @Override
19
    public void onEnable() {
20
    }
21
22
    @Override
23
    public void onDisable() {
24
    }
25
26
    @Handler
27
    public Consumer<PacketInEvent> update = e -> {
28
    	
29
    	if(this.isMode("Packet")) {
30
        if (mc.thePlayer == null) {
31
            return;
32
        }
33
        if (e.getPacket() instanceof S27PacketExplosion) {
34
            e.cancel();
35
        }
36
        if (e.getPacket() instanceof S12PacketEntityVelocity) {
37
            final S12PacketEntityVelocity packetEntityVelocity = (S12PacketEntityVelocity) e.getPacket();
38
            if (packetEntityVelocity.func_149412_c() != mc.thePlayer.getEntityId()) {
39
                return;
40
            }
41
            e.cancel();
42
        	}
43
        }
44
    };
45
}

What this file does

The module is this single file. The constructor adds the 'Packet' mode; the @Handler Consumer<PacketInEvent> field holds the subscription; the body checks isMode("Packet"), guards on mc.thePlayer, cancels S27 unconditionally, then cancels S12 when the entity id matches. The mode gate wraps even the S27 branch, which is the one structural difference from Memeware's version: in Memeware the S27 cancel is outside any mode check, here it only runs while the mode is selected.

The handler returns early on a non-matching entity id inside the gate, so other entities' velocity packets pass through untouched even in Packet mode. onEnable/onDisable are empty, and no settings or state fields exist beyond the inherited module machinery.

source NetworkManager.java (patched receive path)

NetworkManager.java476 lines · JavaOriginal ↗
1
package net.minecraft.network;
2
3
import com.google.common.collect.Queues;
4
import com.google.common.util.concurrent.ThreadFactoryBuilder;
5
import io.netty.bootstrap.Bootstrap;
6
import io.netty.channel.*;
7
import io.netty.channel.ChannelHandler.Sharable;
8
import io.netty.channel.local.LocalChannel;
9
import io.netty.channel.local.LocalEventLoopGroup;
10
import io.netty.channel.local.LocalServerChannel;
11
import io.netty.channel.nio.NioEventLoopGroup;
12
import io.netty.channel.oio.OioEventLoopGroup;
13
import io.netty.channel.socket.nio.NioSocketChannel;
14
import io.netty.handler.timeout.ReadTimeoutHandler;
15
import io.netty.util.AttributeKey;
16
import io.netty.util.concurrent.GenericFutureListener;
17
import me.nekoWare.client.Nekoware;
18
import me.nekoWare.client.event.EventAPI;
19
import me.nekoWare.client.event.events.PacketInEvent;
20
import me.nekoWare.client.event.events.PostPacketInEvent;
21
import me.nekoWare.proxymanager.ProxyAdapter;
22
import net.minecraft.server.gui.IUpdatePlayerListBox;
23
import net.minecraft.util.*;
24
import org.apache.commons.lang3.ArrayUtils;
25
import org.apache.commons.lang3.Validate;
26
import org.apache.logging.log4j.LogManager;
27
import org.apache.logging.log4j.Logger;
28
import org.apache.logging.log4j.Marker;
29
import org.apache.logging.log4j.MarkerManager;
30
31
import javax.crypto.SecretKey;
32
import java.net.InetAddress;
33
import java.net.Proxy;
34
import java.net.SocketAddress;
35
import java.util.Queue;
36
37
@Sharable
38
public class NetworkManager extends SimpleChannelInboundHandler {
39
    private static final Logger logger = LogManager.getLogger();
40
    public static final Marker logMarkerNetwork = MarkerManager.getMarker("NETWORK");
41
    public static final Marker logMarkerPackets = MarkerManager.getMarker("NETWORK_PACKETS", logMarkerNetwork);
42
    public static final AttributeKey attrKeyConnectionState = AttributeKey.valueOf("protocol");
43
    public static final LazyLoadBase CLIENT_NIO_EVENTLOOP = new LazyLoadBase() {
44
        private static final String __OBFID = "CL_00001241";
45
46
        protected NioEventLoopGroup genericLoad() {
47
            return new NioEventLoopGroup(0,
48
                    (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build());
49
        }
50
51
        protected Object load() {
52
            return this.genericLoad();
53
        }
54
    };
55
    public static final LazyLoadBase CLIENT_LOCAL_EVENTLOOP = new LazyLoadBase() {
56
        private static final String __OBFID = "CL_00001242";
57
58
        protected LocalEventLoopGroup genericLoad() {
59
            return new LocalEventLoopGroup(0,
60
                    (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).build());
61
        }
62
63
        protected Object load() {
64
            return this.genericLoad();
65
        }
66
    };
67
    private final EnumPacketDirection direction;
68
69
    /** The queue for packets that require transmission */ {
70
//		Queues.newPriorityQueue();
71
    }
72
73
    private final Queue outboundPacketsQueue = Queues.newConcurrentLinkedQueue();
74
75
    /**
76
     * The active channel
77
     */
78
    private Channel channel;
79
80
    /**
81
     * The address of the remote party
82
     */
83
    private SocketAddress socketAddress;
84
85
    /**
86
     * The INetHandler instance responsible for processing received packets
87
     */
88
    private INetHandler packetListener;
89
90
    /**
91
     * A String indicating why the network has shutdown.
92
     */
93
    private IChatComponent terminationReason;
94
    private boolean isEncrypted;
95
    private boolean disconnected;
96
    private static final String __OBFID = "CL_00001240";
97
98
    public NetworkManager(EnumPacketDirection packetDirection) {
99
        this.direction = packetDirection;
100
    }
101
102
    public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception {
103
        super.channelActive(p_channelActive_1_);
104
        this.channel = p_channelActive_1_.channel();
105
        this.socketAddress = this.channel.remoteAddress();
106
107
        try {
108
            this.setConnectionState(EnumConnectionState.HANDSHAKING);
109
        } catch (Throwable var3) {
110
            logger.fatal(var3);
111
        }
112
    }
113
114
    /**
115
     * Sets the new connection state and registers which packets this channel may
116
     * send and receive
117
     */
118
    public void setConnectionState(EnumConnectionState newState) {
119
        this.channel.attr(attrKeyConnectionState).set(newState);
120
        this.channel.config().setAutoRead(true);
121
        logger.debug("Enabled auto read");
122
    }
123
124
    public void channelInactive(ChannelHandlerContext p_channelInactive_1_) {
125
        this.closeChannel(new ChatComponentTranslation("disconnect.endOfStream", new Object[0]));
126
    }
127
128
    public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) {
129
        logger.debug("Disconnecting " + this.getRemoteAddress(), p_exceptionCaught_2_);
130
        this.closeChannel(new ChatComponentTranslation("disconnect.genericReason",
131
                new Object[]{"Internal Exception: " + p_exceptionCaught_2_}));
132
    }
133
134
    protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_) {
135
        if (this.channel.isOpen()) {
136
            PacketInEvent n = new PacketInEvent(p_channelRead0_2_);
137
            EventAPI.fire(n);
138
139
            if (n.isCancelled())
140
                return;
141
            try {
142
                n.getPacket().processPacket(this.packetListener);
143
            } catch (ThreadQuickExitException var4) {
144
                ;
145
            }
146
            PostPacketInEvent p = new PostPacketInEvent(p_channelRead0_2_);
147
            EventAPI.fire(p);
148
        }
149
    }
150
151
    /**
152
     * Sets the NetHandler for this NetworkManager, no checks are made if this
153
     * handler is suitable for the particular connection state (protocol)
154
     */
155
    public void setNetHandler(INetHandler handler) {
156
        Validate.notNull(handler, "packetListener", new Object[0]);
157
        logger.debug("Set listener of {} to {}", new Object[]{this, handler});
158
        this.packetListener = handler;
159
    }
160
161
    public void sendPacket(Packet packetIn) {
162
        if (this.channel != null && this.channel.isOpen()) {
163
            this.flushOutboundQueue();
164
            this.dispatchPacket(packetIn, (GenericFutureListener[]) null);
165
        } else {
166
            this.outboundPacketsQueue.add(
167
                    new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[]) null));
168
        }
169
    }
170
171
    public void sendPacket(Packet packetIn, GenericFutureListener listener, GenericFutureListener... listeners) {
172
        if (this.channel != null && this.channel.isOpen()) {
173
            this.flushOutboundQueue();
174
            this.dispatchPacket(packetIn, (GenericFutureListener[]) ArrayUtils.add(listeners, 0, listener));
175
        } else {
176
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn,
177
                    (GenericFutureListener[]) ArrayUtils.add(listeners, 0, listener)));
178
        }
179
    }
180
181
    /**
182
     * Will commit the packet to the channel. If the current thread 'owns' the
183
     * channel it will write and flush the packet, otherwise it will add a task for
184
     * the channel eventloop thread to do that.
185
     */
186
    private void dispatchPacket(final Packet inPacket, final GenericFutureListener[] futureListeners) {
187
        final EnumConnectionState var3 = EnumConnectionState.getFromPacket(inPacket);
188
        final EnumConnectionState var4 = (EnumConnectionState) this.channel.attr(attrKeyConnectionState).get();
189
190
        if (var4 != var3) {
191
            logger.debug("Disabled auto read");
192
            this.channel.config().setAutoRead(false);
193
        }
194
195
        if (this.channel.eventLoop().inEventLoop()) {
196
            if (var3 != var4) {
197
                this.setConnectionState(var3);
198
            }
199
200
            ChannelFuture var5 = this.channel.writeAndFlush(inPacket);
201
202
            if (futureListeners != null) {
203
                var5.addListeners(futureListeners);
204
            }
205
206
            var5.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
207
        } else {
208
            this.channel.eventLoop().execute(new Runnable() {
209
                private static final String __OBFID = "CL_00001243";
210
211
                public void run() {
212
                    if (var3 != var4) {
213
                        NetworkManager.this.setConnectionState(var3);
214
                    }
215
216
                    ChannelFuture var1 = NetworkManager.this.channel.writeAndFlush(inPacket);
217
218
                    if (futureListeners != null) {
219
                        var1.addListeners(futureListeners);
220
                    }
221
222
                    var1.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
223
                }
224
            });
225
        }
226
    }
227
228
    /**
229
     * Will iterate through the outboundPacketQueue and dispatch all Packets
230
     */
231
    private void flushOutboundQueue() {
232
        if (this.channel != null && this.channel.isOpen()) {
233
            while (!this.outboundPacketsQueue.isEmpty()) {
234
                NetworkManager.InboundHandlerTuplePacketListener var1 = (NetworkManager.InboundHandlerTuplePacketListener) this.outboundPacketsQueue
235
                        .poll();
236
                this.dispatchPacket(var1.packet, var1.futureListeners);
237
            }
238
        }
239
    }
240
241
    /**
242
     * Checks timeouts and processes all packets received
243
     */
244
    public void processReceivedPackets() {
245
        this.flushOutboundQueue();
246
247
        if (this.packetListener instanceof IUpdatePlayerListBox) {
248
            ((IUpdatePlayerListBox) this.packetListener).update();
249
        }
250
251
        this.channel.flush();
252
    }
253
254
    /**
255
     * Returns the socket address of the remote side. Server-only.
256
     */
257
    public SocketAddress getRemoteAddress() {
258
        return this.socketAddress;
259
    }
260
261
    /**
262
     * Closes the channel, the parameter can be used for an exit message (not
263
     * certain how it gets sent)
264
     */
265
    public void closeChannel(IChatComponent message) {
266
        if (this.channel.isOpen()) {
267
            this.channel.close().awaitUninterruptibly();
268
            this.terminationReason = message;
269
        }
270
    }
271
272
    /**
273
     * True if this NetworkManager uses a memory connection (single player game).
274
     * False may imply both an active TCP connection or simply no active connection
275
     * at all
276
     */
277
    public boolean isLocalChannel() {
278
        return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel;
279
    }
280
281
    /**
282
     * Prepares a clientside NetworkManager: establishes a connection to the address
283
     * and port supplied and configures the channel pipeline. Returns the newly
284
     * created instance.
285
     */
286
    public static NetworkManager provideLanClient(InetAddress p_150726_0_, int p_150726_1_) {
287
        if (Nekoware.INSTANCE.proxy != Proxy.NO_PROXY) {
288
            final NetworkManager var2 = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
289
            ((Bootstrap) ((Bootstrap) ((Bootstrap) (new Bootstrap())
290
                    .group(new OioEventLoopGroup())).handler(new ChannelInitializer() {
291
                private static final String __OBFID = "CL_00002312";
292
293
                protected void initChannel(Channel p_initChannel_1_) {
294
                    try {
295
                        p_initChannel_1_.config().setOption(ChannelOption.IP_TOS, Integer.valueOf(24));
296
                    } catch (ChannelException var4) {
297
                        ;
298
                    }
299
300
                    try {
301
                        p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(false));
302
                    } catch (ChannelException var3) {
303
                        ;
304
                    }
305
                    p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(20))
306
                            .addLast("splitter", new MessageDeserializer2())
307
                            .addLast("decoder", new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))
308
                            .addLast("prepender", new MessageSerializer2())
309
                            .addLast("encoder", new MessageSerializer(EnumPacketDirection.SERVERBOUND))
310
                            .addLast("packet_handler", var2);
311
                }
312
            })).channelFactory(new ProxyAdapter(Nekoware.INSTANCE.proxy))).connect(p_150726_0_, p_150726_1_).syncUninterruptibly();
313
            return var2;
314
        }
315
        final NetworkManager var2 = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
316
        ((Bootstrap) ((Bootstrap) ((Bootstrap) (new Bootstrap())
317
                .group((EventLoopGroup) CLIENT_NIO_EVENTLOOP.getValue())).handler(new ChannelInitializer() {
318
            private static final String __OBFID = "CL_00002312";
319
320
            protected void initChannel(Channel p_initChannel_1_) {
321
                try {
322
                    p_initChannel_1_.config().setOption(ChannelOption.IP_TOS, Integer.valueOf(24));
323
                } catch (ChannelException var4) {
324
                    ;
325
                }
326
327
                try {
328
                    p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(false));
329
                } catch (ChannelException var3) {
330
                    ;
331
                }
332
                p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(20))
333
                        .addLast("splitter", new MessageDeserializer2())
334
                        .addLast("decoder", new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))
335
                        .addLast("prepender", new MessageSerializer2())
336
                        .addLast("encoder", new MessageSerializer(EnumPacketDirection.SERVERBOUND))
337
                        .addLast("packet_handler", var2);
338
            }
339
        })).channel(NioSocketChannel.class)).connect(p_150726_0_, p_150726_1_).syncUninterruptibly();
340
        return var2;
341
    }
342
343
    public static class PacketHandler extends SimpleChannelInboundHandler {
344
        @Override
345
        public void channelRead0(ChannelHandlerContext ctx, Object msg) {
346
            try {
347
                PacketInEvent n = new PacketInEvent((Packet) msg);
348
                EventAPI.fire(n);
349
350
                if (n.isCancelled())
351
                    return;
352
//    			System.out.println(msg);
353
                super.channelRead(ctx, msg);
354
            } catch (Exception e) {
355
                e.printStackTrace();
356
            }
357
        }
358
    }
359
360
    /**
361
     * Prepares a clientside NetworkManager: establishes a connection to the socket
362
     * supplied and configures the channel pipeline. Returns the newly created
363
     * instance.
364
     */
365
    public static NetworkManager provideLocalClient(SocketAddress p_150722_0_) {
366
        final NetworkManager var1 = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
367
        ((Bootstrap) ((Bootstrap) ((Bootstrap) (new Bootstrap())
368
                .group((EventLoopGroup) CLIENT_LOCAL_EVENTLOOP.getValue())).handler(new ChannelInitializer() {
369
            private static final String __OBFID = "CL_00002311";
370
371
            protected void initChannel(Channel p_initChannel_1_) {
372
                p_initChannel_1_.pipeline().addLast("packet_handler", var1);
373
            }
374
        })).channel(LocalChannel.class)).connect(p_150722_0_).syncUninterruptibly();
375
        return var1;
376
    }
377
378
    /**
379
     * Adds an encoder+decoder to the channel pipeline. The parameter is the secret
380
     * key used for encrypted communication
381
     */
382
    public void enableEncryption(SecretKey key) {
383
        this.isEncrypted = true;
384
        this.channel.pipeline().addBefore("splitter", "decrypt",
385
                new NettyEncryptingDecoder(CryptManager.func_151229_a(2, key)));
386
        this.channel.pipeline().addBefore("prepender", "encrypt",
387
                new NettyEncryptingEncoder(CryptManager.func_151229_a(1, key)));
388
    }
389
390
    public boolean func_179292_f() {
391
        return this.isEncrypted;
392
    }
393
394
    /**
395
     * Returns true if this NetworkManager has an active channel, false otherwise
396
     */
397
    public boolean isChannelOpen() {
398
        return this.channel != null && this.channel.isOpen();
399
    }
400
401
    public boolean hasNoChannel() {
402
        return this.channel == null;
403
    }
404
405
    /**
406
     * Gets the current handler for processing packets
407
     */
408
    public INetHandler getNetHandler() {
409
        return this.packetListener;
410
    }
411
412
    /**
413
     * If this channel is closed, returns the exit message, null otherwise.
414
     */
415
    public IChatComponent getExitMessage() {
416
        return this.terminationReason;
417
    }
418
419
    /**
420
     * Switches the channel to manual reading modus
421
     */
422
    public void disableAutoRead() {
423
        this.channel.config().setAutoRead(false);
424
    }
425
426
    public void setCompressionTreshold(int treshold) {
427
        if (treshold >= 0) {
428
            if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder) {
429
                ((NettyCompressionDecoder) this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold);
430
            } else {
431
                this.channel.pipeline().addBefore("decoder", "decompress", new NettyCompressionDecoder(treshold));
432
            }
433
434
            if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder) {
435
                ((NettyCompressionEncoder) this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold);
436
            } else {
437
                this.channel.pipeline().addBefore("encoder", "compress", new NettyCompressionEncoder(treshold));
438
            }
439
        } else {
440
            if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder) {
441
                this.channel.pipeline().remove("decompress");
442
            }
443
444
            if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder) {
445
                this.channel.pipeline().remove("compress");
446
            }
447
        }
448
    }
449
450
    public void checkDisconnected() {
451
        if (!this.hasNoChannel() && !this.isChannelOpen() && !this.disconnected) {
452
            this.disconnected = true;
453
454
            if (this.getExitMessage() != null) {
455
                this.getNetHandler().onDisconnect(this.getExitMessage());
456
            } else if (this.getNetHandler() != null) {
457
                this.getNetHandler().onDisconnect(new ChatComponentText("Disconnected"));
458
            }
459
        }
460
    }
461
462
    protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Object p_channelRead0_2_) {
463
        this.channelRead0(p_channelRead0_1_, (Packet) p_channelRead0_2_);
464
    }
465
466
    static class InboundHandlerTuplePacketListener {
467
        private final Packet packet;
468
        private final GenericFutureListener[] futureListeners;
469
        private static final String __OBFID = "CL_00001244";
470
471
        public InboundHandlerTuplePacketListener(Packet inPacket, GenericFutureListener... inFutureListeners) {
472
            this.packet = inPacket;
473
            this.futureListeners = inFutureListeners;
474
        }
475
    }
476
}

What this file does

The private client ships the same receive-path patch as Memeware: channelRead0 wraps the incoming packet in a PacketInEvent, fires it on the LWJEB bus, and returns before processPacket when the cancelled flag is set, so a cancelled S12 or S27 never reaches NetHandlerPlayClient. A PostPacketInEvent fires after processing for post-handlers, and the outbound path at line 347 runs the same event for outgoing messages.

This file is the enforcement point for the module's cancel: the handler's e.cancel() only sets a flag, and this patch is what turns that flag into a dropped packet. It is also why the cancellation is invisible to the server's own record - the server already sent the velocity and keeps it in its ledger - which is exactly the asymmetry the prediction-based countering checks exploit.

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 KnockbackHandler (AntiKB, required-velocity prediction)

KnockbackHandler.java262 lines · Java
1
package ac.grim.grimac.checks.impl.velocity;
2
3
import ac.grim.grimac.api.config.ConfigManager;
4
import ac.grim.grimac.api.storage.verbose.Verbose;
5
import ac.grim.grimac.checks.Check;
6
import ac.grim.grimac.checks.CheckData;
7
import ac.grim.grimac.checks.type.PacketSendListener;
8
import ac.grim.grimac.checks.type.PostPredictionListener;
9
import ac.grim.grimac.player.GrimPlayer;
10
import ac.grim.grimac.utils.anticheat.update.PredictionComplete;
11
import ac.grim.grimac.utils.data.Pair;
12
import ac.grim.grimac.utils.data.VectorData;
13
import ac.grim.grimac.utils.data.VelocityData;
14
import ac.grim.grimac.utils.math.Vector3dm;
15
import com.github.retrooper.packetevents.event.PacketSendEvent;
16
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
17
import com.github.retrooper.packetevents.util.Vector3d;
18
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityVelocity;
19
import lombok.Getter;
20
import org.jetbrains.annotations.NotNull;
21
22
import java.util.Deque;
23
import java.util.LinkedList;
24
25
// We are making a velocity sandwich between two pieces of transaction packets (bread)
26
@CheckData(name = "AntiKB", stableKey = "grim.velocity.anti_knockback", alternativeName = "AntiKnockback", configName = "Knockback", description = "Did not take the expected entity knockback", setback = 10, decay = 0.025)
27
public class KnockbackHandler extends Check implements PacketSendListener, PostPredictionListener {
28
    private static final Verbose V = Verbose.of("[ignored knockback|o: {offset}]");
29
30
    private final Deque<VelocityData> firstBreadMap = new LinkedList<>();
31
32
    private final Deque<VelocityData> lastKnockbackKnownTaken = new LinkedList<>();
33
    private VelocityData firstBreadOnlyKnockback = null;
34
    @Getter
35
    private boolean knockbackPointThree = false;
36
37
    private double offsetToFlag;
38
    private double maxAdv, immediate, ceiling, multiplier;
39
40
    private double threshold;
41
42
    public KnockbackHandler(GrimPlayer player) {
43
        super(player);
44
    }
45
46
    @Override
47
    public void onPacketSend(final PacketSendEvent event) {
48
        if (event.getPacketType() == PacketType.Play.Server.ENTITY_VELOCITY) {
49
            WrapperPlayServerEntityVelocity velocity = new WrapperPlayServerEntityVelocity(event);
50
            int entityId = velocity.getEntityId();
51
52
            // Detect whether this knockback packet affects the player or if it is useless
53
            // Mojang sends extra useless knockback packets for no apparent reason
54
            if (player.compensatedEntities.serverPlayerVehicle != null && entityId != player.compensatedEntities.serverPlayerVehicle) {
55
                return;
56
            }
57
            if (player.compensatedEntities.serverPlayerVehicle == null && entityId != player.entityID) {
58
                return;
59
            }
60
61
            // If the player isn't in a vehicle and the ID is for the player, the player will take kb
62
            // If the player is in a vehicle and the ID is for the player's vehicle, the player will take kb
63
            Vector3d playerVelocity = velocity.getVelocity();
64
65
            // Blacklist problemated vector until mojang fixes a client-sided bug
66
            if (playerVelocity.getY() == -0.04) {
67
                velocity.setVelocity(playerVelocity.add(new Vector3d(0, 1 / 8000D, 0)));
68
                playerVelocity = velocity.getVelocity();
69
                event.markForReEncode(true);
70
            }
71
72
            playerVelocity = VectorPrecisionConverter.convert(player.getClientVersion(), playerVelocity);
73
74
            // Wrap velocity between two transactions
75
            player.sendTransaction();
76
            addPlayerKnockback(entityId, player.lastTransactionSent.get(), new Vector3dm(playerVelocity.getX(), playerVelocity.getY(), playerVelocity.getZ()));
77
            event.getTasksAfterSend().add(player::sendTransaction);
78
        }
79
    }
80
81
    @NotNull
82
    public Pair<VelocityData, Vector3dm> getFutureKnockback() {
83
        // Chronologically in the future
84
        if (!firstBreadMap.isEmpty()) {
85
            VelocityData data = firstBreadMap.peek();
86
            return new Pair<>(data, data != null ? data.vector : null);
87
        }
88
89
        // Less in the future
90
        if (!lastKnockbackKnownTaken.isEmpty()) {
91
            VelocityData data = lastKnockbackKnownTaken.peek();
92
            return new Pair<>(data, data != null ? data.vector : null);
93
        }
94
95
        // Uncertain, might be in the future
96
        if (player.firstBreadKB != null && player.likelyKB == null) {
97
            VelocityData data = player.firstBreadKB;
98
            return new Pair<>(data, data.vector.clone());
99
        } else if (player.likelyKB != null) { // Known to be in the present
100
            VelocityData data = player.likelyKB;
101
            return new Pair<>(data, data.vector.clone());
102
        }
103
        return new Pair<>(null, null);
104
    }
105
106
    private void addPlayerKnockback(int entityID, int breadOne, @NotNull Vector3dm knockback) {
107
        firstBreadMap.add(new VelocityData(entityID, breadOne, player.getSetbackTeleportUtil().isSendingSetback, knockback));
108
    }
109
110
    public VelocityData calculateRequiredKB(int entityID, int transaction, boolean isJustTesting) {
111
        tickKnockback(transaction);
112
113
        VelocityData returnLastKB = null;
114
        for (VelocityData data : lastKnockbackKnownTaken) {
115
            if (data.entityID == entityID)
116
                returnLastKB = data;
117
        }
118
119
        if (!isJustTesting) {
120
            lastKnockbackKnownTaken.clear();
121
        }
122
        return returnLastKB;
123
    }
124
125
    private void tickKnockback(int transactionID) {
126
        firstBreadOnlyKnockback = null;
127
        if (firstBreadMap.isEmpty()) return;
128
        VelocityData data = firstBreadMap.peek();
129
        while (data != null) {
130
            if (data.transaction == transactionID) { // First bread knockback
131
                firstBreadOnlyKnockback = new VelocityData(data.entityID, data.transaction, data.isSetback, data.vector);
132
                //firstBreadMap.poll();
133
                break; // All knockback after this will have not been applied
134
            } else if (data.transaction < transactionID) { // This kb has 100% arrived to the player
135
                VelocityData velocityData = new VelocityData(data.entityID, data.transaction, data.isSetback, data.vector);
136
137
                if (firstBreadOnlyKnockback != null) { // Don't require kb twice
138
                    velocityData.offset = data.offset;
139
                }
140
141
                lastKnockbackKnownTaken.add(velocityData);
142
143
                // Knockback has been applied and is now required, remove it from first bread
144
                firstBreadOnlyKnockback = null;
145
                firstBreadMap.poll();
146
                data = firstBreadMap.peek();
147
            } else { // We are too far ahead in the future
148
                break;
149
            }
150
        }
151
    }
152
153
    public void forceExempt() {
154
        // Unsure knockback was taken
155
        if (player.firstBreadKB != null) {
156
            player.firstBreadKB.offset = 0;
157
        }
158
159
        if (player.likelyKB != null) {
160
            player.likelyKB.offset = 0;
161
        }
162
    }
163
164
    public void setPointThree(boolean isPointThree) {
165
        knockbackPointThree = knockbackPointThree || isPointThree;
166
    }
167
168
    public void handlePredictionAnalysis(double offset) {
169
        if (player.firstBreadKB != null) {
170
            player.firstBreadKB.offset = Math.min(player.firstBreadKB.offset, offset);
171
        }
172
173
        if (player.likelyKB != null) {
174
            player.likelyKB.offset = Math.min(player.likelyKB.offset, offset);
175
        }
176
    }
177
178
    @Override
179
    public void onPredictionComplete(final PredictionComplete predictionComplete) {
180
        double offset = predictionComplete.getOffset();
181
        if (!predictionComplete.isChecked() || predictionComplete.getData().isTeleport()) {
182
            forceExempt();
183
            return;
184
        }
185
186
        boolean wasZero = knockbackPointThree;
187
        knockbackPointThree = false;
188
189
        if (player.likelyKB == null && player.firstBreadKB == null) {
190
            return;
191
        }
192
193
        if (player.predictedVelocity.isFirstBreadKb()) {
194
            firstBreadOnlyKnockback = null;
195
            firstBreadMap.poll(); // Remove from map so we don't pull it again
196
        }
197
198
        if (wasZero || player.predictedVelocity.isKnockback()) {
199
            // Unsure knockback was taken
200
            if (player.firstBreadKB != null) {
201
                player.firstBreadKB.offset = Math.min(player.firstBreadKB.offset, offset);
202
            }
203
204
            // 100% known kb was taken
205
            if (player.likelyKB != null) {
206
                player.likelyKB.offset = Math.min(player.likelyKB.offset, offset);
207
            }
208
        }
209
210
        if (player.likelyKB != null) {
211
            if (player.likelyKB.offset > offsetToFlag) {
212
                threshold = Math.min(threshold + player.likelyKB.offset, ceiling);
213
                if (player.likelyKB.isSetback) { // Don't increase violations if this velocity was setback, just teleport and resend them velocity.
214
                    if (!isNoSetbackPermission()) {
215
                        player.getSetbackTeleportUtil().executeViolationSetback();
216
                    }
217
                } else {
218
                    boolean ignored = player.likelyKB.offset == Integer.MAX_VALUE;
219
                    if (flag(V.write(verbose()).bool(ignored).f64(player.likelyKB.offset))) { // This velocity was sent by the server.
220
                        if (player.likelyKB.offset >= immediate || threshold >= maxAdv) {
221
                            setbackIfAboveSetbackVL();
222
                        }
223
                    } else {
224
                        reward();
225
                    }
226
                }
227
            } else if (threshold > 0.05) {
228
                threshold *= multiplier;
229
            }
230
        }
231
    }
232
233
    public boolean shouldIgnoreForPrediction(VectorData data) {
234
        if (data.isKnockback() && data.isFirstBreadKb()) {
235
            return player.firstBreadKB.offset > offsetToFlag;
236
        }
237
        return false;
238
    }
239
240
    public boolean wouldFlag() {
241
        return (player.likelyKB != null && player.likelyKB.offset > offsetToFlag) || (player.firstBreadKB != null && player.firstBreadKB.offset > offsetToFlag);
242
    }
243
244
    public VelocityData calculateFirstBreadKnockback(int entityID, int transaction) {
245
        tickKnockback(transaction);
246
        if (firstBreadOnlyKnockback != null && firstBreadOnlyKnockback.entityID == entityID)
247
            return firstBreadOnlyKnockback;
248
        return null;
249
    }
250
251
    @Override
252
    public void onReload(@NotNull ConfigManager config) {
253
        offsetToFlag = config.getDoubleElse("Knockback.threshold", 0.001);
254
        maxAdv = config.getDoubleElse("Knockback.max-advantage", 1);
255
        immediate = config.getDoubleElse("Knockback.immediate-setback-threshold", 0.1);
256
        multiplier = config.getDoubleElse("Knockback.setback-decay-multiplier", 0.999);
257
        ceiling = config.getDoubleElse("Knockback.max-ceiling", 4);
258
        if (maxAdv < 0) maxAdv = Double.MAX_VALUE;
259
        if (immediate < 0) immediate = Double.MAX_VALUE;
260
    }
261
262
}

How it counteracts this module

Grim's KnockbackHandler makes every ENTITY_VELOCITY a required movement once delivery is proven. It sends a transaction before the velocity and a second after it; the vector enters firstBreadMap keyed by the first transaction id and is promoted into lastKnockbackKnownTaken when the client echoes a larger id. From then the prediction engine demands the vector in the player's motion, measuring the offset against config Knockback.threshold (0.001), accumulating with decay 0.999 into a threshold capped at maxAdvantage 1, and set-backing at an offset of at least 0.1.

While Packet mode is active, the S12 cancel is indistinguishable to Grim from any other anti-knockback: the server sent the vector, the sandwich confirmed it, and the motion never contains it, so the offset accrues and the player is set back. The mode gate does not help - the cancel either happens (and is caught) or does not (and there is no module), so there is no partial state that could slip under the threshold. A knockback recorded during one of Grim's own setbacks is forgiven, but the server's ordinary S12 here is not issued during a setback, so that leniency never applies. Transaction eating remains the theoretical bypass, and this module does not attempt it.

anticheat AntiVelocityBasic (pending knockback matching)

AntiVelocityBasic.java46 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.HawkPlayer;
22
import me.islandscout.hawk.check.MovementCheck;
23
import me.islandscout.hawk.check.Cancelless;
24
import me.islandscout.hawk.event.MoveEvent;
25
26
/**
27
 * The AntiVelocityBasic check verifies that players accept knockback.
28
 * It relies on MoveEvent's knockback acceptance detection.
29
 * The AntiVelocityBasic check has been tested to detect as low as a
30
 * 10% difference in horizontal and/or vertical knockback.
31
 */
32
public class AntiVelocityBasic extends MovementCheck implements Cancelless {
33
34
    public AntiVelocityBasic() {
35
        super("antivelocitybasic", true, -1, 5, 0.999, 5000, "%player% may be using anti-velocity (basic), VL: %vl%", null);
36
    }
37
38
    @Override
39
    protected void check(MoveEvent event) {
40
        HawkPlayer pp = event.getHawkPlayer();
41
        if(event.hasFailedKnockback())
42
            punish(pp, false, event);
43
        else
44
            reward(pp);
45
    }
46
}

How it counteracts this module

Hawk's MoveEvent maintains a per-player pending knockback list and matches every move against it. A kb entry is eligible while the elapsed time is within the player's ping plus 200ms; the move's Y must be within 0.01 of the kb's Y (unless the player collides, jumps, swims or steps) and X and Z must fall inside maxDiscrepancy = weirdConstant * baseMultiplier * sprintMultiplier + 0.003 (weirdConstant 0.098 on ground, 0.2518462 jump-sprinting, 0.0196 swimming; baseMultiplier 5 * walkSpeed * speed-potion factor or 10 * flySpeed; sprintMultiplier 1.3 or 2 flying). An entry that ages past ping + 200ms with no matching move sets failedKnockback and AntiVelocityBasic.check flags at VL 5; detection is documented down to a 10% difference.

In Packet mode the cancelled S12 leaves the entry with no matching move, so it expires and flags - the full cancel has no tolerance path. In the mode-off state the module intercepts nothing and the player takes the knockback normally, so the entry is consumed and the check rewards; that clean on/off split is the one thing that keeps a mode-toggling user under this check between hits. The ping + 200ms window itself is the only forgiveness for a genuine network-stalled move.

anticheat UnusedVelocity (unused knockback ledger)

UnusedVelocity.java87 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.moving.player;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.CheckType;
20
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
21
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
22
import fr.neatmonster.nocheatplus.checks.moving.velocity.SimpleAxisVelocity;
23
import fr.neatmonster.nocheatplus.checks.moving.velocity.UnusedTracker;
24
import fr.neatmonster.nocheatplus.logging.debug.DebugUtil;
25
import fr.neatmonster.nocheatplus.players.IPlayerData;
26
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
27
28
public class UnusedVelocity {
29
    
30
    // TODO: Currently is debug only (!). Only call if some debug flag is set. Needs checks.moving.debug to work at all.
31
32
    /**
33
     * Test if any unused velocity has been tracked and what that means. (Convenience.)
34
     * 
35
     * @param player
36
     * @return If the player has failed the check, whatever that means.
37
     */
38
    public static boolean checkUnusedVelocity(final Player player, 
39
            final CheckType checkType, final IPlayerData pData) {
40
        return checkUnusedVelocity(
41
                player, checkType, 
42
                pData.getGenericInstance(MovingData.class), 
43
                pData.getGenericInstance(MovingConfig.class)
44
                );
45
    }
46
47
48
    /**
49
     * Test if any unused velocity has been tracked and what that means.
50
     * 
51
     * @param player
52
     * @param data
53
     * @param cc
54
     * @return If the player has failed the check, whatever that means.
55
     */
56
    public static boolean checkUnusedVelocity(final Player player, 
57
            final CheckType checkType, final MovingData data, final MovingConfig cc) {
58
        boolean violation = false;
59
        final SimpleAxisVelocity verVel = data.getVerticalVelocityTracker();
60
        violation |= quickCheckDirection(player, verVel.unusedTrackerPos, checkType, "vert/pos", data, cc);
61
        violation |= quickCheckDirection(player, verVel.unusedTrackerNeg, checkType, "vert/neg", data, cc);
62
        return violation;
63
    }
64
65
    /**
66
     * Quick check tracker for one direction.
67
     * @param player
68
     * @param checkType 
69
     * @param unusedTrackerPos
70
     * @param string
71
     * @param data
72
     * @param cc
73
     */
74
    private static boolean quickCheckDirection(final Player player, 
75
            final UnusedTracker tracker, final CheckType checkType, final String trackerId ,
76
            MovingData data, MovingConfig cc) {
77
        final int countV = tracker.getResultViolationCount();
78
        if (countV > 0) {
79
            String msg = "Unused velocity " + trackerId + ": c_v: " + countV + " , a_v: " + tracker.getResultViolationAmount() + " , c_u: " + tracker.getResultUpdateCount();
80
            DebugUtil.debug(CheckUtils.getLogMessagePrefix(player, checkType) + msg);
81
        }
82
        tracker.resetResults(); // Reset for now.
83
        // TODO: A real check, e.g. track frequency and/or average amount of violation per so and so time.
84
        return false; // Player can't possibly fail this yet.
85
    }
86
87
}

How it counteracts this module

NCP's movement model queues the vertical velocity the server applied and consumes it to explain the player's movement afterward. checkUnusedVelocity reads the pos and neg UnusedTracker instances of the SimpleAxisVelocity vertical tracker; UnusedTracker.addValue records a violation amount only when the direction has been blocked since the entry was added - the server pushed velocity in a direction the player never moved - and quickCheckDirection reports the violation count, the accumulated amount and the update count, then resets the results.

In this build the check is a debug ledger: quickCheckDirection logs through DebugUtil and returns false with a TODO for a real frequency or amount check, so it cannot fail a player yet. The mechanism it models is exactly the mode-on state: a cancelled S12 in Packet mode leaves the vertical push un-consumed, so the tracker accumulates unused velocity on every hit. The mode-off state consumes it normally, which keeps the ledger clean. As shipped, the module faces NCP's SurvivalFly envelope rather than this check, and the honest statement is that NCP's velocity accounting is where the detection would land once the TODO is implemented.

anticheat VelocityListener (claimed velocity feed)

VelocityListener.java63 lines · Java
1
package ai.idealistic.spartan.listeners.protocol;
2
3
import ai.idealistic.spartan.Register;
4
import ai.idealistic.spartan.abstraction.event.CPlayerVelocityEvent;
5
import ai.idealistic.spartan.abstraction.protocol.PlayerProtocol;
6
import ai.idealistic.spartan.compatibility.necessary.protocollib.BackPlib;
7
import ai.idealistic.spartan.functionality.concurrent.CheckThread;
8
import ai.idealistic.spartan.functionality.server.Config;
9
import ai.idealistic.spartan.functionality.server.PluginBase;
10
import ai.idealistic.spartan.listeners.bukkit.VelocityEvent;
11
import com.comphenix.protocol.PacketType;
12
import com.comphenix.protocol.events.ListenerPriority;
13
import com.comphenix.protocol.events.PacketAdapter;
14
import com.comphenix.protocol.events.PacketContainer;
15
import com.comphenix.protocol.events.PacketEvent;
16
import org.bukkit.entity.Player;
17
import org.bukkit.util.Vector;
18
19
public class VelocityListener extends PacketAdapter {
20
21
22
    public VelocityListener() {
23
        super(
24
                Register.plugin,
25
                ListenerPriority.MONITOR,
26
                PacketType.Play.Server.ENTITY_VELOCITY
27
        );
28
    }
29
30
    @Override
31
    public void onPacketSending(PacketEvent event) {
32
        Player player = event.getPlayer();
33
        PlayerProtocol protocol = PluginBase.getProtocol(player);
34
35
        if (!Config.settings.getBoolean("Important.bedrock_on_protocollib")
36
                && protocol.isBedrockPlayer()) {
37
            return;
38
        }
39
        PacketContainer packet = event.getPacket();
40
41
        if (!packet.getType().equals(PacketType.Play.Server.ENTITY_VELOCITY)) {
42
            return;
43
        }
44
        if (packet.getIntegers().size() >= 4) {
45
            int id = BackPlib.getSafeInt(packet, 0);
46
47
            if (protocol.getEntityId() == id) {
48
                final double x = ((double) BackPlib.getSafeInt(packet, 1)) / 8000.0D;
49
                final double y = ((double) BackPlib.getSafeInt(packet, 2)) / 8000.0D;
50
                final double z = ((double) BackPlib.getSafeInt(packet, 3)) / 8000.0D;
51
                final boolean isCancelled = event.isCancelled();
52
53
                CheckThread.run(protocol, () -> {
54
                    // Now it's safe to use these variables asynchronously
55
                    CPlayerVelocityEvent velocityEvent = new CPlayerVelocityEvent(player, new Vector(x, y, z));
56
                    velocityEvent.setCancelled(isCancelled);
57
                    VelocityEvent.event(velocityEvent, true);
58
                });
59
            }
60
        }
61
    }
62
63
}

How it counteracts this module

Spartan's VelocityListener is a MONITOR-priority ProtocolLib adapter on ENTITY_VELOCITY that converts the self-entity vector (fixed-point ints / 8000.0) into a CPlayerVelocityEvent, forwards the packet's cancellation state, and dispatches it through VelocityEvent.event onto the CheckThread. The event lands in protocol.claimedVelocity and the claimedVeloGravity/claimedVeloSpeed queues (two entries each), which Spartan's movement checks compare against the player's reported movement - the listener is the feed those checks consume.

The claimed vector is recorded from the server's own send, so the client-side cancel in Packet mode cannot erase it: the queues expect the knockback trajectory and the player reports none, a total deficit that accumulates on every hit while the mode is on. The two-entry queue cap is the tolerance surface - only the last two claims are compared - so a user who drops the mode between hits presents clean windows, which is the one escape the gate offers. With the mode off, no interception occurs and no deficit exists at all.

← Back to Analysis Hub