Tenacity 6.0 Timer module 2 files, 160 lines

Tenacity 6.0 Timer: Full Source Analysis

Timer is a scalar on the vanilla clock. A NumberSetting labeled "Speed:" spans 0.1 to 10 with default 1, and a MotionEvent pre handler writes Timer.timerSpeed on every tick.…

dev/tenacity/module/impl/world/TimerModule.java · GitHub source ↗

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

Analysis

Overview

Timer is a scalar on the vanilla clock. A NumberSetting labeled "Speed:" spans 0.1 to 10 with default 1, and a MotionEvent pre handler writes Timer.timerSpeed on every tick. The write is (float)(int) value, so the fractional part is truncated: the setting behaves as an integer multiplier, and any sub-1 value (0.1 through 0.9) casts to 0.0, which freezes elapsedPartialTicks accumulation and halts the client tick loop instead of slowing it. onEnable writes the raw float once before the handler overwrites it, and onDisable restores 1.0F. A TimerUtil field is declared but never referenced. Timer.updateTimer folds the static timerSpeed into the per-frame tick budget, so the whole packet pipeline scales linearly with the setting.

The clock mechanics

net.minecraft.util.Timer holds a static timerSpeed field (1.0F default) and updateTimer() accumulates elapsedPartialTicks += clamp(realDelta, 0, 1) * timerSpeed * ticksPerSecond (line 97), then elapsedTicks is the integer part, capped at 10 ticks per frame. The module writes the static field from a pre-motion event every tick, so the multiplier applies to every frame while toggled and no other code path can override it. A 2x clock doubles the tick budget per real second, and with it the rate of every per-tick serverbound packet.

The truncation bug

The write is Timer.timerSpeed = (float)(int) timer.getCurrentValue(), and the int cast is a first-class finding. Values 2.0 through 2.9 all become 2.0, 3.0 through 3.9 become 3.0, and 0.1 through 0.9 become 0.0. A zero timerSpeed means elapsedPartialTicks never accumulates, so elapsedTicks stays 0 and the game does not tick at all: the slider's slow range is a freeze, not a slow-motion. onEnable writes the raw float without the cast, so the first frame after enabling uses the exact setting before the pre-motion handler truncates it. The effective range after the first tick is therefore {0, 1..10}, not 0.1 to 10.

Wire picture

The module sends nothing itself; it changes when the client emits what it would emit anyway. The C03 movement stream (one to three position packets per tick from func_175161_p) scales with the clock, the C00 keepalive replies and C0F transaction confirmations are emitted earlier relative to wall time because the network read loop runs more often, and those periodic streams are exactly the anchors the countering checks use: Frequency TimerA refuses to run without a recently accepted keepalive, and Grim Timer calibrates its movement clock against the C0F and PONG stream.

source TimerModule.java (module)

TimerModule.java52 lines · JavaOriginal ↗
1
package dev.tenacity.module.impl.world;
2
3
import dev.tenacity.event.IEventListener;
4
import dev.tenacity.event.impl.packet.PacketReceiveEvent;
5
import dev.tenacity.event.impl.player.MotionEvent;
6
import dev.tenacity.event.impl.render.Render2DEvent;
7
import dev.tenacity.module.Module;
8
import dev.tenacity.module.ModuleCategory;
9
import dev.tenacity.setting.impl.ModeSetting;
10
import dev.tenacity.setting.impl.NumberSetting;
11
import dev.tenacity.util.misc.TimerUtil;
12
import net.minecraft.network.Packet;
13
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
14
import net.minecraft.util.Timer;
15
16
public final class TimerModule extends Module {
17
18
19
    private final TimerUtil timerUtil = new TimerUtil();
20
21
    public final NumberSetting timer = new NumberSetting("Speed:", 1, 0.1, 10, 0.1);
22
23
    public TimerModule() {
24
        super("Timer", "Speeds up or slows down time", ModuleCategory.WORLD);
25
         initializeSettings(timer);
26
       // initializeSettings(mode);
27
    }
28
29
    private final IEventListener<MotionEvent> onMotionEvent = event -> {
30
        if (event.isPre()) {
31
            Timer.timerSpeed = (float) (int) timer.getCurrentValue();
32
        }
33
    };
34
35
    @Override
36
    public void onEnable() {
37
        if (mc.thePlayer == null) {
38
            return;
39
        }
40
        Timer.timerSpeed = (float) timer.getCurrentValue();
41
        super.onEnable();
42
    }
43
    @Override
44
    public void onDisable() {
45
        if (mc.thePlayer == null) {
46
            return;
47
        }
48
        Timer.timerSpeed = 1f;
49
        super.onDisable();
50
    }
51
}

