forked from GlaireDaggers/Netcode.IO.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetcodeReplayProtection.cs
More file actions
56 lines (47 loc) · 1.31 KB
/
Copy pathNetcodeReplayProtection.cs
File metadata and controls
56 lines (47 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
namespace NetcodeIO.NET.Internal
{
/// <summary>
/// Helper class for protecting against packet replay
/// </summary>
internal sealed class NetcodeReplayProtection
{
private const int NETCODE_REPLAY_PROTECTION_BUFFER_SIZE = 256;
public ulong mostRecentSequence;
public ulong[] receivedPackets;
public NetcodeReplayProtection()
{
mostRecentSequence = 0;
receivedPackets = new ulong[NETCODE_REPLAY_PROTECTION_BUFFER_SIZE];
Reset();
}
/// <summary>
/// Reset the packet replay buffer
/// </summary>
public void Reset()
{
mostRecentSequence = 0;
for (int i = 0; i < receivedPackets.Length; i++)
receivedPackets[i] = ulong.MaxValue;
}
/// <summary>
/// Check if the given packet was already received. If not, store it in the replay buffer.
/// </summary>
public bool AlreadyReceived(ulong sequence)
{
if ((sequence & ((ulong)1 << 63)) != 0)
return false;
if (sequence + NETCODE_REPLAY_PROTECTION_BUFFER_SIZE <= mostRecentSequence)
return true;
int index = (int)(sequence % NETCODE_REPLAY_PROTECTION_BUFFER_SIZE);
if (receivedPackets[index] == 0xFFFFFFFFFFFFFFFF)
{
receivedPackets[index] = sequence;
return false;
}
if (receivedPackets[index] >= sequence)
return true;
receivedPackets[index] = sequence;
return false;
}
}
}