-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork.js
More file actions
3942 lines (3637 loc) · 143 KB
/
network.js
File metadata and controls
3942 lines (3637 loc) · 143 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
/*jslint node: true */
"use strict";
var bCordova = (typeof window === 'object' && window && window.cordova);
var WebSocket = bCordova ? global.WebSocket : require('ws');
var socks = bCordova ? null : require('socks');
var HttpsProxyAgent = bCordova ? null : require('https-proxy-agent');
var WebSocketServer = WebSocket.Server;
var crypto = require('crypto');
var _ = require('lodash');
var async = require('async');
var db = require('./db.js');
var constants = require('./constants.js');
var storage = require('./storage.js');
var myWitnesses = require('./my_witnesses.js');
var joint_storage = require('./joint_storage.js');
var validation = require('./validation.js');
var ValidationUtils = require("./validation_utils.js");
var writer = require('./writer.js');
var conf = require('./conf.js');
var mutex = require('./mutex.js');
var catchup = require('./catchup.js');
var privatePayment = require('./private_payment.js');
var objectHash = require('./object_hash.js');
var objectLength = require('./object_length.js');
var ecdsaSig = require('./signature.js');
var eventBus = require('./event_bus.js');
var light = require('./light.js');
var inputs = require('./inputs.js');
var breadcrumbs = require('./breadcrumbs.js');
var mail = require('./mail.js');
var aa_composer = require('./aa_composer.js');
var formulaEvaluation = require('./formula/evaluation.js');
var dataFeeds = require('./data_feeds.js');
var libraryPackageJson = require('./package.json');
var FORWARDING_TIMEOUT = 10*1000; // don't forward if the joint was received more than FORWARDING_TIMEOUT ms ago
var STALLED_TIMEOUT = 5000; // a request is treated as stalled if no response received within STALLED_TIMEOUT ms
var RESPONSE_TIMEOUT = 300*1000; // after this timeout, the request is abandoned
var HEARTBEAT_TIMEOUT = conf.HEARTBEAT_TIMEOUT || 10*1000;
var HEARTBEAT_RESPONSE_TIMEOUT = 60*1000;
var HEARTBEAT_PAUSE_TIMEOUT = 2*HEARTBEAT_TIMEOUT;
var MAX_STATE_VARS = 2000;
var wss;
var arrOutboundPeers = [];
var assocConnectingOutboundWebsockets = {};
var assocUnitsInWork = {};
var assocRequestedUnits = {};
var bStarted = false;
var bCatchingUp = false;
var bWaitingForCatchupChain = false;
var coming_online_time = Date.now();
var assocReroutedConnectionsByTag = {};
var arrWatchedAddresses = []; // does not include my addresses, therefore always empty
var arrTempWatchedAddresses = [];
var last_hearbeat_wake_ts = Date.now();
var peer_events_buffer = [];
var assocKnownPeers = {};
var assocBlockedPeers = {};
var exchangeRates = {};
var knownWitnesses = {};
var bWatchingForLight = false;
var prev_bugreport_hash = '';
let definitions = {}; // cache
let largeHistoryTags = {};
if (bCordova){ // browser
console.log("defining .on() on ws");
WebSocket.prototype.on = function(event, callback) {
var self = this;
if (event === 'message'){
this['on'+event] = function(event){
callback.call(self, event.data);
};
return;
}
if (event !== 'open'){
this['on'+event] = callback;
return;
}
// allow several handlers for 'open' event
if (!this['open_handlers'])
this['open_handlers'] = [];
this['open_handlers'].push(callback);
this['on'+event] = function(){
self['open_handlers'].forEach(function(cb){
cb();
});
};
};
WebSocket.prototype.once = WebSocket.prototype.on;
WebSocket.prototype.setMaxListeners = function(){};
}
// if not using a hub and accepting messages directly (be your own hub)
var my_device_address;
var objMyTempPubkeyPackage;
function setMyDeviceProps(device_address, objTempPubkey){
my_device_address = device_address;
objMyTempPubkeyPackage = objTempPubkey;
}
exports.light_vendor_url = null;
// general network functions
function sendMessage(ws, type, content) {
var message = JSON.stringify([type, content]);
if (ws.readyState !== ws.OPEN)
return console.log("readyState="+ws.readyState+' on peer '+ws.peer+', will not send '+message);
console.log("SENDING "+message+" to "+ws.peer);
if (bCordova) {
ws.send(message);
} else {
ws.send(message, function(err){
if (err)
ws.emit('error', 'From send: '+err);
});
}
}
function sendJustsayingToLightVendor(subject, body, handle){
if (!handle)
handle = function(){};
if (!conf.bLight)
return handle("sendJustsayingToLightVendor cannot be called as full node")
if (!exports.light_vendor_url){
console.log("light_vendor_url not set yet");
return setTimeout(function(){
sendJustsayingToLightVendor(subject, body, handle);
}, 1000);
}
findOutboundPeerOrConnect(exports.light_vendor_url, function(err, ws){
if (err)
return handle("connect to light vendor failed: "+err);
sendMessage(ws, 'justsaying', {subject: subject, body: body});
return handle(null);
});
}
function sendJustsaying(ws, subject, body){
sendMessage(ws, 'justsaying', {subject: subject, body: body});
}
function sendAllInboundJustsaying(subject, body){
wss.clients.forEach(function(ws){
sendMessage(ws, 'justsaying', {subject: subject, body: body});
});
}
function sendError(ws, error) {
sendJustsaying(ws, 'error', error);
}
function sendInfo(ws, content) {
sendJustsaying(ws, 'info', content);
}
function sendResult(ws, content) {
sendJustsaying(ws, 'result', content);
}
function sendErrorResult(ws, unit, error) {
sendResult(ws, {unit: unit, result: 'error', error: error});
}
function sendVersion(ws){
sendJustsaying(ws, 'version', {
protocol_version: constants.version,
alt: constants.alt,
library: libraryPackageJson.name,
library_version: libraryPackageJson.version,
program: conf.program,
program_version: conf.program_version
});
}
function sendResponse(ws, tag, response){
var command = ws.assocCommandsInPreparingResponse[tag];
delete ws.assocCommandsInPreparingResponse[tag];
sendMessage(ws, 'response', {tag: tag, command: command, response: response});
}
function sendErrorResponse(ws, tag, error) {
sendResponse(ws, tag, {error: error});
}
// if a 2nd identical request is issued before we receive a response to the 1st request, then:
// 1. its responseHandler will be called too but no second request will be sent to the wire
// 2. bReroutable flag must be the same
function sendRequest(ws, command, params, bReroutable, responseHandler){
var request = {command: command};
if (params)
request.params = params;
var content = _.clone(request);
var tag = objectHash.getBase64Hash(request, true);
//if (ws.assocPendingRequests[tag]) // ignore duplicate requests while still waiting for response from the same peer
// return console.log("will not send identical "+command+" request");
if (ws.assocPendingRequests[tag]){
console.log('already sent a '+command+' request to '+ws.peer+', will add one more response handler rather than sending a duplicate request to the wire');
ws.assocPendingRequests[tag].responseHandlers.push(responseHandler);
}
else{
content.tag = tag;
// after STALLED_TIMEOUT, reroute the request to another peer
// it'll work correctly even if the current peer is already disconnected when the timeout fires
var reroute = !bReroutable ? null : function(){
console.log('will try to reroute a '+command+' request stalled at '+ws.peer);
if (!ws.assocPendingRequests[tag])
return console.log('will not reroute - the request was already handled by another peer');
ws.assocPendingRequests[tag].bRerouted = true;
findNextPeer(ws, function(next_ws){ // the callback may be called much later if findNextPeer has to wait for connection
if (!ws.assocPendingRequests[tag])
return console.log('will not reroute after findNextPeer - the request was already handled by another peer');
if (next_ws === ws || assocReroutedConnectionsByTag[tag] && assocReroutedConnectionsByTag[tag].indexOf(next_ws) >= 0){
console.log('will not reroute '+command+' to the same peer, will rather wait for a new connection');
eventBus.once('connected_to_source', function(){ // try again
console.log('got new connection, retrying reroute '+command);
reroute();
});
return;
}
console.log('rerouting '+command+' from '+ws.peer+' to '+next_ws.peer);
ws.assocPendingRequests[tag].responseHandlers.forEach(function(rh){
sendRequest(next_ws, command, params, bReroutable, rh);
});
if (!assocReroutedConnectionsByTag[tag])
assocReroutedConnectionsByTag[tag] = [ws];
assocReroutedConnectionsByTag[tag].push(next_ws);
});
};
var reroute_timer = !bReroutable ? null : setTimeout(reroute, STALLED_TIMEOUT);
var cancel_timer = bReroutable ? null : setTimeout(function(){
ws.assocPendingRequests[tag].responseHandlers.forEach(function(rh){
rh(ws, request, {error: "[internal] response timeout"});
});
delete ws.assocPendingRequests[tag];
}, RESPONSE_TIMEOUT);
ws.assocPendingRequests[tag] = {
request: request,
responseHandlers: [responseHandler],
reroute: reroute,
reroute_timer: reroute_timer,
cancel_timer: cancel_timer
};
sendMessage(ws, 'request', content);
}
return tag;
}
function deletePendingRequest(ws, tag){
if (ws && ws.assocPendingRequests && ws.assocPendingRequests[tag]){
var pendingRequest = ws.assocPendingRequests[tag];
clearTimeout(pendingRequest.reroute_timer);
clearTimeout(pendingRequest.cancel_timer);
delete ws.assocPendingRequests[tag];
// if the request was rerouted, cancel all other pending requests
if (assocReroutedConnectionsByTag[tag]){
assocReroutedConnectionsByTag[tag].forEach(function(client){
if (client.assocPendingRequests[tag]){
clearTimeout(client.assocPendingRequests[tag].reroute_timer);
clearTimeout(client.assocPendingRequests[tag].cancel_timer);
delete client.assocPendingRequests[tag];
}
});
delete assocReroutedConnectionsByTag[tag];
}
return true;
}else{
return false;
}
}
function handleResponse(ws, tag, response){
var pendingRequest = ws.assocPendingRequests[tag];
if (!pendingRequest) // was canceled due to timeout or rerouted and answered by another peer
//throw "no req by tag "+tag;
return console.log("no req by tag "+tag);
pendingRequest.responseHandlers.forEach(function(responseHandler){
process.nextTick(function(){
responseHandler(ws, pendingRequest.request, response);
});
});
deletePendingRequest(ws, tag);
}
function cancelRequestsOnClosedConnection(ws){
console.log("websocket closed, will complete all outstanding requests");
for (var tag in ws.assocPendingRequests){
var pendingRequest = ws.assocPendingRequests[tag];
clearTimeout(pendingRequest.reroute_timer);
clearTimeout(pendingRequest.cancel_timer);
if (pendingRequest.reroute){ // reroute immediately, not waiting for STALLED_TIMEOUT
if (!pendingRequest.bRerouted)
pendingRequest.reroute();
// we still keep ws.assocPendingRequests[tag] because we'll need it when we find a peer to reroute to
}
else{
pendingRequest.responseHandlers.forEach(function(rh){
rh(ws, pendingRequest.request, {error: "[internal] connection closed"});
});
delete ws.assocPendingRequests[tag];
}
}
printConnectionStatus();
}
// peers
function findNextPeer(ws, handleNextPeer){
tryFindNextPeer(ws, function(next_ws){
if (next_ws)
return handleNextPeer(next_ws);
var peer = ws ? ws.peer : '[none]';
console.log('findNextPeer after '+peer+' found no appropriate peer, will wait for a new connection');
eventBus.once('connected_to_source', function(new_ws){
console.log('got new connection, retrying findNextPeer after '+peer);
findNextPeer(ws, handleNextPeer);
});
});
}
function tryFindNextPeer(ws, handleNextPeer){
var arrOutboundSources = arrOutboundPeers.filter(function(outbound_ws){ return outbound_ws.bSource; });
var len = arrOutboundSources.length;
if (len > 0){
var peer_index = arrOutboundSources.indexOf(ws); // -1 if it is already disconnected by now, or if it is inbound peer, or if it is null
var next_peer_index = (peer_index === -1) ? getRandomInt(0, len-1) : ((peer_index+1)%len);
handleNextPeer(arrOutboundSources[next_peer_index]);
}
else
findRandomInboundPeer(handleNextPeer);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max+1 - min)) + min;
}
function findRandomInboundPeer(handleInboundPeer){
var arrInboundSources = wss.clients.filter(function(inbound_ws){ return inbound_ws.bSource; });
if (arrInboundSources.length === 0)
return handleInboundPeer(null);
var arrInboundHosts = arrInboundSources.map(function(ws){ return ws.host; });
// filter only those inbound peers that are reversible
db.query(
"SELECT peer_host FROM peer_host_urls JOIN peer_hosts USING(peer_host) \n\
WHERE is_active=1 AND peer_host IN(?) \n\
AND (count_invalid_joints/count_new_good_joints<? \n\
OR count_new_good_joints=0 AND count_nonserial_joints=0 AND count_invalid_joints=0) \n\
ORDER BY (count_new_good_joints=0), "+db.getRandom()+" LIMIT 1",
[arrInboundHosts, conf.MAX_TOLERATED_INVALID_RATIO],
function(rows){
console.log(rows.length+" inbound peers");
if (rows.length === 0)
return handleInboundPeer(constants.bDevnet ? arrInboundSources[Math.floor(Math.random()*arrInboundSources.length)] : null);
var host = rows[0].peer_host;
console.log("selected inbound peer "+host);
var ws = arrInboundSources.filter(function(ws){ return (ws.host === host); })[0];
if (!ws)
throw Error("inbound ws not found");
handleInboundPeer(ws);
}
);
}
function checkIfHaveEnoughOutboundPeersAndAdd(){
var arrOutboundPeerUrls = arrOutboundPeers.map(function(ws){ return ws.peer; });
db.query(
"SELECT peer FROM peers JOIN peer_hosts USING(peer_host) \n\
WHERE (count_invalid_joints/count_new_good_joints<? \n\
OR count_new_good_joints=0 AND count_nonserial_joints=0 AND count_invalid_joints=0) \n\
AND peer IN(?)",
[conf.MAX_TOLERATED_INVALID_RATIO, (arrOutboundPeerUrls.length > 0) ? arrOutboundPeerUrls : null],
function(rows){
var count_good_peers = rows.length;
if (count_good_peers >= conf.MIN_COUNT_GOOD_PEERS)
return;
if (count_good_peers === 0) // nobody trusted enough to ask for new peers, can't do anything
return;
var arrGoodPeerUrls = rows.map(function(row){ return row.peer; });
for (var i=0; i<arrOutboundPeers.length; i++){
var ws = arrOutboundPeers[i];
if (arrGoodPeerUrls.indexOf(ws.peer) !== -1)
requestPeers(ws);
}
}
);
}
function connectToPeer(url, onOpen, dontAddPeer) {
if (!dontAddPeer)
addPeer(url);
var options = {};
if (socks && conf.socksHost && conf.socksPort) {
options.agent = new socks.Agent({
proxy: {
ipaddress: conf.socksHost,
port: conf.socksPort,
type: 5,
authentication: {
username: typeof conf.socksUsername === 'undefined' ? "dummy" : conf.socksUsername,
password: typeof conf.socksPassword === 'undefined' ? "dummy" : conf.socksPassword
}
}
}, /^wss/i.test(url));
console.log('Using socksHost: ' + conf.socksHost);
console.log('Using socksPort: ' + conf.socksPort);
console.log('Using socksUsername: ' + typeof conf.socksUsername === 'undefined' ? "dummy" : conf.socksUsername);
console.log('Using socksPassword: ' + typeof conf.socksPassword === 'undefined' ? "dummy" : conf.socksPassword);
} else if (HttpsProxyAgent && conf.httpsProxy) {
options.agent = new HttpsProxyAgent(conf.httpsProxy);
console.log('Using httpsProxy: ' + conf.httpsProxy);
}
var ws = options.agent ? new WebSocket(url,options) : new WebSocket(url);
assocConnectingOutboundWebsockets[url] = ws;
setTimeout(function(){
if (assocConnectingOutboundWebsockets[url]){
console.log('abandoning connection to '+url+' due to timeout');
delete assocConnectingOutboundWebsockets[url];
// after this, new connection attempts will be allowed to the wire, but this one can still succeed. See the check for duplicates below.
}
}, 5000);
ws.setMaxListeners(40); // avoid warning
ws.once('open', function onWsOpen() {
breadcrumbs.add('connected to '+url);
delete assocConnectingOutboundWebsockets[url];
ws.assocPendingRequests = {};
ws.assocCommandsInPreparingResponse = {};
if (!ws.url)
throw Error("no url on ws");
if (ws.url !== url && ws.url !== url + "/") // browser implementatin of Websocket might add /
throw Error("url is different: "+ws.url);
var another_ws_to_same_peer = getOutboundPeerWsByUrl(url);
if (another_ws_to_same_peer){ // duplicate connection. May happen if we abondoned a connection attempt after timeout but it still succeeded while we opened another connection
console.log('already have a connection to '+url+', will keep the old one and close the duplicate');
ws.close(1000, 'duplicate connection');
if (onOpen)
onOpen(null, another_ws_to_same_peer);
return;
}
ws.peer = url;
ws.host = getHostByPeer(ws.peer);
ws.bOutbound = true;
ws.last_ts = Date.now();
console.log('connected to '+url+", host "+ws.host);
arrOutboundPeers.push(ws);
sendVersion(ws);
if (conf.myUrl) // I can listen too, this is my url to connect to
sendJustsaying(ws, 'my_url', conf.myUrl);
if (!conf.bLight)
subscribe(ws);
if (onOpen)
onOpen(null, ws);
eventBus.emit('connected', ws);
eventBus.emit('open-'+url);
});
ws.on('close', function onWsClose() {
var i = arrOutboundPeers.indexOf(ws);
console.log('close event, removing '+i+': '+url);
if (i !== -1)
arrOutboundPeers.splice(i, 1);
cancelRequestsOnClosedConnection(ws);
if (options.agent && options.agent.destroy)
options.agent.destroy();
});
ws.on('error', function onWsError(e){
delete assocConnectingOutboundWebsockets[url];
console.log("error from server "+url+": "+e);
var err = e.toString();
// !ws.bOutbound means not connected yet. This is to distinguish connection errors from later errors that occur on open connection
if (!ws.bOutbound && onOpen)
onOpen(err);
if (!ws.bOutbound)
eventBus.emit('open-'+url, err);
});
ws.on('message', onWebsocketMessage);
console.log('connectToPeer done');
}
function addOutboundPeers(multiplier){
if (!multiplier)
multiplier = 1;
if (multiplier >= 32) // limit recursion
return;
var order_by = (multiplier <= 4) ? "count_new_good_joints DESC" : db.getRandom(); // don't stick to old peers with most accumulated good joints
var arrOutboundPeerUrls = arrOutboundPeers.map(function(ws){ return ws.peer; });
var arrInboundHosts = wss.clients.map(function(ws){ return ws.host; });
var max_new_outbound_peers = Math.min(conf.MAX_OUTBOUND_CONNECTIONS-arrOutboundPeerUrls.length, 5); // having too many connections being opened creates odd delays in db functions
if (max_new_outbound_peers <= 0)
return;
db.query(
"SELECT peer \n\
FROM peers \n\
JOIN peer_hosts USING(peer_host) \n\
LEFT JOIN peer_host_urls ON peer=url AND is_active=1 \n\
WHERE (count_invalid_joints/count_new_good_joints<? \n\
OR count_new_good_joints=0 AND count_nonserial_joints=0 AND count_invalid_joints=0) \n\
"+((arrOutboundPeerUrls.length > 0) ? "AND peer NOT IN("+arrOutboundPeerUrls.map(db.escape).join(', ')+") \n" : "")+"\n\
"+((arrInboundHosts.length > 0) ? "AND (peer_host_urls.peer_host IS NULL OR peer_host_urls.peer_host NOT IN("+arrInboundHosts.map(db.escape).join(', ')+")) \n" : "")+"\n\
AND peer_hosts.peer_host != 'uri' \n\
AND is_self=0 \n\
ORDER BY "+order_by+" LIMIT ?",
[conf.MAX_TOLERATED_INVALID_RATIO*multiplier, max_new_outbound_peers],
function(rows){
for (var i=0; i<rows.length; i++){
assocKnownPeers[rows[i].peer] = true;
findOutboundPeerOrConnect(rows[i].peer);
}
if (arrOutboundPeerUrls.length === 0 && rows.length === 0) // if no outbound connections at all, get less strict
addOutboundPeers(multiplier*2);
}
);
}
function getHostByPeer(peer){
var matches = peer.match(/^wss?:\/\/(.*)$/i);
if (matches)
peer = matches[1];
matches = peer.match(/^(.*?)[:\/]/);
return matches ? matches[1] : peer;
}
function addPeerHost(host, onDone){
db.query("INSERT "+db.getIgnore()+" INTO peer_hosts (peer_host) VALUES (?)", [host], function(){
if (onDone)
onDone();
});
}
function addPeer(peer){
if (assocKnownPeers[peer])
return;
assocKnownPeers[peer] = true;
var host = getHostByPeer(peer);
addPeerHost(host, function(){
console.log("will insert peer "+peer);
db.query("INSERT "+db.getIgnore()+" INTO peers (peer_host, peer) VALUES (?,?)", [host, peer]);
});
}
function getOutboundPeerWsByUrl(url){
console.log("outbound peers: "+arrOutboundPeers.map(function(o){ return o.peer; }).join(", "));
for (var i=0; i<arrOutboundPeers.length; i++)
if (arrOutboundPeers[i].peer === url)
return arrOutboundPeers[i];
return null;
}
function getPeerWebSocket(peer){
for (var i=0; i<arrOutboundPeers.length; i++)
if (arrOutboundPeers[i].peer === peer)
return arrOutboundPeers[i];
for (var i=0; i<wss.clients.length; i++)
if (wss.clients[i].peer === peer)
return wss.clients[i];
return null;
}
function getInboundDeviceWebSocket(device_address){
for (var i=0; i<wss.clients.length; i++){
if (wss.clients[i].device_address === device_address)
return wss.clients[i];
}
return null;
}
function findOutboundPeerOrConnect(url, onOpen, dontAddPeer){
if (!url)
throw Error('no url');
if (!onOpen)
onOpen = function(){};
if (!bStarted)
return onOpen("[internal] network not started yet");
url = url.toLowerCase();
var ws = getOutboundPeerWsByUrl(url);
if (ws)
return onOpen(null, ws);
// check if we are already connecting to the peer
ws = assocConnectingOutboundWebsockets[url];
if (ws){ // add second event handler
breadcrumbs.add('already connecting to '+url);
return eventBus.once('open-'+url, function secondOnOpen(err){
console.log('second open '+url+", err="+err);
if (err)
return onOpen(err);
if (ws.readyState === ws.OPEN)
onOpen(null, ws);
else{
// can happen e.g. if the ws was abandoned but later succeeded, we opened another connection in the meantime,
// and had another_ws_to_same_peer on the first connection
console.log('in second onOpen, websocket already closed');
onOpen('[internal] websocket already closed');
}
});
}
console.log("will connect to "+url);
connectToPeer(url, onOpen, dontAddPeer);
}
function purgePeerEvents(){
if (conf.storage !== 'sqlite')
return;
console.log('will purge peer events');
db.query("DELETE FROM peer_events WHERE event_date <= datetime('now', '-0.5 day')", function() {
console.log("deleted some old peer_events");
});
}
function purgeDeadPeers(){
if (conf.storage !== 'sqlite')
return;
console.log('will purge dead peers');
var arrOutboundPeerUrls = arrOutboundPeers.map(function(ws){ return ws.peer; });
db.query("SELECT rowid, "+db.getUnixTimestamp('event_date')+" AS ts FROM peer_events ORDER BY rowid DESC LIMIT 1", function(lrows){
if (lrows.length === 0)
return;
var last_rowid = lrows[0].rowid;
var last_event_ts = lrows[0].ts;
db.query("SELECT peer, peer_host FROM peers", function(rows){
async.eachSeries(rows, function(row, cb){
if (arrOutboundPeerUrls.indexOf(row.peer) >= 0)
return cb();
db.query(
"SELECT MAX(rowid) AS max_rowid, MAX("+db.getUnixTimestamp('event_date')+") AS max_event_ts FROM peer_events WHERE peer_host=?",
[row.peer_host],
function(mrows){
var max_rowid = mrows[0].max_rowid || 0;
var max_event_ts = mrows[0].max_event_ts || 0;
var count_other_events = last_rowid - max_rowid;
var days_since_last_event = (last_event_ts - max_event_ts)/24/3600;
if (count_other_events < 20000 || days_since_last_event < 7)
return cb();
console.log('peer '+row.peer+' is dead, will delete');
db.query("DELETE FROM peers WHERE peer=?", [row.peer], function(){
delete assocKnownPeers[row.peer];
cb();
});
}
);
});
});
});
}
function requestPeers(ws){
sendRequest(ws, 'get_peers', null, false, handleNewPeers);
}
function handleNewPeers(ws, request, arrPeerUrls){
if (arrPeerUrls.error)
return console.log('get_peers failed: '+arrPeerUrls.error);
if (!Array.isArray(arrPeerUrls))
return sendError(ws, "peer urls is not an array");
var arrQueries = [];
for (var i=0; i<arrPeerUrls.length; i++){
var url = arrPeerUrls[i];
if (conf.myUrl && conf.myUrl.toLowerCase() === url.toLowerCase())
continue;
var regexp = (conf.WS_PROTOCOL === 'wss://') ? /^wss:\/\// : /^wss?:\/\//;
if (!url.match(regexp)){
console.log('ignoring new peer '+url+' because of incompatible ws protocol');
continue;
}
var host = getHostByPeer(url);
if (host === 'uri')
continue;
db.addQuery(arrQueries, "INSERT "+db.getIgnore()+" INTO peer_hosts (peer_host) VALUES (?)", [host]);
db.addQuery(arrQueries, "INSERT "+db.getIgnore()+" INTO peers (peer_host, peer, learnt_from_peer_host) VALUES(?,?,?)", [host, url, ws.host]);
}
async.series(arrQueries);
}
function heartbeat(){
// just resumed after sleeping
var bJustResumed = (bCordova && Date.now() - last_hearbeat_wake_ts > HEARTBEAT_PAUSE_TIMEOUT);
last_hearbeat_wake_ts = Date.now();
wss.clients.concat(arrOutboundPeers).forEach(function(ws){
if (ws.bSleeping || ws.readyState !== ws.OPEN)
return;
var elapsed_since_last_received = Date.now() - ws.last_ts;
if (elapsed_since_last_received < HEARTBEAT_TIMEOUT)
return;
if (!ws.last_sent_heartbeat_ts || bJustResumed){
ws.last_sent_heartbeat_ts = Date.now();
return sendRequest(ws, 'heartbeat', null, false, handleHeartbeatResponse);
}
var elapsed_since_last_sent_heartbeat = Date.now() - ws.last_sent_heartbeat_ts;
if (elapsed_since_last_sent_heartbeat < HEARTBEAT_RESPONSE_TIMEOUT)
return;
console.log('will disconnect peer '+ws.peer+' who was silent for '+elapsed_since_last_received+'ms');
ws.close(1000, "lost connection");
});
}
function handleHeartbeatResponse(ws, request, response){
delete ws.last_sent_heartbeat_ts;
if (response === 'sleep') // the peer doesn't want to be bothered with heartbeats any more, but still wants to keep the connection open
ws.bSleeping = true;
// as soon as the peer sends a heartbeat himself, we'll think he's woken up and resume our heartbeats too
}
function requestFromLightVendor(command, params, responseHandler){
if (!responseHandler)
return new Promise((resolve, reject) => requestFromLightVendor(command, params, (ws, request, response) => response && response.error ? reject(response.error) : resolve(response)));
if (!exports.light_vendor_url){
console.log("light_vendor_url not set yet");
return setTimeout(function(){
requestFromLightVendor(command, params, responseHandler);
}, 1000);
}
findOutboundPeerOrConnect(exports.light_vendor_url, function(err, ws){
if (err)
return responseHandler(null, null, {error: "[connect to light vendor failed]: "+err});
sendRequest(ws, command, params, false, responseHandler);
});
}
function getConnectionStatus(){
return {
incoming: wss.clients.length,
outgoing: arrOutboundPeers.length,
outgoing_being_opened: Object.keys(assocConnectingOutboundWebsockets).length
}
}
function printConnectionStatus(){
var objConnectionStatus = getConnectionStatus();
console.log(objConnectionStatus.incoming+" incoming connections, "+objConnectionStatus.outgoing+" outgoing connections, "+
objConnectionStatus.outgoing_being_opened+" outgoing connections being opened");
}
function subscribe(ws){
ws.subscription_id = crypto.randomBytes(30).toString("base64"); // this is to detect self-connect
storage.readLastMainChainIndex(function(last_mci){
sendRequest(ws, 'subscribe', {subscription_id: ws.subscription_id, last_mci: last_mci, library_version: libraryPackageJson.version}, false, function(ws, request, response){
delete ws.subscription_id;
if (response.error)
return;
ws.bSource = true;
eventBus.emit('connected_to_source', ws);
});
});
}
// joints
// sent as justsaying or as response to a request
function sendJoint(ws, objJoint, tag) {
console.log('sending joint identified by unit ' + objJoint.unit.unit + ' to', ws.peer);
tag ? sendResponse(ws, tag, {joint: objJoint}) : sendJustsaying(ws, 'joint', objJoint);
}
// sent by light clients to their vendors
function postJointToLightVendor(objJoint, handleResponse) {
console.log('posting joint identified by unit ' + objJoint.unit.unit + ' to light vendor');
requestFromLightVendor('post_joint', objJoint, function(ws, request, response){
handleResponse(response);
});
}
function sendFreeJoints(ws) {
storage.readFreeJoints(function(objJoint){
sendJoint(ws, objJoint);
}, function(){
sendJustsaying(ws, 'free_joints_end', null);
});
}
function sendJointsSinceMci(ws, mci) {
joint_storage.readJointsSinceMci(
mci,
function(objJoint){
sendJoint(ws, objJoint);
},
function(){
sendJustsaying(ws, 'free_joints_end', null);
}
);
}
function requestFreeJointsFromAllOutboundPeers(){
for (var i=0; i<arrOutboundPeers.length; i++)
sendJustsaying(arrOutboundPeers[i], 'refresh', null);
}
function requestNewJoints(ws){
storage.readLastMainChainIndex(function(last_mci){
sendJustsaying(ws, 'refresh', last_mci);
});
}
function rerequestLostJoints(bForce){
//console.log("rerequestLostJoints");
if (bCatchingUp && !bForce)
return;
joint_storage.findLostJoints(function(arrUnits){
console.log("lost units", arrUnits.length > 0 ? arrUnits : 'none');
tryFindNextPeer(null, function(ws){
if (!ws)
return;
console.log("found next peer "+ws.peer);
requestJoints(ws, arrUnits.filter(function(unit){ return (!assocUnitsInWork[unit] && !havePendingJointRequest(unit)); }));
});
});
}
function requestNewMissingJoints(ws, arrUnits){
var arrNewUnits = [];
async.eachSeries(
arrUnits,
function(unit, cb){
if (assocUnitsInWork[unit])
return cb();
if (havePendingJointRequest(unit)){
console.log("unit "+unit+" was already requested");
return cb();
}
joint_storage.checkIfNewUnit(unit, {
ifNew: function(){
arrNewUnits.push(unit);
cb();
},
ifKnown: function(){console.log("known"); cb();}, // it has just been handled
ifKnownUnverified: function(){console.log("known unverified"); cb();}, // I was already waiting for it
ifKnownBad: function(error){
throw Error("known bad "+unit+": "+error);
}
});
},
function(){
//console.log(arrNewUnits.length+" of "+arrUnits.length+" left", assocUnitsInWork);
// filter again as something could have changed each time we were paused in checkIfNewUnit
arrNewUnits = arrNewUnits.filter(function(unit){ return (!assocUnitsInWork[unit] && !havePendingJointRequest(unit)); });
if (arrNewUnits.length > 0)
requestJoints(ws, arrNewUnits);
}
);
}
function requestJoints(ws, arrUnits) {
if (arrUnits.length === 0)
return;
arrUnits.forEach(function(unit){
if (assocRequestedUnits[unit]){
var diff = Date.now() - assocRequestedUnits[unit];
// since response handlers are called in nextTick(), there is a period when the pending request is already cleared but the response
// handler is not yet called, hence assocRequestedUnits[unit] not yet cleared
if (diff <= STALLED_TIMEOUT)
return console.log("unit "+unit+" already requested "+diff+" ms ago, assocUnitsInWork="+assocUnitsInWork[unit]);
// throw new Error("unit "+unit+" already requested "+diff+" ms ago, assocUnitsInWork="+assocUnitsInWork[unit]);
}
if (ws.readyState === ws.OPEN)
assocRequestedUnits[unit] = Date.now();
// even if readyState is not ws.OPEN, we still send the request, it'll be rerouted after timeout
sendRequest(ws, 'get_joint', unit, true, handleResponseToJointRequest);
});
}
function handleResponseToJointRequest(ws, request, response){
delete assocRequestedUnits[request.params];
if (!response.joint){
var unit = request.params;
if (response.joint_not_found === unit){
if (conf.bLight) // we trust the light vendor that if it doesn't know about the unit after 1 day, it doesn't exist
db.query("DELETE FROM unhandled_private_payments WHERE unit=? AND creation_date<"+db.addTime('-1 DAY'), [unit]);
if (!bCatchingUp)
return console.log("unit "+unit+" does not exist"); // if it is in unhandled_joints, it'll be deleted in 1 hour
// return purgeDependenciesAndNotifyPeers(unit, "unit "+unit+" does not exist");
db.query("SELECT 1 FROM hash_tree_balls WHERE unit=?", [unit], function(rows){
if (rows.length === 0)
return console.log("unit "+unit+" does not exist (catching up)");
// return purgeDependenciesAndNotifyPeers(unit, "unit "+unit+" does not exist (catching up)");
findNextPeer(ws, function(next_ws){
breadcrumbs.add("found next peer to reroute joint_not_found "+unit+": "+next_ws.peer);
requestJoints(next_ws, [unit]);
});
});
}
// if it still exists, we'll request it again
// we requst joints in two cases:
// - when referenced from parents, in this case we request it from the same peer who sent us the referencing joint,
// he should know, or he is attempting to DoS us
// - when catching up and requesting old joints from random peers, in this case we are pretty sure it should exist
return;
}
var objJoint = response.joint;
if (!objJoint.unit || !objJoint.unit.unit)
return sendError(ws, 'no unit');
var unit = objJoint.unit.unit;
if (request.params !== unit)
return sendError(ws, "I didn't request this unit from you: "+unit);
if (conf.bLight && objJoint.ball && !objJoint.unit.content_hash){
// accept it as unfinished (otherwise we would have to require a proof)
delete objJoint.ball;
delete objJoint.skiplist_units;
}
conf.bLight ? handleLightOnlineJoint(ws, objJoint) : handleOnlineJoint(ws, objJoint);
}
function havePendingRequest(command){
var arrPeers = wss.clients.concat(arrOutboundPeers);
for (var i=0; i<arrPeers.length; i++){
var assocPendingRequests = arrPeers[i].assocPendingRequests;
for (var tag in assocPendingRequests)
if (assocPendingRequests[tag].request.command === command)
return true;
}
return false;
}
function havePendingJointRequest(unit){
var arrPeers = wss.clients.concat(arrOutboundPeers);
for (var i=0; i<arrPeers.length; i++){
var assocPendingRequests = arrPeers[i].assocPendingRequests;
for (var tag in assocPendingRequests){
var request = assocPendingRequests[tag].request;
if (request.command === 'get_joint' && request.params === unit)
return true;
}
}
return false;
}
// We may receive a reference to a nonexisting unit in parents. We are not going to keep the referencing joint forever.
function purgeJunkUnhandledJoints(){
if (bCatchingUp || Date.now() - coming_online_time < 3600*1000 || wss.clients.length === 0 && arrOutboundPeers.length === 0)
return;
joint_storage.purgeOldUnhandledJoints();
}
function purgeJointAndDependenciesAndNotifyPeers(objJoint, error, onDone){
if (error.indexOf('is not stable in view of your parents') >= 0){ // give it a chance to be retried after adding other units
eventBus.emit('nonfatal_error', "error on unit "+objJoint.unit.unit+": "+error+"; "+JSON.stringify(objJoint), new Error());
// schedule a retry
console.log("will schedule a retry of " + objJoint.unit.unit);
setTimeout(function () {
console.log("retrying " + objJoint.unit.unit);
rerequestLostJoints(true);
joint_storage.readDependentJointsThatAreReady(null, handleSavedJoint);
}, 60 * 1000);
return onDone();
}
joint_storage.purgeJointAndDependencies(
objJoint,
error,
// this callback is called for each dependent unit
function(purged_unit, peer){
var ws = getPeerWebSocket(peer);
if (ws)
sendErrorResult(ws, purged_unit, "error on (indirect) parent unit "+objJoint.unit.unit+": "+error);
},
onDone
);
}
function purgeDependenciesAndNotifyPeers(unit, error, onDone){
joint_storage.purgeDependencies(
unit,
error,
// this callback is called for each dependent unit
function(purged_unit, peer){
var ws = getPeerWebSocket(peer);
if (ws)
sendErrorResult(ws, purged_unit, "error on (indirect) parent unit "+unit+": "+error);
},
onDone
);
}
function forwardJoint(ws, objJoint){
wss.clients.concat(arrOutboundPeers).forEach(function(client) {
if (client != ws && client.bSubscribed)
sendJoint(client, objJoint);
});
}
function handleJoint(ws, objJoint, bSaved, bPosted, callbacks){
if ('aa' in objJoint)
return callbacks.ifJointError("AA unit cannot be broadcast");
var unit = objJoint.unit.unit;
if (assocUnitsInWork[unit])
return callbacks.ifUnitInWork();
assocUnitsInWork[unit] = true;
var validate = function(){
mutex.lock(['handleJoint'], function(unlock){