What this file does

The module is three small handlers: onMotionEvent writes the truncated timerSpeed every pre-motion, onEnable writes the raw float once, and onDisable restores 1.0F. The unused TimerUtil field and the commented-out initializeSettings(mode) line are leftovers. The truncating cast in the pre-motion write is the whole story of the module: it is the difference between the advertised 0.1 to 10 range and the real {0, 1..10} behavior after the first tick.

source Timer.java (vanilla clock target)

Timer.java108 lines · JavaOriginal ↗
1
package net.minecraft.util;
2
3
import net.minecraft.client.Minecraft;
4
5
public class Timer
6
{
7
    /** The number of timer ticks per second of real time */
8
    float ticksPerSecond;
9
10
    /**
11
     * The time reported by the high-resolution clock at the last call of updateTimer(), in seconds
12
     */
13
    private double lastHRTime;
14
15
    /**
16
     * How many full ticks have turned over since the last call to updateTimer(), capped at 10.
17
     */
18
    public int elapsedTicks;
19
20
    /**
21
     * How much time has elapsed since the last tick, in ticks, for use by display rendering routines (range: 0.0 -
22
     * 1.0).  This field is frozen if the display is paused to eliminate jitter.
23
     */
24
    public float renderPartialTicks;
25
26
    /**
27
     * A multiplier to make the timer (and therefore the game) go faster or slower.  0.5 makes the game run at half-
28
     * speed.
29
     */
30
    public static float timerSpeed = 1.0F;
31
32
    /**
33
     * How much time has elapsed since the last tick, in ticks (range: 0.0 - 1.0).
34
     */
35
    public float elapsedPartialTicks;
36
37
    /**
38
     * The time reported by the system clock at the last sync, in milliseconds
39
     */
40
    private long lastSyncSysClock;
41
42
    /**
43
     * The time reported by the high-resolution clock at the last sync, in milliseconds
44
     */
45
    private long lastSyncHRClock;
46
    private long field_74285_i;
47
48
    /**
49
     * A ratio used to sync the high-resolution clock to the system clock, updated once per second
50
     */
51
    private double timeSyncAdjustment = 1.0D;
52
53
    public Timer(float p_i1018_1_)
54
    {
55
        this.ticksPerSecond = p_i1018_1_;
56
        this.lastSyncSysClock = Minecraft.getSystemTime();
57
        this.lastSyncHRClock = System.nanoTime() / 1000000L;
58
    }
59
60
    /**
61
     * Updates all fields of the Timer using the current time
62
     */
63
    public void updateTimer()
64
    {
65
        long i = Minecraft.getSystemTime();
66
        long j = i - this.lastSyncSysClock;
67
        long k = System.nanoTime() / 1000000L;
68
        double d0 = (double)k / 1000.0D;
69
70
        if (j <= 1000L && j >= 0L)
71
        {
72
            this.field_74285_i += j;
73
74
            if (this.field_74285_i > 1000L)
75
            {
76
                long l = k - this.lastSyncHRClock;
77
                double d1 = (double)this.field_74285_i / (double)l;
78
                this.timeSyncAdjustment += (d1 - this.timeSyncAdjustment) * 0.20000000298023224D;
79
                this.lastSyncHRClock = k;
80
                this.field_74285_i = 0L;
81
            }
82
83
            if (this.field_74285_i < 0L)
84
            {
85
                this.lastSyncHRClock = k;
86
            }
87
        }
88
        else
89
        {
90
            this.lastHRTime = d0;
91
        }
92
93
        this.lastSyncSysClock = i;
94
        double d2 = (d0 - this.lastHRTime) * this.timeSyncAdjustment;
95
        this.lastHRTime = d0;
96
        d2 = MathHelper.clamp_double(d2, 0.0D, 1.0D);
97
        this.elapsedPartialTicks = (float)((double)this.elapsedPartialTicks + d2 * (double)this.timerSpeed * (double)this.ticksPerSecond);
98
        this.elapsedTicks = (int)this.elapsedPartialTicks;
99
        this.elapsedPartialTicks -= (float)this.elapsedTicks;
100
101
        if (this.elapsedTicks > 10)
102
        {
103
            this.elapsedTicks = 10;
104
        }
105
106
        this.renderPartialTicks = this.elapsedPartialTicks;
107
    }
108
}

