-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
710 lines (531 loc) · 15.5 KB
/
server.js
File metadata and controls
710 lines (531 loc) · 15.5 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
/**
* Imports
*/
import { WebSocketServer } from 'ws';
import { WebSocket } from 'ws';
import fs from 'fs';
import * as RATE_LIMIT from "./serverlibs/ratelimit.js"
import * as UTILS from "./serverlibs/serverutils.js"
/**
* Defauilt parameters
*/
var DEBUG_LOGS = false;
var DEBUG_SHORT = false;
var SERVER_PORT = 8081;
var MAX_TRADES = 1000;
var MAX_USER_ORDERS = 50;
var TRADES_FILE = "./trades.json";
var RATELIMIT_FILE = "./ratelimit.json";
var MEG_CHECK_TRADES = false;
var MEG_SERVER = "127.0.0.1";
var MEG_PORT = 8080;
var MEG_USERPASS = "apicaller:apicaller";
/**
* Command line params..
*/
const args = process.argv;
for(var c=0;c<args.length;c++){
var param = args[c];
if(param == "-help"){
console.log("Usage parameters : ");
console.log("-port [port] : Set the port to listen on");
console.log("-megserver [user:password@host:port] : Specify a MEG server to check trades");
console.log("-tradesfile [file] : Set the file to store trades");
console.log("-ratesfile [file] : Set the file to store rate limit data");
console.log("-maxtrades [maxtrades] : Max trades to store in file");
console.log("-debug : Show debug output");
console.log("-debugshort : Show shorter debug output");
console.log("-help : Show this help");
//And exit
process.exit();
}else if(param == "-debug"){
DEBUG_LOGS = true;
}else if(param == "-debugshort"){
DEBUG_LOGS = true;
DEBUG_SHORT = true;
}else if(param == "-tradesfile"){
c++;
TRADES_FILE = args[c];
}else if(param == "-ratesfile"){
c++;
RATELIMIT_FILE = args[c];
}else if(param == "-maxtrades"){
c++;
MAX_TRADES = +args[c];
}else if(param == "-megserver"){
c++;
var megserver = args[c];
//Break it down into the components
var at = megserver.indexOf("@");
MEG_USERPASS = megserver.substring(0,at);
var hostport = megserver.substring(at+1);
at = hostport.indexOf(":");
MEG_SERVER = hostport.substring(0,at);
MEG_PORT = +hostport.substring(at+1);
MEG_CHECK_TRADES = true;
if(DEBUG_LOGS){
console.log("MEG_USER : "+MEG_USERPASS);
console.log("MEG_SERVER : "+MEG_SERVER);
console.log("MEG_PORT : "+MEG_PORT);
}
}else if(param == "-port"){
c++;
SERVER_PORT = +args[c];
}
}
//Output some info
console.log('DEX server is running on port '+SERVER_PORT);
console.log('Trades are stored in file '+TRADES_FILE);
console.log('MAX Trades to store '+MAX_TRADES);
if(DEBUG_LOGS){
console.log('DEBUG logs are ON');
}else{
console.log('DEBUG logs are OFF');
}
//Create a WebSocket Server
const server = new WebSocketServer({
port: SERVER_PORT
});
//The set of all clients
const clients = new Set();
//All the Client orderbooks
var orderbooks = {};
//All the Trades
var alltrades = [];
//Last few Chat messages..
var allchat = [];
//Run a function on exit
process.on("SIGINT", function(){
process.exit(0);
});
process.on("SIGTERM", function(){
process.exit(0);
});
process.on("exit", function(){
shutdown();
});
function shutdown(){
console.log("Running shutdown function..");
//Try and write this..
try{
console.log("Save trades file..");
fs.writeFileSync(TRADES_FILE, JSON.stringify(alltrades));
console.log("Save rate limit data..");
RATE_LIMIT.saveRateLimitData(RATELIMIT_FILE);
}catch(Error){
console.log("Error writing files.. : "+Error)
}
}
//What to do on connections
server.on('connection', (socket) => {
//Set a unique ID
socket.id = UTILS.getRandomHexString();
if(DEBUG_LOGS){
console.log("New Connection.. "+socket.id);
}
//We still have to receive the FIRST message
socket.firstmessage = false;
//Add client to our list
clients.add(socket);
//Create an init message
var init = {};
init.trades = alltrades;
init.orderbooks = orderbooks;
init.chat = allchat;
//Tell the user their uuid and the current orderbooks
socket.send(createCustomMsg(socket.id,"init_dex",init));
//On receive message
socket.on('message', (message) => {
try{
//Get the message
var strmsg = `${message}`;
//Get the JSON version
var msgjson = JSON.parse(strmsg);
//Get the UUID
var uuid = msgjson.uuid;
if(!uuid){
//Incorrect message format
//console.log("MISSING UUID from:"+socket.id);
return;
}else{
//console.log("MESSAGE UUID from:"+socket.id+" UUID:"+uuid);
}
//Blank uuid.. as not to share
msgjson.uuid = "0xFF";
if(DEBUG_LOGS){
if(msgjson.type != "ping"){
if(DEBUG_SHORT){
console.log("Message from:"+socket.id+" msg:"+strmsg.substring(0,20)+"..");
}else{
console.log("Message from:"+socket.id+" msg:"+strmsg);
}
}
}
//Check if the User is in the SIN BIN (ping allowed)
if(msgjson.type != "ping"){
//Check for User
if(!RATE_LIMIT.checkForUser(uuid)){
//Add this User to the Rate Limiter
RATE_LIMIT.addRLUser(uuid);
//NEW users automatically go in SIN BIN..
sinbin(uuid, socket, "As a NEW USER you are not allowed to send messages for 5 minutes..");
socket.firstmessage = true;
return;
}else if(RATE_LIMIT.checkSinBin(uuid)){
console.log("SINBIN Message ignored from:"+socket.id+" msg:"+msgjson.type);
//Is this the FIRST message
if(!socket.firstmessage){
socket.firstmessage = true;
console.log("Send sinbin message to User "+uuid);
//Tell the user to refresh in 10 minutes..
var rateobj = {};
rateobj.uuid = "0x000000";
rateobj.message = "YOU HAVE EXCEEDED THE MESSAGE RATE LIMIT! (..you are in the SIN BIN for 5 minutes)";
//Send them a message..
socket.send(createCustomMsg("0x00","ratelimit",rateobj));
}
return;
}else if(!RATE_LIMIT.newValidRLMessage(uuid)){
//EXCEEDED..! add to SIN BIN
sinbin(uuid, socket, "YOU HAVE EXCEEDED THE MESSAGE RATE LIMIT! (..added to SIN BIN for 5 minutes)");
try{
//wipe their orders.. they refresh in 10 minutes
var sinorderbook = orderbooks[socket.id];
sinorderbook.orders = [];
//Broadcast this new empty book..
broadcast(createCustomMsg(socket.id,"update_orderbook",sinorderbook));
}catch(err){
}
return;
}
}
//We have now received the first message
socket.firstmessage = true;
//What message type is it..
if(msgjson.type == "chat"){
if(msgjson.data.trim() != ""){
//Broadcast to all..
newChat(socket.id, msgjson);
}
}else if(msgjson.type=="update_orderbook"){
//Get the orderbook
var orderbook = msgjson.data;
//Check is a valid book
if(!checkOrderBookMessage(orderbook)){
console.log("Invalid orderbook received.. "+JSON.stringify(orderbook));
var err = {};
err.type = "INVALID_ORDER";
err.message = "You have sent an invalid orderbook! MAX ("+MAX_USER_ORDERS+")";
//Send them a message..
socket.send(createCustomMsg("0x00","error","You have sent an invalid orderbook! MAX ("+MAX_USER_ORDERS+")"));
return;
}
//Add to our total list
orderbooks[socket.id] = orderbook;
//Broadcast this..
broadcast(createCustomMsg(socket.id,"update_orderbook",orderbook));
}else if(msgjson.type=="update_addorder"){
//Remove this order - so server has correct book for User
addOrder(socket.id, msgjson.data);
//Broadcast this..
broadcast(createCustomMsg(socket.id,"update_addorder",msgjson.data));
}else if(msgjson.type=="update_removeorder"){
//Remove this order - so server has correct book for User
removeOrder(socket.id, msgjson.data);
//Broadcast this..
broadcast(createCustomMsg(socket.id,"update_removeorder",msgjson.data));
}else if(msgjson.type=="refresh"){
//Create an init message
var init = {};
init.trades = alltrades;
init.orderbooks = orderbooks;
init.chat = allchat;
//Tell the user their uuid and the current orderbooks
socket.send(createCustomMsg(socket.id,"init_dex",init));
}else if(msgjson.type=="message"){
//Get the User..
sendToUser(socket.id, msgjson.data.uuid, msgjson.data.message);
}else if(msgjson.type=="trade"){
//There has been a trade
var trade = msgjson.data;
//NOT checked yet
trade.checkuid = UTILS.getRandomHexString();
trade.checked = false;
trade.checking = MEG_CHECK_TRADES;
if(MEG_CHECK_TRADES){
//Add to our check list
addCheckTrade(trade);
}else{
//Add it to our list
addTrade(trade);
}
//Broadcast
broadcast(createCustomMsg("0x00","trade",trade));
}else if(msgjson.type=="ping"){
//Send back a pong message
socket.send(createCustomMsg("0x00","pong",{}));
}else{
console.log("Unknown message type :"+msgjson.type+" msg:"+strmsg);
}
}catch(Error){
console.log("Error onmessage from:"+socket.id+" error:"+Error);
}
});
//On Close connection
socket.on('close', () => {
if(DEBUG_LOGS){
console.log(`Connection Closed: `+socket.id);
}
try{
//remove from our client list
clients.delete(socket);
//Delete the orderbook
delete orderbooks[socket.id];
//Tell all the clients..
broadcast(createCustomMsg(socket.id,"closed",""));
}catch(Error){
console.log("Error onclose from:"+socket.id+" error:"+Error);
}
});
});
//Read in the trades..
try {
// Read file synchronously
const data = fs.readFileSync(TRADES_FILE, 'utf8');
//Convert
alltrades = JSON.parse(data);
var tradelen = alltrades.length;
console.log("Trades found : "+tradelen);
//Check size..
if(tradelen > MAX_TRADES){
console.log("Trimming Trades to MAX : "+MAX_TRADES);
var starttrade = tradelen-MAX_TRADES;
var newarr = [];
for(var i=0;i<MAX_TRADES;i++){
var trade = alltrades[starttrade + i];
newarr.push(trade);
}
//Set this..
alltrades = newarr;
}
} catch (err) {
//File not found.. first time running..
console.error('No Trades found.. yet..');
}
//Load in the Rate limit..
RATE_LIMIT.loadRateLimitData(RATELIMIT_FILE);
/**
* UTILITY FUNCTIONS
*/
//Broadcast a message
function broadcast(str){
if(DEBUG_LOGS){
if(DEBUG_SHORT){
console.log("Broadcast > "+str.substring(0,20)+"..");
}else{
console.log("Broadcast > "+str);
}
}
//Cycle through all the clients
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
try{
client.send(str);
}catch(Error){
console.log("Error send to:"+client.id+" error:"+Error);
}
}
});
}
//Broadcast a message
function sendToUser(from, to, data){
//Create the message
var msg = createCustomMsg(from, "message", data);
if(DEBUG_LOGS){
if(DEBUG_SHORT){
console.log("Send To "+to+"> "+msg.substring(0,20)+"..");
}else{
console.log("Send To "+to+"> "+msg);
}
}
//Cycle through all the clients
var found = false;
clients.forEach((client) => {
if (!found && client.id==to && client.readyState === WebSocket.OPEN) {
try{
client.send(msg);
found = true;
}catch(Error){
console.log("Error send to:"+client.id+" error:"+Error);
}
}
});
if(!found){
console.log("Error user not found:"+id);
}
}
/**
* RATE LIMIT SIN BIN
*/
function sinbin(uuid, socket, message){
//Add User to the Sin bin..
RATE_LIMIT.addUserSinBin(uuid);
//Tell the user to refresh in 10 minutes..
var rateobj = {};
rateobj.uuid = "0x000000";
rateobj.message = message;
//Send them a message..
socket.send(createCustomMsg("0x00","ratelimit",rateobj));
}
/**
* Add a trade = only keep the last X many
*/
function addTrade(trade){
//Push to our list..
alltrades.push(trade);
//Max number of trades
if(alltrades.length > MAX_TRADES){
alltrades.shift();
}
}
/**
* Add a Chat message
*/
function newChat(fromuuid, msg){
//No blank messages
if(msg.data.trim() == ""){
return;
}else if(msg.data.length > 256){
//Too long..
return;
}
//Create a Chat object
var chatobj = {};
chatobj.uuid = fromuuid;
chatobj.message = msg.data.trim();
//Push to our list..
allchat.push(chatobj);
//Max number of trades
if(allchat.length > 500){
allchat.shift();
}
//Broadcast to all..
broadcast(createCustomMsg(fromuuid,"chat",chatobj));
}
//Create any message
function createCustomMsg(id, type, data){
var msg = {};
msg.uuid = id;
msg.type = type;
msg.data = data;
return JSON.stringify(msg);
}
//Check the Update_orderBook message
function checkOrderBookMessage(orderbook){
//Check is a valid book
if(!( orderbook.address &&
orderbook.script &&
orderbook.balance &&
orderbook.orders)){
//Bad Orderbook
return false;
}
//How many orders
if(orderbook.orders.length >= MAX_USER_ORDERS){
return false;
}
return true;
}
//Add an order to a Users Orderbook
function addOrder(fromid, order){
//Get that Orderbook
var book = orderbooks[fromid].orders;
book.push(order);
}
//Remove an order from a User
function removeOrder(fromid, bookuuid){
//Get that Orderbook
var book = orderbooks[fromid].orders;
//Now remove that order
var neworders = [];
var len = book.length;
for(var i=0;i<len;i++) {
if(book[i].uuid != bookuuid){
neworders.push(book[i]);
}
}
//Reset User Orders
orderbooks[fromid].orders = neworders;
}
/**
* IF a MEG server is spoecified.. will check a Trade before sending on..
*/
var MEG_AUTH = 'Basic ' + Buffer.from(MEG_USERPASS).toString('base64');;
var MAX_CHECK_ATTEMPTS = 20;
var CHECK_TRADES = [];
if(MEG_CHECK_TRADES){
setInterval(function(){
//Any trades to check
if(CHECK_TRADES.length==0){
return;
}
if(DEBUG_LOGS){
console.log("Check all new trades..");
}
//Check TRADES txpowid..
var keeptrades = [];
for(var i=0;i<CHECK_TRADES.length;i++){
if(!CHECK_TRADES[i].checked){
if(CHECK_TRADES[i].checkedamount<MAX_CHECK_ATTEMPTS){
try{
//Check if this is a valid trade
checkTrade(CHECK_TRADES[i]);
//Keeper
keeptrades.push(CHECK_TRADES[i]);
}catch(err){
console.log("Error checking trade : "+JSON.stringify(CHECK_TRADES[i])+" "+err);
}
}
}
}
//Set new list
CHECK_TRADES = keeptrades;
}, 1000 * 30);
//Run a check
UTILS.postURL(MEG_SERVER, MEG_PORT, MEG_AUTH, "/wallet/block","",function(resp){
console.log("MEG check block call : "+JSON.stringify(resp));
});
}
function addCheckTrade(trade){
if(DEBUG_LOGS){
console.log("Check trade added : "+JSON.stringify(trade));
}
//Trade not checked..
trade.checked = false;
trade.checkedamount = 0;
//Check it..
CHECK_TRADES.push(trade);
}
function checkTrade(trade){
//Increment checked amount..
trade.checkedamount++;
//Check if this trade exists..
checkTxPoW(trade.txpowid, function(resp){
console.log("CHECK : "+JSON.stringify(resp));
if(resp.status && resp.response.found){
trade.checked=true;
if(DEBUG_LOGS){
console.log("Valid trade found : "+JSON.stringify(resp));
}
//Add it to our list
addTrade(trade);
//Broadcast
broadcast(createCustomMsg("0x00","trade_check",trade));
}
});
}
function checkTxPoW(txpowid,callback){
UTILS.postURL(MEG_SERVER, MEG_PORT, MEG_AUTH, "/wallet/checktxpow","txpowid="+txpowid, function(resp){
callback(resp);
});
}