Repository navigation
Expand file tree
/
Copy pathTests.cs
More file actions
1795 lines (1371 loc) · 59 KB
/
Copy pathTests.cs
File metadata and controls
1795 lines (1371 loc) · 59 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using NetcodeIO.NET.Utils;
using NetcodeIO.NET.Utils.IO;
using NetcodeIO.NET.Internal;
using System.Diagnostics;
namespace NetcodeIO.NET.Tests
{
/// <summary>
/// A suite of test methods for verifying that components of the API functions as intended
/// All methods will either throw an exception if the test fails, or will simply return with no errors on success.
/// </summary>
public static class Tests
{
const ulong TEST_PROTOCOL_ID = 0x1122334455667788L;
const ulong TEST_CLIENT_ID = 0x1L;
const int TEST_SERVER_PORT = 40000;
const int TEST_CONNECT_TOKEN_EXPIRY = 30;
static readonly byte[] _privateKey = new byte[]
{
0x60, 0x6a, 0xbe, 0x6e, 0xc9, 0x19, 0x10, 0xea,
0x9a, 0x65, 0x62, 0xf6, 0x6f, 0x2b, 0x30, 0xe4,
0x43, 0x71, 0xd6, 0x2c, 0xd1, 0x99, 0x27, 0x26,
0x6b, 0x3c, 0x60, 0xf4, 0xb7, 0x15, 0xab, 0xa1,
};
private struct testEncryptionMapping
{
public EndPoint address;
public byte[] SendKey;
public byte[] ReceiveKey;
public int TimeoutSeconds;
public uint ClientID;
}
public static void TestSequence()
{
assert(MiscUtils.SequenceBytesRequired(0) == 1);
assert(MiscUtils.SequenceBytesRequired(0x11) == 1);
assert(MiscUtils.SequenceBytesRequired(0x1122) == 2);
assert(MiscUtils.SequenceBytesRequired(0x112233) == 3);
assert(MiscUtils.SequenceBytesRequired(0x11223344) == 4);
assert(MiscUtils.SequenceBytesRequired(0x1122334455) == 5);
assert(MiscUtils.SequenceBytesRequired(0x112233445566) == 6);
assert(MiscUtils.SequenceBytesRequired(0x11223344556677) == 7);
assert(MiscUtils.SequenceBytesRequired(0x1122334455667788) == 8);
}
public static void TestConnectToken()
{
TokenFactory factory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
IPEndPoint serverEndpoint2 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 10);
IPEndPoint[] connectServers = new IPEndPoint[]
{
serverEndpoint, serverEndpoint2
};
byte[] userData = new byte[256];
KeyUtils.GenerateKey(userData);
ulong timestamp = DateTime.Now.ToUnixTimestamp();
byte[] connectToken = factory.GenerateConnectToken(connectServers, TEST_CONNECT_TOKEN_EXPIRY, 5, 1, TEST_CLIENT_ID, userData);
NetcodePublicConnectToken token = new NetcodePublicConnectToken();
using (var reader = ByteArrayReaderWriter.Get(connectToken))
{
token.Read(reader);
}
assert(token.ProtocolID == TEST_PROTOCOL_ID, "Token protocol ID does not match");
assert(token.TimeoutSeconds == 5, "Token expiry does not match");
assert(token.ConnectServers.Length == connectServers.Length, "Token connect server lists do not match");
for (int i = 0; i < token.ConnectServers.Length; i++)
{
bool match = token.ConnectServers[i].Endpoint.Equals(connectServers[i]);
assert(match, "Token connect server lists do not match");
}
assert(token.ExpireTimestamp > token.CreateTimestamp, "Token expire timestamp invalid");
assert(token.CreateTimestamp >= timestamp, "Token create timestamp invalid");
byte[] privateConnectToken = token.PrivateConnectTokenBytes;
NetcodePrivateConnectToken privateToken = new NetcodePrivateConnectToken();
privateToken.Read(privateConnectToken, _privateKey, TEST_PROTOCOL_ID, token.ExpireTimestamp, token.ConnectTokenSequence);
assert(privateToken.ClientID == TEST_CLIENT_ID, "Private token client ID does not match");
assert(MiscUtils.ByteArraysEqual(userData, privateToken.UserData), "Private token user data mismatch");
}
public static void TestChallengeToken()
{
// generate a challenge token
NetcodeChallengeToken challengeToken = new NetcodeChallengeToken();
challengeToken.ClientID = TEST_CLIENT_ID;
byte[] userData = new byte[256];
KeyUtils.GenerateKey(userData);
challengeToken.UserData = userData;
// write challenge token
byte[] challengeTokenBytes = new byte[300];
using (var writer = ByteArrayReaderWriter.Get(challengeTokenBytes))
challengeToken.Write(writer);
// encrypt buffer
byte[] encryptedChallengeToken = new byte[300];
ulong sequence = 1000;
byte[] key = new byte[32];
KeyUtils.GenerateKey(key);
int challengeTokenLength = PacketIO.EncryptChallengeToken(sequence, challengeTokenBytes, key, encryptedChallengeToken);
// read challenge token back in
NetcodeChallengeToken readChallengeToken = new NetcodeChallengeToken();
readChallengeToken.Read(encryptedChallengeToken, sequence, key);
assert(readChallengeToken.ClientID == challengeToken.ClientID, "Client ID mismatch");
assert(MiscUtils.ByteArraysEqual(readChallengeToken.UserData, challengeToken.UserData), "User data mismatch");
}
public static void TestEncryptionManager()
{
EncryptionManager encryptionManager = new EncryptionManager(256);
encryptionManager.Reset();
double time = 100.0;
testEncryptionMapping[] encryptionMapping = new testEncryptionMapping[5];
for (int i = 0; i < encryptionMapping.Length; i++)
{
encryptionMapping[i] = new testEncryptionMapping()
{
address = new IPEndPoint(IPAddress.Parse("0:0:0:0:0:0:0:1"), 20000 + i),
SendKey = new byte[32],
ReceiveKey = new byte[32],
TimeoutSeconds = 10 + i,
ClientID = (uint)i
};
KeyUtils.GenerateKey(encryptionMapping[i].SendKey);
KeyUtils.GenerateKey(encryptionMapping[i].ReceiveKey);
}
// add encryption mappings and make sure they can be looked up by address
for (int i = 0; i < encryptionMapping.Length; i++)
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
assert(encryptionIndex == -1, "Encryption manager returned invalid index");
assert(encryptionManager.GetSendKey(encryptionIndex) == null, "Encryption manager returned invalid key");
assert(encryptionManager.GetReceiveKey(encryptionIndex) == null, "Encryption manager returned invalid key");
assert(encryptionManager.AddEncryptionMapping(encryptionMapping[i].address, encryptionMapping[i].SendKey, encryptionMapping[i].ReceiveKey, time, -1.0, encryptionMapping[i].TimeoutSeconds, encryptionMapping[i].ClientID), "Encryption manager failed to add mapping");
encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
int timeoutSeconds = encryptionManager.GetTimeoutSeconds(encryptionIndex);
uint clientID = encryptionManager.GetClientID(encryptionIndex);
assert(timeoutSeconds == encryptionMapping[i].TimeoutSeconds, "Encryption manager returned invalid timeout seconds");
assert(clientID == encryptionMapping[i].ClientID, "Encryption manager returned invalid client ID");
byte[] sendKey = encryptionManager.GetSendKey(encryptionIndex);
byte[] receiveKey = encryptionManager.GetReceiveKey(encryptionIndex);
assert(sendKey != null, "Encryption manager failed to return key");
assert(receiveKey != null, "Encryption manager failed to return key");
assert(MiscUtils.ByteArraysEqual(sendKey, encryptionMapping[i].SendKey), "Encryption manager returned invalid key");
assert(MiscUtils.ByteArraysEqual(receiveKey, encryptionMapping[i].ReceiveKey), "Encryption manager returned invalid key");
}
// removing an encryption mapping that doesn't exist should return false
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("0:0:0:0:0:0:0:1"), 50000);
assert(encryptionManager.RemoveEncryptionMapping(endpoint, time) == false, "Encryption manager removed invalid entry");
}
// remove first and last encryption mappings
assert(encryptionManager.RemoveEncryptionMapping(encryptionMapping[0].address, time), "Encryption manager failed to remove entry");
assert(encryptionManager.RemoveEncryptionMapping(encryptionMapping[encryptionMapping.Length - 1].address, time), "Encryption manager failed to remove entry");
// ensure removed encryption mappings cannot be looked up by address
for (int i = 0; i < encryptionMapping.Length; i++)
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
byte[] sendKey = encryptionManager.GetSendKey(encryptionIndex);
byte[] receiveKey = encryptionManager.GetReceiveKey(encryptionIndex);
if (i == 0 || i == (encryptionMapping.Length - 1))
{
assert(sendKey == null, "Encryption manager returned invalid key");
assert(receiveKey == null, "Encryption manager returned invalid key");
}
else
{
assert(sendKey != null, "Encryption manager failed to return key");
assert(receiveKey != null, "Encryption manager failed to return key");
assert(MiscUtils.ByteArraysEqual(sendKey, encryptionMapping[i].SendKey), "Encryption manager returned invalid key");
assert(MiscUtils.ByteArraysEqual(receiveKey, encryptionMapping[i].ReceiveKey), "Encryption manager returned invalid key");
}
}
// add the encryption mappings back in
assert(
encryptionManager.AddEncryptionMapping(
encryptionMapping[0].address,
encryptionMapping[0].SendKey,
encryptionMapping[0].ReceiveKey,
time, -1.0,
encryptionMapping[0].TimeoutSeconds,
encryptionMapping[0].ClientID),
"Encryption manager failed to add mapping");
assert(
encryptionManager.AddEncryptionMapping(
encryptionMapping[encryptionMapping.Length - 1].address,
encryptionMapping[encryptionMapping.Length - 1].SendKey,
encryptionMapping[encryptionMapping.Length - 1].ReceiveKey,
time, -1.0,
encryptionMapping[encryptionMapping.Length - 1].TimeoutSeconds,
encryptionMapping[encryptionMapping.Length - 1].ClientID),
"Encryption manager failed to add mapping");
// ensure all encryption mappings can be looked up
for (int i = 0; i < encryptionMapping.Length; i++)
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
int timeoutSeconds = encryptionManager.GetTimeoutSeconds(encryptionIndex);
uint clientID = encryptionManager.GetClientID(encryptionIndex);
assert(timeoutSeconds == encryptionMapping[i].TimeoutSeconds, "Encryption manager returned invalid timeout seconds");
assert(clientID == encryptionMapping[i].ClientID, "Encryption manager returned invalid client ID");
byte[] sendKey = encryptionManager.GetSendKey(encryptionIndex);
byte[] receiveKey = encryptionManager.GetReceiveKey(encryptionIndex);
assert(sendKey != null, "Encryption manager failed to return key");
assert(receiveKey != null, "Encryption manager failed to return key");
assert(MiscUtils.ByteArraysEqual(sendKey, encryptionMapping[i].SendKey), "Encryption manager returned invalid key");
assert(MiscUtils.ByteArraysEqual(receiveKey, encryptionMapping[i].ReceiveKey), "Encryption manager returned invalid key");
}
// check that encryption mappings time out properly
time += Defines.NETCODE_TIMEOUT_SECONDS * 2;
for (int i = 0; i < encryptionMapping.Length; i++)
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
byte[] sendKey = encryptionManager.GetSendKey(encryptionIndex);
byte[] receiveKey = encryptionManager.GetReceiveKey(encryptionIndex);
assert(sendKey == null, "Encryption manager returned invalid key");
assert(receiveKey == null, "Encryption manager returned invalid key");
}
// add the same encryption mappings after timeout
for (int i = 0; i < encryptionMapping.Length; i++)
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
assert(encryptionIndex == -1, "Encryption manager returned invalid index");
assert(encryptionManager.GetSendKey(encryptionIndex) == null, "Encryption manager returned invalid key");
assert(encryptionManager.GetReceiveKey(encryptionIndex) == null, "Encryption manager returned invalid key");
assert(encryptionManager.AddEncryptionMapping(encryptionMapping[i].address, encryptionMapping[i].SendKey, encryptionMapping[i].ReceiveKey, time, -1.0, encryptionMapping[i].TimeoutSeconds, encryptionMapping[i].ClientID), "Encryption manager failed to add mapping");
encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
int timeoutSeconds = encryptionManager.GetTimeoutSeconds(encryptionIndex);
uint clientID = encryptionManager.GetClientID(encryptionIndex);
assert(timeoutSeconds == encryptionMapping[i].TimeoutSeconds, "Encryption manager returned invalid timeout seconds");
assert(clientID == encryptionMapping[i].ClientID, "Encryption manager returned invalid client ID");
byte[] sendKey = encryptionManager.GetSendKey(encryptionIndex);
byte[] receiveKey = encryptionManager.GetReceiveKey(encryptionIndex);
assert(sendKey != null, "Encryption manager failed to return key");
assert(receiveKey != null, "Encryption manager failed to return key");
assert(MiscUtils.ByteArraysEqual(sendKey, encryptionMapping[i].SendKey), "Encryption manager returned invalid key");
assert(MiscUtils.ByteArraysEqual(receiveKey, encryptionMapping[i].ReceiveKey), "Encryption manager returned invalid key");
}
// reset the encryption manager and ensure all entries are removed
encryptionManager.Reset();
for (int i = 0; i < encryptionMapping.Length; i++)
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[i].address, time);
byte[] sendKey = encryptionManager.GetSendKey(encryptionIndex);
byte[] receiveKey = encryptionManager.GetReceiveKey(encryptionIndex);
assert(sendKey == null, "Encryption manager returned invalid key");
assert(receiveKey == null, "Encryption manager returned invalid key");
}
// test the expire time works as expected
assert(encryptionManager.AddEncryptionMapping(encryptionMapping[0].address, encryptionMapping[0].SendKey, encryptionMapping[0].ReceiveKey, time, time + 1.0, encryptionMapping[0].TimeoutSeconds, encryptionMapping[0].ClientID), "Encryption manager failed to add mapping");
{
int encryptionIndex = encryptionManager.FindEncryptionMapping(encryptionMapping[0].address, time);
assert(encryptionIndex != -1, "Encryption manager failed to find entry");
assert(encryptionManager.FindEncryptionMapping(encryptionMapping[0].address, time + 1.1) == -1, "Encryption manager returned invalid entry");
encryptionManager.SetExpireTime(encryptionIndex, -1.0);
assert(encryptionManager.FindEncryptionMapping(encryptionMapping[0].address, time) == encryptionIndex, "Encryption manager returned invalid entry");
}
}
public static void TestReplayProtection()
{
NetcodeReplayProtection replayProtection = new NetcodeReplayProtection();
for (int i = 0; i < 2; i++)
{
replayProtection.Reset();
assert(replayProtection.mostRecentSequence == 0, "Replay protection failed to reset");
// sequence numbers with high bits set should be ignored
assert(replayProtection.AlreadyReceived(1UL << 63) == false, "Replay protection failed to ignore sequence");
assert(replayProtection.mostRecentSequence == 0, "Replay protection failed to ignore sequence");
const int max_sequence = (256 * 4);
for (ulong sequence = 0; sequence < max_sequence; sequence++)
{
assert(replayProtection.AlreadyReceived(sequence) == false, "Replay protection found invalid sequence");
}
// old packets outside the buffer should be considered already received
assert(replayProtection.AlreadyReceived(0), "Replay protection failed to flag old sequence");
// packets received a second time should be flagged already received
for (ulong sequence = max_sequence - 10; sequence < max_sequence; sequence++)
{
assert(replayProtection.AlreadyReceived(sequence), "Replay protection failed to flag already received sequence");
}
// jumping ahead to a much higher sequence should be considered not already received
assert(replayProtection.AlreadyReceived(max_sequence + 256) == false, "Replay protection flagged new sequence");
// old packets should be considered already received
for (ulong sequence = 0; sequence < max_sequence; sequence++)
{
assert(replayProtection.AlreadyReceived(sequence), "Replay protection failed to flag old sequence");
}
}
}
public static void TestClientServerConnection()
{
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Server server = new Server(socketMgr.CreateContext(serverEndpoint), 256, "127.0.0.1", TEST_SERVER_PORT, TEST_PROTOCOL_ID, _privateKey);
server.Start(false);
server.time = time;
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
ulong clientID = 1000;
byte[] userData = new byte[256];
KeyUtils.GenerateKey(userData);
byte[] connectToken = tokenFactory.GenerateConnectToken(new IPEndPoint[] { serverEndpoint }, TEST_CONNECT_TOKEN_EXPIRY, 5, 0, clientID, userData);
client.Connect(connectToken, false);
while (true)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
if (client.State <= ClientState.Disconnected)
break;
if (client.State == ClientState.Connected)
break;
}
assert(client.State == ClientState.Connected, "Client failed to connect: " + client.State);
int clientMessagesReceived = 0;
int serverMessagesReceived = 0;
server.OnClientMessageReceived += (sender, payload, size) =>
{
// send message back to client
sender.SendPayload(payload, size);
serverMessagesReceived++;
};
client.OnMessageReceived += (payload, size) =>
{
clientMessagesReceived++;
};
// send messages to the server until client and server have at least 10 messages each (or until we hit iteration max)
for (int i = 0; i < 1000; i++)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
byte[] testPayload = new byte[256];
client.Send(testPayload, testPayload.Length);
if (clientMessagesReceived >= 10 && serverMessagesReceived >= 10)
break;
}
assert(clientMessagesReceived >= 10 && serverMessagesReceived >= 10, "Sending messages failed!");
client.Disconnect();
server.Stop();
}
public static void TestClientServerKeepAlive()
{
Console.WriteLine("TestClientServerKeepAlive");
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Server server = new Server(socketMgr.CreateContext(serverEndpoint), 256, "127.0.0.1", TEST_SERVER_PORT, TEST_PROTOCOL_ID, _privateKey);
server.Start(false);
server.time = time;
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
ulong clientID = 1000;
byte[] userData = new byte[256];
KeyUtils.GenerateKey(userData);
byte[] connectToken = tokenFactory.GenerateConnectToken(new IPEndPoint[] { serverEndpoint }, time, TEST_CONNECT_TOKEN_EXPIRY, 5, 0, clientID, userData);
client.Connect(connectToken, false);
while (true)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
if (client.State <= ClientState.Disconnected)
break;
if (client.State == ClientState.Connected)
break;
}
assert(client.State == ClientState.Connected, "Client failed to connect: " + client.State);
// pump client and server long enough that they would timeout without keep-alive packets
int iterations = (int)Math.Ceiling(1.5 * Defines.NETCODE_TIMEOUT_SECONDS / dt);
for (int i = 0; i < iterations; i++)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
if (client.State <= ClientState.Disconnected)
break;
}
assert(client.State == ClientState.Connected, "Client disconnected: " + client.State);
client.Disconnect();
server.Stop();
}
public static void TestClientServerMultipleClients()
{
Console.WriteLine("TestClientServerMultipleClients");
int[] client_counts = new int[] { 2, 32, 5 };
int start_stop_iters = client_counts.Length;
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
Server server = new Server(socketMgr.CreateContext(serverEndpoint), 32, "127.0.0.1", TEST_SERVER_PORT, TEST_PROTOCOL_ID, _privateKey);
server.Start(false);
server.time = time;
ulong clientID = 1000UL;
ulong tokenSequence = 0UL;
for (int i = 0; i < start_stop_iters; i++)
{
Client[] clients = new Client[client_counts[i]];
for (int j = 0; j < clients.Length; j++)
{
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100 + j);
clients[j] = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
clients[j].time = time;
byte[] connectToken = tokenFactory.GenerateConnectToken(new IPEndPoint[] { serverEndpoint }, time,
30, 5, tokenSequence, clientID, new byte[256]);
clientID++;
tokenSequence++;
clients[j].Connect(connectToken, false);
}
var sw = new Stopwatch();
// make sure all clients can connect
while (true)
{
time += dt;
socketMgr.Update(time);
server.Tick(time);
foreach (Client c in clients)
c.Tick(time);
int numConnectedClients = 0;
bool disconnect = false;
foreach (Client c in clients)
{
if (c.State <= ClientState.Disconnected)
{
disconnect = true;
break;
}
if (c.State == ClientState.Connected)
numConnectedClients++;
}
if (disconnect)
break;
if (numConnectedClients == client_counts[i])
break;
}
foreach (Client c in clients)
assert(c.State == ClientState.Connected, "Some clients failed to connect (iteration " + i + ")");
// make sure all clients can exchange packets with the server
int[] clientPacketsReceived = new int[clients.Length];
int serverMessagesReceived = 0;
server.OnClientMessageReceived += (sender, payload, size) =>
{
// send message back to client
sender.SendPayload(payload, size);
serverMessagesReceived++;
};
for (int x = 0; x < clients.Length; x++)
{
int clientIDX = x;
clients[x].OnMessageReceived += (payload, size) =>
{
clientPacketsReceived[clientIDX]++;
};
}
// send messages until everybody's got at least 10 messages (or we hit iteration max)
for (int x = 0; x < 1000; x++)
{
time += dt;
foreach (Client c in clients)
c.Tick(time);
server.Tick(time);
socketMgr.Update(time);
foreach (Client c in clients)
{
byte[] testPayload = new byte[256];
c.Send(testPayload, testPayload.Length);
}
if (clientPacketsReceived.All(n => n >= 10) && serverMessagesReceived >= 10)
break;
}
assert(clientPacketsReceived.All(n => n >= 10) && serverMessagesReceived >= 10, "Packets failed to send");
foreach (Client c in clients)
c.Disconnect();
}
server.Stop();
}
public static void TestClientServerMultipleServers()
{
Console.WriteLine("TestClientServerMultipleServers");
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
Server server = new Server(socketMgr.CreateContext(serverEndpoint), 32, "127.0.0.1", TEST_SERVER_PORT, TEST_PROTOCOL_ID, _privateKey);
server.Start(false);
server.time = time;
IPEndPoint[] testServerEndpoints = new IPEndPoint[]
{
new IPEndPoint(IPAddress.Parse("10.10.10.10"), 1000),
new IPEndPoint(IPAddress.Parse("100.100.100.100"), 50000),
new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT),
};
byte[] connectToken = tokenFactory.GenerateConnectToken(testServerEndpoints, time, 30, 5, 1UL, 1000UL, new byte[256]);
client.Connect(connectToken, false);
while (true)
{
time += dt;
socketMgr.Update(time);
client.Tick(time);
server.Tick(time);
if (client.State <= ClientState.Disconnected)
break;
if (client.State == ClientState.Connected)
break;
}
assert(client.State == ClientState.Connected, "Client failed to connect: " + client.State);
int clientMessagesReceived = 0;
int serverMessagesReceived = 0;
server.OnClientMessageReceived += (sender, payload, size) =>
{
// send message back to client
sender.SendPayload(payload, size);
serverMessagesReceived++;
};
client.OnMessageReceived += (payload, size) =>
{
clientMessagesReceived++;
};
// send messages to the server until client and server have at least 10 messages each (or until we hit iteration max)
for (int i = 0; i < 1000; i++)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
byte[] testPayload = new byte[256];
client.Send(testPayload, testPayload.Length);
if (clientMessagesReceived >= 10 && serverMessagesReceived >= 10)
break;
}
assert(clientMessagesReceived >= 10 && serverMessagesReceived >= 10, "Sending messages failed!");
client.Disconnect();
server.Stop();
}
public static void TestConnectTokenExpired()
{
Console.WriteLine("TestConnectTokenExpired");
double time = 0.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
IPEndPoint[] testServerEndpoints = new IPEndPoint[]
{
new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT),
};
// token expires one second from when it is created
byte[] connectToken = tokenFactory.GenerateConnectToken(testServerEndpoints, time, 1, 1, 1UL, 1000UL, new byte[256]);
client.Connect(connectToken, false);
// advancing time by 10 seconds should immediately force token to expire
time += 10.0;
client.Tick(time);
assert(client.State == ClientState.ConnectTokenExpired, "Connect token failed to expire!");
}
public static void TestClientInvalidConnectToken()
{
Console.WriteLine("TestClientInvalidConnectToken");
double time = 0.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
IPEndPoint[] testServerEndpoints = new IPEndPoint[]
{
new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT),
};
// fill a connect token with random bytes
// this should cause the client to immediately fail with InvalidConnectToken
byte[] connectToken = new byte[2048];
KeyUtils.GenerateKey(connectToken);
client.Connect(connectToken, false);
assert(client.State == ClientState.InvalidConnectToken, "Client accepted invalid connect token");
}
public static void TestConnectionTimeout()
{
Console.WriteLine("TestConnectionTimeout");
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Server server = new Server(socketMgr.CreateContext(serverEndpoint), 256, "127.0.0.1", TEST_SERVER_PORT, TEST_PROTOCOL_ID, _privateKey);
server.Start(false);
server.time = time;
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
ulong clientID = 1000;
byte[] userData = new byte[256];
KeyUtils.GenerateKey(userData);
byte[] connectToken = tokenFactory.GenerateConnectToken(new IPEndPoint[] { serverEndpoint }, TEST_CONNECT_TOKEN_EXPIRY, 5, 0, clientID, userData);
client.Connect(connectToken, false);
while (true)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
if (client.State <= ClientState.Disconnected)
break;
if (client.State == ClientState.Connected)
break;
}
assert(client.State == ClientState.Connected, "Client failed to connect: " + client.State);
// now stop updating the server and run long enough that the client should disconnect
int iterations = (int)Math.Ceiling(1.5 * Defines.NETCODE_TIMEOUT_SECONDS / dt);
for (int i = 0; i < iterations; i++)
{
time += dt;
socketMgr.Update(time);
client.Tick(time);
if (client.State <= ClientState.Disconnected)
break;
}
assert(client.State == ClientState.ConnectionTimedOut, "Client failed to time out: " + client.State);
client.Disconnect();
server.Stop();
}
public static void TestChallengeResponseTimeout()
{
Console.WriteLine("TestChallengeResponseTimeout");
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;
TokenFactory tokenFactory = new TokenFactory(TEST_PROTOCOL_ID, _privateKey);
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT);
IPEndPoint clientEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), TEST_SERVER_PORT + 100);
Server server = new Server(socketMgr.CreateContext(serverEndpoint), 256, "127.0.0.1", TEST_SERVER_PORT, TEST_PROTOCOL_ID, _privateKey);
server.Start(false);
server.time = time;
// server should not respond to challenge response packets. this should make the client time out with ChallengeResponseTimedOut state
server.debugIgnoreChallengeResponse = true;
Client client = new Client((endpoint) =>
{
var socket = socketMgr.CreateContext(clientEndpoint);
socket.Bind(clientEndpoint);
return socket;
});
client.time = time;
ulong clientID = 1000;
byte[] userData = new byte[256];
KeyUtils.GenerateKey(userData);
byte[] connectToken = tokenFactory.GenerateConnectToken(new IPEndPoint[] { serverEndpoint }, TEST_CONNECT_TOKEN_EXPIRY, 5, 0, clientID, userData);
client.Connect(connectToken, false);
while (true)
{
time += dt;
client.Tick(time);
server.Tick(time);
socketMgr.Update(time);
if (client.State <= ClientState.Disconnected)
break;
if (client.State == ClientState.Connected)
break;
}
assert(client.State == ClientState.ChallengeResponseTimedOut, "Wrong client state (should be ChallengeResponseTimedOut): " + client.State);
client.Disconnect();
server.Stop();
}
public static void TestConnectionRequestTimeout()
{
Console.WriteLine("TestConnectionRequestTimeout");
double time = 0.0;
double dt = 1.0 / 10.0;
NetworkSimulatorSocketManager socketMgr = new NetworkSimulatorSocketManager();
socketMgr.LatencyMS = 250;
socketMgr.JitterMS = 250;
socketMgr.PacketLossChance = 5;
socketMgr.DuplicatePacketChance = 10;
socketMgr.AutoTime = false;