What this file does

Tenacity 6.0 ships the vanilla net/minecraft tree, and this file is the object the module abuses. updateTimer() accumulates elapsedPartialTicks from the wall-clock delta multiplied by the static timerSpeed and ticksPerSecond (line 97), caps elapsedTicks at 10 per frame, and feeds the result to the client tick loop. The static timerSpeed field (line 30) is the single global multiplier the module rewrites, which is why one write per tick is enough to scale the entire packet pipeline.

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 NCP MorePackets (movement rate window)

MorePackets.java127 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 java.util.ArrayList;
18
import java.util.List;
19
20
import org.bukkit.Location;
21
import org.bukkit.entity.Player;
22
23
import fr.neatmonster.nocheatplus.actions.ParameterName;
24
import fr.neatmonster.nocheatplus.checks.Check;
25
import fr.neatmonster.nocheatplus.checks.CheckType;
26
import fr.neatmonster.nocheatplus.checks.ViolationData;
27
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
28
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
29
import fr.neatmonster.nocheatplus.checks.net.NetStatic;
30
import fr.neatmonster.nocheatplus.players.IPlayerData;
31
import fr.neatmonster.nocheatplus.utilities.StringUtil;
32
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
33
34
/**
35
 * The MorePackets check will try to identify players that send more than the usual
36
 * amount of move-packets to the server to be able to move faster than normal, without getting caught by the other
37
 * checks (flying/running).
38
 */
39
public class MorePackets extends Check {
40
41
    private final List<String> tags = new ArrayList<String>();
42
43
    /**
44
     * Instantiates a new more packets check.
45
     */
46
    public MorePackets() {
47
        super(CheckType.MOVING_MOREPACKETS);
48
    }
49
50
    /**
51
     * Check for speeding by sending too many packets. We assume 22 packets per
52
     * second to be legitimate, while 20 would be ideal. See
53
     * PlayerData.morePacketsFreq for the monitored amount of time and the
54
     * resolution. See NetStatic for the actual check code.
55
     * 
56
     * @param player
57
     * @param from
58
     * @param to
59
     * @param allowSetSetBack
60
     *            If to allow setting the set back location.
61
     * @param data
62
     * @param cc
63
     * @return
64
     */
65
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to, 
66
            final boolean allowSetSetBack, final MovingData data, final MovingConfig cc,
67
            final IPlayerData pData) {
68
        // Take time once, first:
69
        final long time = System.currentTimeMillis();
70
        final boolean debug = pData.isDebugActive(type);
71
72
        //    	if (from.isSamePos(to)) {
73
        //    		// Ignore moves with "just look" for now.
74
        //    		// TODO: Extra ActionFrequency for "just look" + use to burn, maybe also check individually.
75
        //    		return null;
76
        //    	}
77
78
        // Ensure we have a set back location.
79
        if (allowSetSetBack && !data.hasMorePacketsSetBack()){
80
            // TODO: Check if other set back is appropriate or if to set/reset on other events.
81
            if (data.hasSetBack()) {
82
                data.setMorePacketsSetBackFromSurvivalfly();
83
            }
84
            else {
85
                data.setMorePacketsSetBack(from);
86
            }
87
        }
88
89
        // Check for a violation of the set limits.
90
        tags.clear();
91
        final double violation = NetStatic.morePacketsCheck(data.morePacketsFreq, time, 1f, cc.morePacketsEPSMax, cc.morePacketsEPSIdeal, data.morePacketsBurstFreq, cc.morePacketsBurstPackets, cc.morePacketsBurstDirect, cc.morePacketsBurstEPM, tags);
92
93
        // Process violation result.
94
        if (violation > 0.0) {
95
            // Increment violation level.
96
            data.morePacketsVL = violation; // TODO: Accumulate somehow [e.g. always += 1, decrease with continuous moving without violation]?
97
98
            // Violation handling.
99
            final ViolationData vd = new ViolationData(this, player, data.morePacketsVL, violation, cc.morePacketsActions);
100
            if (debug || vd.needsParameters()) {
101
                vd.setParameter(ParameterName.PACKETS, Integer.toString(new Double(violation).intValue()));
102
                vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
103
            }
104
            if (executeActions(vd).willCancel()) {
105
                // Set to cancel the move.
106
                /*
107
                 * TODO: Harmonize with MovingUtil.getApplicableSetBackLocation
108
                 * (somehow include the desired set back type / loc / context).
109
                 */
110
                return data.hasMorePacketsSetBack() ? data.getMorePacketsSetBack() : data.getSetBack(to); // TODO
111
            }
112
        } 
113
        else if (allowSetSetBack && data.getMorePacketsSetBackAge() > cc.morePacketsSetBackAge) {
114
            // Update the set back location. (CHANGED to only update, if not a violation.)
115
            // (Might update whenever newTo == null)
116
            data.setMorePacketsSetBack(from);
117
            if (debug) {
118
                debug(player, "Update set back (morepackets) to from.");
119
            }
120
        }
121
122
        // No set back.
123
        return null;
124
125
    }
