-
Notifications
You must be signed in to change notification settings - Fork 0
/
dt.js
2624 lines (1950 loc) · 75.8 KB
/
dt.js
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
/*
MIT License
Copyright (c) 2022 Andrew Hodel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var crypto = require('crypto');
var net = require('net');
var events = require('events');
var ipac = require('./node-ip-ac/node-ip-ac.js');
var dt = function(config) {
// config {}
// master boolean one master node per dt
// port number port to listen on
// key string key to encrypt all traffic, common to all nodes
// nodes [string] list of IPv4 and IPv6 addresses of some public nodes
// timeout number timeout in milliseconds
// ping_interval number ping interval in milliseconds
var init_error = [];
if (typeof(config.master) !== 'boolean') {
config.master = false;
} else if (typeof(config.port) !== 'number') {
init_error.push('new dt(config), config.port must be a number with the udp port to listen on');
}
if (typeof(config.key) !== 'string') {
init_error.push('new dt(config), config.key must be a string of the key to encrypt all traffic with that is common to all nodes');
}
if (typeof(config.nodes) !== 'object') {
init_error.push('new dt(config), config.nodes must be an array of strings of IPv6 and IPv4 address:port of the nodes');
}
if (typeof(config.timeout) !== 'number') {
config.timeout = 7000;
}
if (typeof(config.ping_interval) !== 'number') {
config.ping_interval = 2000;
}
if (init_error.length > 0) {
console.error(init_error);
process.exit(1)
}
// configurable options
this.master = config.master;
this.port = Number(config.port);
this.key = Buffer.from(config.key);
this.timeout = Number(config.timeout);
this.ping_interval = Number(config.ping_interval);
// debug settings, each shows itself and all those below
// 0 no debugging output
// 1 print client nodes connected to server and primary client connections
// 2 print clean loop output and primary client selection output
// 3 print messages and what node they are from
this.debug = Number(config.debug);
var m = Buffer.from('this is how each message is encrypted, be careful of javascript variable references and ignore those who harass with lies');
// move this console.log() statement to line 80 to see why javascript references can be confusing while you are being harassed with lies and don't have pointers
//console.log('\nencrypting', m);
var enc = this.encrypt(m);
//console.log('encrypted', enc);
var dec = this.decrypt(enc);
//console.log('decrypted', dec);
// storage objects
this.primary_node = null;
this.nodes = [];
this.objects = [];
this.message_ids = [];
this.fragment_list = [];
// counters
this.active_test_count = 0;
// advanced/non configurable options
this.max_ping_count = 20;
// run the clean routing this often
this.clean_interval = 5000;
// send an object_hashes to other nodes this often
this.object_hashes_interval = 1000 * 60 * 5;
// if there is a better node to use as the primary, wait this long before disconnecting the existing primary client
this.better_primary_wait = 1000 * 60 * 20;
// a node with a latency lower than this * the primary node latency avg is classified as better
this.better_primary_latency_multiplier = .7;
// wait this long before purging nodes that are
// 1. unreachable
// 2. not updated in the fragment list
this.purge_node_wait = 1000 * 60 * 60;
// retest after a successful test at this interval
this.retest_wait_period = 1000 * 60 * 10;
// do not allow messages with a duplicate message_id more than this often
this.message_duplicate_expire = 1000 * 60 * 5;
// only defrag this often
this.defrag_wait_period = 1000 * 60 * 10;
var c = 0;
while (c < config.nodes.length) {
// build the nodes objects for the initial nodes
// initial nodes are servers that this node can connect to
var ip_port = config.nodes[c].split(':');
if (ip_port.length !== 2) {
console.error('node is missing IP and port', config.nodes[c]);
process.exit(1);
}
this.nodes.push({ip: ip_port[0], port: Number(ip_port[1]), is_self: false, origin_type: 'initial', primary_connection_failures: 0, node_id: null, rtt: -1, rtt_array: [], connected_as_primary: false, test_status: 'pending', test_failures: 0, last_ping_time: null, conn: undefined, test_count: 0, primary_client_connect_count: 0, defrag_count: 0, last_defrag: Date.now(), last_test_success: null, last_data_time: null});
c++;
}
// to prevent the node from connecting to itself
this.node_id = crypto.randomUUID();
this.ip_ac = ipac.init();
console.log('creating new dt node', this.port, this.node_id);
this.server = net.createServer(function(conn) {
// 'connection' listener.
// this is a new client
if (this.dt_object.debug >= 1) {
console.log('new client connected to server', conn.remoteAddress);
}
conn.on('close', function() {
if (this.dt_object.debug >= 1) {
console.log('client disconnected from server', conn.remoteAddress);
}
}.bind({dt_object: this.dt_object}));
conn.on('error', function(err) {
//console.error('client error', err);
});
if (ipac.test_ip_allowed(this.dt_object.ip_ac, conn.remoteAddress) === false) {
// this IP address has been blocked by node-ip-ac
if (this.dt_object.debug >= 1) {
console.log('client IP blocked when connecting to server', conn.remoteAddress);
}
conn.end();
return;
}
//console.log('client connected', conn.remoteAddress);
// create the client id
conn.client_id = crypto.randomUUID();
conn.node_connecting = true;
// make sure the open response has been received within the timeout
setTimeout(function() {
if (conn.node_connecting === true) {
// disconnect if the timeout is exceeded while connecting
if (this.dt_object.debug >= 1) {
console.log('client exceeded open timeout while connecting to server', conn.remoteAddress);
}
conn.end();
return;
}
}.bind({dt_object: this.dt_object}), this.dt_object.timeout);
// set the recv_msn
conn.recv_msn = 0;
var data = Buffer.alloc(0);
var data_len = 0;
var test_all_data = function() {
//console.log('server read test_all_data()', data_len, data.length);
if (data_len <= data.length) {
// decrypt the data_len
var decrypted = this.dt_object.decrypt(data.subarray(0, data_len));
//console.log('server decrypted read', decrypted.length, decrypted.toString());
try {
// decrypted is a valid message
var vm = JSON.parse(decrypted);
if (vm.node_id === this.dt_object.node_id) {
// tell the client that it connected to itself
this.dt_object.server_send(conn, {type: 'is_self', node_id: this.dt_object.node_id});
conn.end();
return;
}
/*
console.log('server received a message');
console.log('conn.recv_msn', conn.recv_msn);
console.log('vm.msn', vm.msn);
console.log('conn.client_id', conn.client_id);
console.log(vm);
*/
if (conn.recv_msn !== vm.msn) {
// disconnect if client is sending out of sequence
if (this.dt_object.debug >= 1) {
console.log('socket disconnected from main server by invalid message sequence number');
}
conn.end();
return;
} else if (vm.client_id !== conn.client_id && conn.recv_msn !== 0) {
// disconnect a different client_id after first message that sets the sequence number and client id before allowing any modifications
if (this.dt_object.debug >= 1) {
console.log('socket disconnected from main server by invalid client_id');
}
conn.end();
return;
}
// increment the recv_msn of the connection
conn.recv_msn++;
// type open is the first message
if (vm.type === 'open') {
// node is no longer connecting
conn.node_connecting = false;
// this is an authorized connection
ipac.modify_auth(this.dt_object.ip_ac, true, conn.remoteAddress);
// get the node ip address
var node_ip = this.dt_object.clean_remote_address(conn.remoteAddress);
//console.log(vm.listening_port + ' opened a client connection\n\n');
// set the node_id
var updated = false;
var c = 0;
while (c < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[c];
if (n.node_id === vm.node_id || (n.ip === node_ip && n.port === vm.listening_port)) {
// this is the node that connected
// update the conn object on the node
this.dt_object.nodes[c].conn = conn
// set the node object on conn
conn.node = this.dt_object.nodes[c];
// update the last_data_time
conn.node.last_data_time = Date.now();
// set the node_id
conn.node.node_id = vm.node_id;
updated = true;
break;
}
c++;
}
if (updated === false) {
// add new node to this.nodes
var i = this.dt_object.nodes.push({ip: node_ip, port: vm.listening_port, is_self: false, origin_type: 'client', primary_connection_failures: 0, node_id: vm.node_id, conn: conn, rtt: -1, rtt_array: [], connected_as_primary: false, test_status: 'pending', test_failures: 0, last_ping_time: null, test_count: 0, primary_client_connect_count: 0, defrag_count: 0, last_defrag: Date.now(), last_test_success: null, last_data_time: Date.now()});
conn.node = this.dt_object.nodes[i];
}
if (this.dt_object.debug >= 1) {
console.log('new client sent valid open message', conn.remoteAddress, 'node_id', conn.node.node_id, 'origin_type', conn.node.origin_type);
}
// after the local node entry has been updated with the node_id
// send an open response so the node's primary client can set the node_id
this.dt_object.server_send(conn, {type: 'open', node_id: this.dt_object.node_id});
var c = 0;
while (c < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[c];
if (n.node_id === vm.node_id || (n.ip === node_ip && n.port === vm.listening_port)) {
// this is this node
} else if (this.dt_object.node_connected(n) === true) {
// tell client nodes that a node connected with a distant_node message
this.dt_object.server_send(n.conn, {type: 'distant_node', ip: node_ip, port: vm.listening_port, node_id: vm.node_id});
}
c++;
}
// tell the server node that a node connected with a distant_node message
//console.log('sending distant_node to the server');
this.dt_object.client_send({type: 'distant_node', ip: node_ip, port: vm.listening_port, node_id: vm.node_id});
// send the known nodes as type: distant_node
// to the client that connected
var c = 0;
while (c < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[c];
if (n.connected_as_primary === true) {
// the primary client is connected to a server
} else if (n.node_id === vm.node_id || (n.ip === node_ip && n.port === vm.listening_port)) {
// this is the node that connected
} else {
this.dt_object.server_send(conn, {type: 'distant_node', ip: n.ip, port: n.port, node_id: n.node_id});
}
c++;
}
// the server sends the object hashes to clients regardless of having recieved the object_hashes
// because the object_hashes diff routine on the master node(s) will repeatedly create a
// remove_object message with the object hash until it is completely removed from the network
// send object_hashes
var o_hashes = [];
var n = 0;
while (n < this.dt_object.objects.length) {
// add the sha256 checksum to the array
o_hashes.push(this.dt_object.objects[n][0]);
n++;
}
this.dt_object.server_send(conn, {type: 'object_hashes', object_hashes: o_hashes});
} else {
// parse the message
this.dt_object.valid_server_message(conn, vm);
}
} catch (err) {
//console.error('error in server with a client authorization', err);
// if the decrypted message does not parse into JSON
// logout this ip in node-ip-ac
ipac.modify_auth(this.dt_object.ip_ac, undefined, conn.remoteAddress);
conn.end();
return;
}
// reset data
data = data.subarray(data_len, data.length);
//console.log('new data.length', data.length);
if (data.length > 0) {
// get length
data_len = data.readUInt32BE(0);
data = data.subarray(4);
test_all_data();
} else {
// no new data
// reset data_len
data_len = 0;
}
return;
}
// there was not enough data
return;
}.bind({dt_object: this.dt_object});
conn.on('data', function(chunk) {
try {
// update the last_data_time for the client node
if (conn.node !== undefined) {
conn.node.last_data_time = Date.now();
}
if (data_len === 0) {
// first chunk
if (chunk.length < 6) {
// the chunk is not long enough, it should be at least 4 bytes for the message length and at least 2 bytes for {}
// logout this ip in node-ip-ac
ipac.modify_auth(this.dt_object.ip_ac, undefined, conn.remoteAddress);
conn.end();
return;
}
// read length
data_len = chunk.readUInt32BE(0);
if (conn.recv_msn === 0) {
// this is the first message from a connection
// if more than 1000 bytes are sent
if (data_len > 1000 || data.length > 1000 || chunk.length > 1000) {
// logout this ip in node-ip-ac
ipac.modify_auth(this.dt_object.ip_ac, undefined, conn.remoteAddress);
// disconnect the socket
conn.end();
return;
}
}
//console.log('first chunk, data length', data_len);
// add to data without length
data = Buffer.concat([data, chunk.subarray(4)]);
test_all_data();
} else {
// continue to read through data_len
data = Buffer.concat([data, chunk]);
test_all_data();
}
} catch (err) {
//console.log('socket read error', err);
}
}.bind({dt_object: this.dt_object}));
}.bind({dt_object: this}));
this.server.on('error', function(err) {
// error
//console.error(err);
});
this.server.listen(this.port, function() {
//console.log('dt server bound', this.dt_object.port);
// lookup and connect to a node, first attempt after the server is successfully started
this.dt_object.connect();
// start clean routine
this.dt_object.clean();
this.dt_object.emitter.emit('started');
}.bind({dt_object: this}));
}
dt.prototype.connect = function() {
// short delay
var start = Date.now();
var waiter = setInterval(function() {
if (Date.now() - start < 1000 * 3) {
// wait 3 seconds to connect
return;
}
// the full 3 seconds has elapsed
// stop the waiter loop
clearInterval(waiter);
// connect to a node
if (this.dt_object.debug >= 2) {
console.log('primary client selection, total nodes', this.dt_object.nodes.length);
}
// find the node with the lowest primary_connection_failures
// this ensures that the primary connection is to a stable node
var lowest_primary_connection_failures = -1;
this.dt_object.primary_node = null;
var lowest_avg_rtt = -1;
var forced_connect = false;
var c = 0;
while (c < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[c];
if (n.force_connect === true) {
// force connect to this node
this.dt_object.primary_node = n;
// only force the connection once
n.force_connect = false;
forced_connect = true;
break;
}
var n_avg = this.dt_object.rtt_avg(n.rtt_array);
if (this.dt_object.debug >= 2) {
console.log('potential primary node to connect to', n.node_id, n.ip, n.port, 'primary_connection_failures', n.primary_connection_failures);
}
if (n.is_self === true) {
// do not attempt connection to self
if (this.dt_object.debug >= 2) {
console.log('\tpotential node skipped, is this node');
}
c++;
continue;
}
if (this.dt_object.node_connected(n) === true) {
// do not attempt connection to nodes that are already connected
// a connection object means the node is connected
if (this.dt_object.debug >= 2) {
console.log('\tpotential node skipped, already connected as client');
}
c++;
continue;
}
// finding the node with the lowest primary_connection_failures
if (n.primary_connection_failures < lowest_primary_connection_failures || lowest_primary_connection_failures === -1) {
this.dt_object.primary_node = n;
lowest_avg_rtt = n_avg;
lowest_primary_connection_failures = n.primary_connection_failures;
//console.log('better primary node selection against primary_connection_failures');
}
c++;
}
if (forced_connect === false) {
// this.dt_object.primary_node has the lowest primary_connection_failures
// test the nodes that equal the primary_connection_failures count
// and choose the one with the lowest avg rtt
// this ensures that the primary connection is stable and has a low round trip time
var r = 0;
while (r < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[r];
var n_avg = this.dt_object.rtt_avg(n.rtt_array);
//console.log('test primary node against average rtt', n.node_id, n.ip, n.port, n_avg);
if (n.is_self === true) {
// skip self nodes
} else if (isNaN(n_avg)) {
// skip nodes with no average rtt
//console.log('\tskipped with no average rtt');
} else if (n.primary_connection_failures > lowest_primary_connection_failures) {
// skip nodes that have more primary_connection failures
//console.log('\tskipped per more primary_connection_failures than lowest');
} else if (n_avg < lowest_avg_rtt) {
// there is a node with better latency
this.dt_object.primary_node = n;
lowest_avg_rtt = n_avg;
//console.log('better primary node selection against average rtt', n.node_id);
}
r++;
}
}
if (this.dt_object.primary_node === null) {
// this node has no nodes to connect to
// it should stay on to allow nodes to connect to it
if (this.dt_object.debug >= 2) {
console.log('primary client connect, no nodes ready for connection');
}
// lookup the best node again
this.dt_object.connect();
// end this connect/lookup loop
return;
}
if (this.dt_object.debug >= 1) {
console.log('primary client connect', this.dt_object.primary_node.ip, this.dt_object.primary_node.port, this.dt_object.primary_node.node_id, 'primary_connection_failures: ' + this.dt_object.primary_node.primary_connection_failures, 'average rtt: ' + this.dt_object.rtt_avg(this.dt_object.primary_node.rtt_array));
}
// ping the server
var primary_client_ping;
var primary_client_send_object_hashes;
this.dt_object.primary_node.object_hashes_received = false;
this.dt_object.primary_node.primary_client_connect_count++;
// set data_since_last_pong
this.dt_object.primary_node.data_since_last_pong = 0;
this.dt_object.primary_node.messages_since_last_pong = 0;
// set last_test_success to null so the node isn't disconnected for not being tested
this.dt_object.primary_node.last_test_success = null;
this.dt_object.client = net.connect({port: this.dt_object.primary_node.port, host: this.dt_object.primary_node.ip, keepAlive: false}, function() {
// 'connect' listener.
//console.log('primary client connected to', this.dt_object.primary_node.ip, this.dt_object.primary_node.port, this.dt_object.primary_node.node_id);
// set last_data_time
this.dt_object.primary_node.last_data_time = Date.now();
this.dt_object.client.node_connecting = true;
// make sure the open response has been received within the timeout
this.dt_object.client_connected_check = setTimeout(function() {
if (this.dt_object.client.node_connecting === true) {
// the node has not finished connecting within the timeout
// increment primary_connection_failures
this.dt_object.primary_node.primary_connection_failures += 3;
// disconnect if untrue
this.dt_object.client.end();
return;
}
// the node connected within the timeout
}.bind({dt_object: this.dt_object}), this.dt_object.timeout);
// send node_id
this.dt_object.client_send({type: 'open', node_id: this.dt_object.node_id, listening_port: this.dt_object.port});
}.bind({dt_object: this.dt_object}));
this.dt_object.client.on('close', function() {
// stop pinging
clearInterval(primary_client_ping);
clearInterval(primary_client_send_object_hashes);
this.dt_object.primary_node.connected_as_primary = false;
if (this.dt_object.debug >= 1) {
console.log('primary client disconnected from server node', this.dt_object.primary_node.ip, this.dt_object.primary_node.port, this.dt_object.primary_node.node_id);
}
// clear the client_connected_check to allow a new one with a reconnect
clearInterval(this.dt_object.client_connected_check);
this.dt_object.client_connected_check = undefined;
// reconnect to the network with a fresh node lookup
this.dt_object.connect();
}.bind({dt_object: this.dt_object}));
this.dt_object.client.on('timeout', function() {
//console.error('primary client timeout', this.dt_object.primary_node.ip, this.dt_object.primary_node.port, this.dt_object.primary_node.node_id);
this.dt_object.primary_node.connected_as_primary = false;
// a connection timeout is a failure
this.dt_object.primary_node.primary_connection_failures += 3;
}.bind({dt_object: this.dt_object}));
this.dt_object.client.on('error', function(err) {
//console.error('primary client socket error', this.dt_object.primary_node.ip, this.dt_object.primary_node.port, this.dt_object.connect.node_id, err.toString());
this.dt_object.primary_node.connected_as_primary = false;
// a connection error is a failure
this.dt_object.primary_node.primary_connection_failures += 3;
}.bind({dt_object: this.dt_object}));
// set the start time of this connection
this.dt_object.primary_node.primary_connection_start = Date.now();
// set client timeout of the socket
this.dt_object.client.setTimeout(this.dt_object.timeout);
// set the recv_msn
this.dt_object.client.recv_msn = 0;
var data = Buffer.alloc(0);
var data_len = 0;
var test_all_data = function() {
//console.log('primary client read test_all_data()', data_len, data.length);
if (data_len <= data.length) {
// decrypt the data_len
var decrypted = this.dt_object.decrypt(data.subarray(0, data_len));
//console.log('primary client decrypted read', decrypted.length, decrypted.toString());
try {
// decrypted is a valid message
var vm = JSON.parse(decrypted);
// update the client_id (socket id) sent from the server
//console.log('primary client response with client_id', vm.client_id);
this.dt_object.client.client_id = vm.client_id;
if (this.dt_object.client.recv_msn !== vm.msn) {
// increment primary_connection_failures
this.dt_object.primary_node.primary_connection_failures += 3;
// disconnect per out of sequence msn
//console.log('disconnecting from server per out of sequence msn');
this.dt_object.client.end();
return;
}
this.dt_object.client.recv_msn++;
// type: 'open' is the response to the sent type: 'open' message
// when there is a valid connection
if (vm.type === 'open') {
// set the node_id
this.dt_object.primary_node.node_id = vm.node_id;
// set connecting = false on the client
this.dt_object.client.node_connecting = false;
if (this.dt_object.primary_node.primary_connection_failures > 0) {
// a successful open response to the primary client should decrement the primary_connection_failures
// if it isn't already perfect
this.dt_object.primary_node.primary_connection_failures--;
}
primary_client_send_object_hashes = setInterval(function() {
// if multiple master nodes exist, they must be synchronized before
// allowing the master nodes to send their objects
// they cannot diff because they have no concept of origin time as they could be thousands of years
// between message and response while using a different origin time zone and not originating from unix time (random message from unknown source with shared key)
//
// this is also why origin timestamps are not that useful when you have relative locations
// no reason to keep the origin time of every ship (or the memory)
// no reason to know the origin time of a ship between two planets each with their own origin time
// if you have a historical record of their relative locations
//
// packetized data reception and decoding is slowed by particles
// every on/off stream/laser can be overwritten preventing moving the binary stream from packet data to parallel laser beams
// because the timing cannot be reputable
//
// time exists, but you won't know the origin time (universally applicable) until you have the bounds of the universe to measure upon and room to store the locations of each object
// you can always use the node-distributed-table fragment routine to figure out part of it though
// https://github.com/andrewhodel/node-distributed-table/issues/2
//
// or maybe everything in the universe will use seconds forever, it's still a problem of origin time at large distances
// with many devices because of the maintainence nightmare that is upgrading atomic clocks
// you could modify add_object() to save all the data and be able to diff between master nodes, but then you would turn life into data
// by needing infinite hard drive space, until the bounds of the universe are defined
if (this.dt_object.primary_node.object_hashes_received === true || this.dt_object.master === true) {
// the object_hashes have been received or this node is a master, continue
} else {
// wait another iteration
// non master nodes shall wait until the object hashes are received
//console.log('primary client waiting to send object_hashes to server until recieved');
return;
}
// send object_hashes
var o_hashes = [];
var n = 0;
while (n < this.dt_object.objects.length) {
// add the sha256 checksum to the array
o_hashes.push(this.dt_object.objects[n][0]);
n++;
}
this.dt_object.client_send({type: 'object_hashes', object_hashes: o_hashes});
clearInterval(primary_client_send_object_hashes);
}.bind({dt_object: this.dt_object}), 200);
// start to ping the server
primary_client_ping = setInterval(function() {
this.dt_object.client_send({type: 'ping', node_id: this.dt_object.node_id, ts: Date.now(), previous_rtt: this.dt_object.primary_node.rtt});
}.bind({dt_object: this.dt_object}), this.dt_object.ping_interval);
// send the connected nodes
var cn = [];
var c = 0;
while (c < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[c];
if (n.connected_as_primary === true) {
// the primary client is connected to a server
} else if (this.dt_object.node_connected(n) === true) {
cn.push({ip: n.ip, port: n.port, node_id: n.node_id});
}
c++;
}
this.dt_object.client_send({type: 'connected_nodes', node_id: this.dt_object.node_id, connected_nodes: cn});
} else {
// parse the message
this.dt_object.valid_primary_client_message(vm);
}
} catch (err) {
console.error('error in primary client authorization to server', err);
console.error('decrypted input data', decrypted);
return;
}
// reset data
data = data.subarray(data_len, data.length);
//console.log('new data.length', data.length);
if (data.length > 0) {
// get length
data_len = data.readUInt32BE(0);
data = data.subarray(4);
test_all_data();
} else {
// no new data
// reset data_len
data_len = 0;
}
return;
}
// there was not enough data
return;
}.bind({dt_object: this.dt_object});
this.dt_object.client.on('data', function(chunk) {
try {
// update the last_data_time for the primary node
this.dt_object.primary_node.last_data_time = Date.now();
if (data_len === 0) {
// first chunk
// read length
data_len = chunk.readUInt32BE(0);
//console.log('first chunk, data length', data_len);
// add to data without length
data = Buffer.concat([data, chunk.subarray(4)]);
test_all_data();
} else {
// continue to read through data_len
data = Buffer.concat([data, chunk]);
test_all_data();
}
} catch (err) {
//console.log('socket read error', err);
}
}.bind({dt_object: this.dt_object}));
}.bind({dt_object: this}), 200);
}
dt.prototype.rtt_avg = function(r) {
if (r === undefined) {
return -1;
}
var sum = 0;
var c = 0;
while (c < r.length) {
sum += r[c];
c++;
}
return sum / c;
}
dt.prototype.test_node = function(node) {
//console.log('testing node', node);
node.test_start = Date.now();
node.test_status = 'current';
node.test_count++;
// distant node ping
var ping;
var received_pings = 0;
var client = net.connect({port: node.port, host: node.ip, keepAlive: false}, function() {
// 'connect' listener.
//console.log('test_node() connected', node.ip, node.port);
// send the connected nodes
var cn = [];
var c = 0;
while (c < this.dt_object.nodes.length) {
var n = this.dt_object.nodes[c];
if (n.connected_as_primary === true) {
// the primary client is connected to a server
} else if (this.dt_object.node_connected(n) === true) {
cn.push({ip: n.ip, port: n.port, node_id: n.node_id});
}
c++;
}
this.dt_object.client_send({type: 'connected_nodes', node_id: this.dt_object.node_id, connected_nodes: cn}, client);
// ping the server
// and send the previous rtt
ping = setInterval(function() {
// send with this node's node_id
this.dt_object.client_send({type: 'test_ping', node_id: this.dt_object.node_id, ts: Date.now(), previous_rtt: node.rtt}, client);
}.bind({dt_object: this.dt_object}), this.dt_object.ping_interval);
}.bind({dt_object: this}));
client.on('close', function() {
// stop pinging
clearInterval(ping);
this.dt_object.active_test_count--;
//console.log('disconnected from node in test_node()', node.ip, node.port, node.node_id);
}.bind({dt_object: this}));
client.on('timeout', function() {
//console.error('timeout connecting to node in test_node()', node.ip, node.port, node.node_id);
node.test_status = 'failed';
node.test_failures++;
}.bind({dt_object: this}));
client.on('error', function(err) {
//console.error('error connecting to node in test_node()', node.ip, node.port, node.node_id, err.toString());
node.test_status = 'failed';
node.test_failures++;
}.bind({dt_object: this}));
// increment the active test count
this.active_test_count++;
// set client timeout of the socket
client.setTimeout(this.timeout);
// set the recv_msn
client.recv_msn = 0;
var data = Buffer.alloc(0);
var data_len = 0;
var test_all_data = function() {
//console.log('test client read test_all_data()', data_len, data.length);
if (data_len <= data.length) {