126
127
}

How it counteracts this module

MorePackets scores every processed move into morePacketsFreq, an ActionFrequency with 500ms buckets over the configured window (MovingData line 321), against a 22 packets per second ceiling with 20 ideal, plus a burst path on the newest half-second bucket (15 packets, direct-violation 10, burst events 95 per minute). A 2x clock produces roughly 40 C03 packets per second sustained, so the window accumulator runs positive for the whole duration and the check cancels at vl above 2, with the set-back seeded from SurvivalFly. The detection floor is sustained use above about 1.1x because empty buckets burn excess; short spikes under the window ceiling are forgiven.

anticheat NCP KeepAliveFrequency (keepalive ledger gate)

KeepAliveFrequency.java101 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;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.players.IPlayerData;
22
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
23
24
public class KeepAliveFrequency extends Check {
25
26
    public KeepAliveFrequency() {
27
        super(CheckType.NET_KEEPALIVEFREQUENCY);
28
    }
29
    
30
    /**
31
     * Checks hasBypass on violation only.
32
     * @param player
33
     * @param time
34
     * @param data
35
     * @param cc
36
     * @return If to cancel.
37
     */
38
    public boolean check(final Player player, final long time, final NetData data, final NetConfig cc, final IPlayerData pData) {
39
        final long now = System.currentTimeMillis();
40
        final long joinTime = pData.getLastJoinTime();
41
        if (joinTime > 0L && now < joinTime + cc.keepAliveFrequencyStartupDelay) {
42
            return false;
43
        }
44
        if (data.keepAliveExpectedResponse && !data.keepAliveDuplicateId) {
45
            return false;
46
        }
47
        data.keepAliveFreq.add(time, 1f);
48
        final float first = data.keepAliveFreq.bucketScore(0);
49
        
50
        if (first > 1f) {
51
            // Trigger a violation.
52
            final float fullScore = data.keepAliveFreq.score(1f);
53
            if (isModeledBoundaryBurst(data, fullScore, first)) {
54
                return false;
55
            }
56
            final double vl = Math.max(first - getFirstBucketViolationLimit(data), fullScore - data.keepAliveFreq.numberOfBuckets());
57
            final boolean cancel = executeActions(player, vl, 1.0, cc.keepAliveFrequencyActions).willCancel();
58
            return cancel;
59
        }
60
        return false;
61
    }
62
63
    private boolean isModeledBoundaryBurst(final NetData data, final float fullScore, final float first) {
64
        // KeepAlive model: if outgoing tracking is unavailable, only treat small monotonic id bursts as timing leftovers.
65
        if (data.keepAliveDuplicateId || fullScore > data.keepAliveFreq.numberOfBuckets() + 2f) {
66
            return false;
67
        }
68
        // Folia/netty can timestamp two adjacent valid replies in the same millisecond; do not cancel a single pair.
69
        return first <= 2f || isUntrackedMonotonicBurst(data, fullScore, first);
70
    }
71
72
    private boolean isUntrackedMonotonicBurst(final NetData data, final float fullScore, final float first) {
73
        if (data.keepAliveOutgoingSeen || fullScore > data.keepAliveFreq.numberOfBuckets()) {
74
            return false;
75
        }
76
        if (!data.keepAlivePacketIdAvailable || !data.keepAlivePreviousPacketIdAvailable) {
77
            return false;
78
        }
79
        if (data.keepAlivePacketId <= data.keepAlivePreviousPacketId) {
80
            return false;
81
        }
82
        return first <= getFallbackFirstBucketLimit(data);
83
    }
84
85
    private float getFirstBucketViolationLimit(final NetData data) {
86
        if (data.keepAliveDuplicateId) {
87
            return 1f;
88
        }
89
        if (!data.keepAliveOutgoingSeen
90
                && data.keepAlivePacketIdAvailable
91
                && data.keepAlivePreviousPacketIdAvailable
92
                && data.keepAlivePacketId > data.keepAlivePreviousPacketId) {
93
            return getFallbackFirstBucketLimit(data);
94
        }
95
        return 2f;
96
    }
97
98
    private float getFallbackFirstBucketLimit(final NetData data) {
99
        return Math.max(3f, Math.min(6f, data.keepAliveFreq.numberOfBuckets() / 4f));
100
    }
101
}

How it counteracts this module

KeepAliveFrequency replaces accept-any-echo keepalives with an id ledger: every outgoing S00 id is recorded (pruned after 30000ms, capped at 40 pending) and each incoming C00 is matched against it, with unexpected or duplicate replies counted into one-second buckets. Its structural role here is a gate: Frequency TimerA refuses to run unless a keepalive was recently accepted, so the ledger is what arms the timer check. It fires on the accelerated loop when a batched keepalive delivery drains into one second-bucket or when replies age out or duplicate.

anticheat Frequency TimerA (inter-packet delay)

TimerA.java84 lines · Java
1
package xyz.elevated.frequency.check.impl.timer;
2
3
import xyz.elevated.frequency.Frequency;
4
import xyz.elevated.frequency.check.CheckData;
5
import xyz.elevated.frequency.check.type.PacketCheck;
6
import xyz.elevated.frequency.data.PlayerData;
7
import xyz.elevated.frequency.exempt.type.ExemptType;
8
import xyz.elevated.frequency.util.MovingStats;
9
import xyz.elevated.frequency.wrapper.impl.client.WrappedPlayInFlying;
10
11
@CheckData(name = "Timer (A)")
12
public final class TimerA extends PacketCheck {
13
    private final MovingStats movingStats = new MovingStats(20);
14
15
    private long lastFlying = 0L;
16
    private long allowance = 0;
17
18
    public TimerA(final PlayerData playerData) {
19
        super(playerData);
20
    }
21
22
    @Override
23
    public void process(final Object object) {
24
        final boolean flying = object instanceof WrappedPlayInFlying;
25
26
        if (flying) {
27
            // Get the server ticks and the current time for the check processing
28
            final int serverTicks = Frequency.INSTANCE.getTickManager().getTicks();
29
            final long now = System.currentTimeMillis();
30
31
            /*
32
            * We want to make sure the player is not exempt from any of the actions below.
33
            * Additionally, we want to ensure that the player is not lagged out and accepted a keepalive.
34
            * Thankfully, we shouldn't have any bypasses because of this because of PingSpoof.
35
             */
36
            final boolean exempt = this.isExempt(ExemptType.TPS, ExemptType.TELEPORTING, ExemptType.LAGGING);
37
            final boolean accepted = playerData.getConnectionManager().getKeepAliveTime(serverTicks).isPresent();
38
39
            /*
40
            * Basic theory is that the player is going to deviate through 50ms without many changes to that
41
            * basic range of [48, 50]. So we're running a deviation check to check how much the player has deviated
42
            * from the basic limit of 50ms (square-root of 50 is 7.07). We're also making sure the player is actually
43
            * increasing speed through an allowance that accounts for the tick expected versus the tick received.
44
             */
45
            handle: {
46
                if (exempt || !accepted) break handle;
47
48
                // Get the delay from the current and the last flying packet
49
                final long delay = now - lastFlying;
50
51
                // Add the delay to the MovingStats to analyze our input
52
                movingStats.add(delay);
53
54
                /*
55
                * As mentioned above, the basic threshold of the player is the square-root of 50. Because
56
                * the expected tick should always be 50ms. To check how much the player has deviated from that
57
                * single point, we're using it as a threshold value in the deviation check below.
58
                 */
59
                final double threshold = 7.07;
60
                final double deviation = movingStats.getStdDev(threshold);
61
62
                // We're making sure the deviation check processed and the deviation is smaller than the threshold.
63
                if (deviation < threshold && !Double.isNaN(deviation)) {
64
                    /*
65
                    * I am sure many of you have seen this before, and it's essentially the most basic version of
66
                    * a balance / allowance check. We're increasing the allowance with the expected amount of 50,
67
                    * and we're subtracting from it the actual delay received. This will act as our "buffer" system.
68
                     */
69
                    allowance += 50;
70
                    allowance -= delay;
71
72
                    // Our previous threshold can act as one here too.
73
                    if (allowance > Math.floor(threshold)) fail();
74
                }
75
76
                else {
77
                    allowance = 0;
78
                }
79
            }
80
81
            this.lastFlying = now;
82
        }
83
    }
84
}

How it counteracts this module

TimerA compares the delay between consecutive C03 packets against the 50ms tick expectation: each move adds 50 minus the observed delay to an allowance, and the check fails once the allowance exceeds the floor of 7.07, gated on a recently accepted keepalive and exemption flags for TPS, TELEPORT and LAG. A 2x clock compresses inter-packet gaps to roughly 25ms, so the allowance climbs past the threshold within two packets. Sub-1x speed drains the allowance instead, so slow timer passes by design; the truncation bug's 0.0 freeze is likewise invisible to this check because no packets arrive at all.

anticheat Grim Timer (transaction-anchored balance)

Timer.java113 lines · Java
1
package ac.grim.grimac.checks.impl.timer;
2
3
import ac.grim.grimac.api.config.ConfigManager;
4
import ac.grim.grimac.checks.Check;
5
import ac.grim.grimac.checks.CheckData;
6
import ac.grim.grimac.checks.type.PrePredictionPacketReceiveListener;
7
import ac.grim.grimac.player.GrimPlayer;
8
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
9
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
10
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
11
import org.jetbrains.annotations.NotNull;
12
13
@CheckData(name = "Timer", stableKey = "grim.timer.timer", configName = "TimerA", description = "The players game is running faster than normal", setback = 10)
14
public class Timer extends Check implements PrePredictionPacketReceiveListener {
15
    protected long timerBalanceRealTime = 0;
16
17
    // Default value is real time minus max keep-alive time
18
    protected long knownPlayerClockTime = (long) (System.nanoTime() - 6e10);
19
    protected long lastMovementPlayerClock = (long) (System.nanoTime() - 6e10);
20
21
    // How long should the player be able to fall back behind their ping? (nanos)
22
    // Default: 120 milliseconds
23
    protected long clockDrift;
24
25
    protected boolean hasGottenMovementAfterTransaction = false;
26
27
    // Proof for this timer check
28
    // https://i.imgur.com/Hk2Wb6c.png
29
    //
30
    // The largest gap will always be the transaction ping (server -> client -> server)
31
    // Proof lies that client -> server ping will always be lower
32
    //
33
    // The largest gap is the floor for movements
34
    // If the smaller gap surpasses the larger gap, the player is cheating
35
    //
36
    // This usually flags 1.01 on low ping extremely quickly
37
    // Higher ping/low fps scales proportionately, and will flag less quickly but will still always flag 1.01
38
    // Players standing still will reset this amount of time
39
    //
40
    // This is better than traditional timer checks because ping fluctuations will never affect this check
41
    // As we are tying this check to the player's ping, rather than real time.
42
    //
43
    // Tested 10/20/30 fps and f3 + t spamming for lag spikes at 0 ping localhost/200 ping clumsy, no falses
44
    // Also didn't false when going from 0 -> 2000 ms ping, and 2000 ms -> 0 ms ping
45
    // it's a very nice check, in my opinion.  I guess I will find out if netty lag can false it
46
47
    // You might notice that we deviate a bit from this to handle lag
48
    // We take the FIRST transaction after each movement, to avoid issues with this packet order at low FPS:
49
    // TRANSACTION TRANSACTION TRANSACTION MOVEMENT MOVEMENT MOVEMENT
50
    // TRANSACTION TRANSACTION TRANSACTION MOVEMENT MOVEMENT MOVEMENT
51
    //
52
    // We then take the last transaction before this to increase stability with these lag spikes and
53
    // to guarantee that we are at least 50 ms back before adding the time
54
    public Timer(GrimPlayer player) {
55
        super(player);
56
    }
57
58
    @Override
59
    public void onPrePredictionPacketReceive(final PacketReceiveEvent event) {
60
        if (hasGottenMovementAfterTransaction && checkForTransaction(event.getPacketType())) {
61
            knownPlayerClockTime = lastMovementPlayerClock;
62
            lastMovementPlayerClock = player.getPlayerClockAtLeast();
63
            hasGottenMovementAfterTransaction = false;
64
        }
65
66
        if (!shouldCountPacketForTimer(event.getPacketType())) return;
67
68
        hasGottenMovementAfterTransaction = true;
69
        timerBalanceRealTime += 50e6;
70
71
        doCheck(event);
72
    }
73
74
    public void doCheck(final PacketReceiveEvent event) {
75
        if (timerBalanceRealTime > System.nanoTime()) {
76
            if (flag()) {
77
                // Cancel the packet
78
                if (shouldModifyPackets()) {
79
                    event.setCancelled(true);
80
                    player.onPacketCancel();
81
                }
82
83
                if (shouldSetback()) {
84
                    player.getSetbackTeleportUtil().executeNonSimulatingSetback();
85
                }
86
            }
87
88
            // Reset the violation by 1 movement
89
            timerBalanceRealTime -= 50e6;
90
        }
91
92
        limitFallBehind();
93
    }
94
95
    protected void limitFallBehind() {
96
        timerBalanceRealTime = Math.max(timerBalanceRealTime, lastMovementPlayerClock - clockDrift);
97
    }
98
99
    public boolean checkForTransaction(PacketTypeCommon packetType) {
100
        return packetType == PacketType.Play.Client.PONG ||
101
                packetType == PacketType.Play.Client.WINDOW_CONFIRMATION;
102
    }
103
104
    public boolean shouldCountPacketForTimer(PacketTypeCommon packetType) {
105
        // If not flying, or this was a teleport, or this was a duplicate 1.17 mojang stupidity packet
106
        return isTickPacket(packetType);
107
    }
108
109
    @Override
110
    public void onReload(@NotNull ConfigManager config) {
111
        clockDrift = (long) (config.getDoubleElse(getConfigName() + ".drift", 120.0) * 1e6);
112
    }
113
}

How it counteracts this module

Grim Timer grants 50ms of balance per movement packet against real time measured with System.nanoTime, with the baseline clock anchored to the C0F stream: knownPlayerClockTime is only refreshed after a movement followed by a PONG or WINDOW_CONFIRMATION, and clockDrift defaults to 120ms. Each accelerated packet spends 50ms of balance that only about 50ms of real time repays, so a 2x clock drives the balance deeply negative within a few ticks, and the burst path catches the 10-ticks-in-one-frame cap when the render loop stalls. The check is one-directional: sub-1x and the freeze both pass, since falling behind is absorbed by limitFallBehind.

← Back to Analysis Hub