-
Notifications
You must be signed in to change notification settings - Fork 5
/
app_mongo.js
747 lines (621 loc) · 24.9 KB
/
app_mongo.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
//
// Add indexes in mongo
// Before start create user and indexes
/*
db.slates.createIndex({queue:1, made:1, createdat: 1});
db.slates.createIndex({messageid:1, made:1});
db.slates.createIndex({ "createdat": 1 }, {expireAfterSeconds: 604800 });
db.createUser(
{
user: "epicbox",
pwd: passwordPrompt(), // or cleartext password
roles: [
{ role: "readWrite", db: "epicbox" },
{ role: "readWrite", db: "epicbox" }
]
}
);
*/
const fs = require("fs");
const {createServer} = require("http");
const { execFile } = require('node:child_process');
const uid = require('uid2');
const { WebSocket, WebSocketServer } = require('ws');
const { MongoClient } = require('mongodb');
const customConfig = process.argv.indexOf('--config');
//this epicbox protocol version
const protver = "3.0.0";
/**
* @deprecated in wallet version 3.5.2
* use dynamic challenge strings
*/
const static_challenge = "7WUDtkSaKyGRUnQ22rE3QUXChV8DmA6NnunDYP4vheTpc";
//used to reference client socket (ws) to public address (epic address) for slate passthroughs
const clients_publicaddress = {};
const config = {
mongourl: "mongodb://127.0.0.1:27019",
epicbox_domain: "epicbox.epiccash.com",
epicbox_port: "443",
localepicboxserviceport: "3423",
pathtoepicboxlib: "./epicboxlib",
db_name: "epicbox",
collection_name: "slates",
challenge_interval: 60000,
debugMessage: true,
stats: false,
};
let mongoclient = null;
let collection = null;
let statistics = {
from: new Date(),
connectionsInHour: 0,
slatesReceivedInHour: 0,
slatesRelayedInHour:0,
slatesSentInHour: 0,
subscribeInHour: 0,
activeconnections: 0,
slatesAttempt:0
}
//clean stats every hour
setInterval(()=>{
statistics = {
from: new Date(),
connectionsInHour: 0,
slatesReceivedInHour: 0,
slatesRelayedInHour: 0,
slatesSentInHour: 0,
subscribeInHour: 0,
activeconnections: 0,
slatesAttempt: 0
}
}, 60*60*1000);
const requestListener = (req, res) => {
res.writeHead(200)
res.end(`<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<title>Epicbox</title>\n\
<style>a:link {\n\
color: orange;\n\
} a:visited {\n\
color: orange;\n\
}</style>\n\
</head>\n\
<body style='background-color: #242222; color: lightgray; margin-left: 20px;''>\n\
\n\
<h2>Epicbox Server</h2>\n\
<p>Protocol version ${protver}</p>\n\
<p>Americas - epicbox.epiccash.com</p>\n\
<p>Americas - epicbox.epicnet.us</p>\n\
<p>Europe - epicbox.fastepic.eu</p>\n\
<p>Europe - epicbox.btlabs.tech</p>\n\
<p>Europe - epicbox.51pool.online</p>\n\
<br>\n\
<p>More about Epic</p>\n\
<a href='https://epiccash.com'>Epic Cash</a>\n\
<br>\n\
<br>\n\
Required epic-wallet.toml settings.\n\
\n\
<pre>\n\
<code>\n\
\n\
[epicbox]\n\
epicbox_domain = 'epicbox.epiccash.com'\n\
epicbox_port = 443\n\
\n\
</code>\n\
</pre>\n\
<p> start wallet listener: ./epic-wallet listen -m epicbox</p>\n\
<br>\n\
<h2>\n\
Epicbox Statistics from ${statistics.from.toUTCString()}:\n\
</h1>\n\
<h2>\n\
connections: ${statistics.connectionsInHour}<br>\n\
active connections: ${statistics.activeconnections}<br>\n\
subscribes: ${statistics.connectionsInHour}<br>\n\
received slates: ${statistics.slatesReceivedInHour}<br>\n\
relayed slates: ${statistics.slatesRelayedInHour}<br>\n\
sending slate attempts: ${statistics.slatesAttempt}<br>\n\
</h3>\n\
</body>\n\
</html>`);
}
/*
webserver for port 80
*/
const server = createServer(requestListener);
/*
epicbox websocket
*/
const wss = new WebSocketServer({
server: server,
});
wss.on('connection', (ws, req) => {
if(config.stats){
statistics.connectionsInHour++;
}
ws.uid = uid(5);
ws.epicboxver = null;
ws.ip = null;
ws.challenge = null;
ws.epicPublicAddress = null;
//don't send challenges or slates to busy client
ws.process_slate = false;
//count send attempts to client
ws.sendslate_attempts = 0;
ws.max_sendslate_attempts = 0;
ws.pending_challenge = false;
ws.client_details = {
wallet_version: '',
wallet_mode: '',
protocol_version: ''
};
if (req.headers['x-forwarded-for']){
ws.ip = req.headers['x-forwarded-for'].split(',')[0].trim();
} else {
ws.ip = req.socket.remoteAddress;
}
console.log(`[${new Date().toLocaleTimeString()}] [${ws.uid}] New connection from `, ws.ip);
// send a Challenge to wallet or other epicbox when first time connect
// challenges are send in interval every x seconds later
challenge(ws);
ws.on('close', (code, reason) => {
if(ws.client_details.wallet_mode == 'listener'){
delete clients_publicaddress[ws.epicPublicAddress];
}
ws.epicPublicAddress = null;
console.log('[%s] - [%s][%s] -> [%s] code: %s, reason: %s', new Date().toLocaleTimeString(), ws.uid, ws.ip, "Close connection", code, reason.toString());
});
ws.on('error', (err) => {
if(ws.client_details.wallet_mode == 'listener'){
delete clients_publicaddress[ws.epicPublicAddress];
}
ws.epicPublicAddress = null;
console.log('[%s] - [%s][%s] -> [%s] error: %s', new Date().toLocaleTimeString(), ws.uid, ws.ip, "Error", err);
});
ws.on('message', (data) => {
let message = null;
try{
message = JSON.parse(data);
}catch(err){
console.log("Error parsing json data from client.", err);
if(ws.client_details.wallet_mode == 'listener'){
delete clients_publicaddress[ws.epicPublicAddress];
}
ws.epicPublicAddress = null;
return ws.close(code = 3000, reason = 'Error parsing message.');
}
let type = message.type;
/* TODO:
- clients should set version via setVersion type
- split wallet client from epicbox client
*/
switch (type.toLowerCase()) {
case "ping":
ws.send("pong");
break;
case "pong":
ws.send("ping");
break;
/**
* @deprecated epicbox protocol version 3.0.0
* clients should not be allowed to trigger challenge/subscribe requests
*/
case "challenge":
challenge(ws);
break;
case "subscribe":
subscribe(ws, message);
break;
case "unsubscribe":
unsubscribe(ws);
break;
case "postslate":
validatePostslate(ws, message);
break;
//made is send after slate was successfully processed in wallet
case "made":
made(ws, message);
break;
/**
* @deprecated epicbox protocol version 3.0.0
*/
case "getversion":
ws.send(JSON.stringify({type: "GetVersion", str: protver}))
break;
/**
* @deprecated epicbox protocol version 3.0.0
*/
case "fastsend":
ws.send(JSON.stringify({type:"Ok"}));
break;
case "clientdetails":
clientdetails(ws, message);
break;
}
//end switch message type
console.log('[%s] - [%s][%s] -> [%s]', new Date().toLocaleTimeString(), ws.uid, ws.ip, type);
config.debugMessage ? console.log("Message", message) : null;
});
});
/*
get current unix timestamp
*/
const getTimestamp = () => {
return Math.floor(Date.now() / 1000);
}
/*
send challenge to client.
the first challenge must use the old static challenge string for backward compatibility.
older epicbox clients with protocol version 2.0.0
new epicbox/clients can use a dynamic challenge.
//TODO if client blocks then this send messages are waiting in the queue
@param {object} ws - Client socket
*/
const challenge = (ws) => {
//we do not know clients epicbox version on first challenge request.
//todo. client should send its version when connect to epicbox via client_details
let challenge = ws.epicboxver == "2.0.0" || ws.epicboxver == null ? static_challenge : uid(32);
ws.challenge = challenge;
ws.send(JSON.stringify({"type": "Challenge", "str": challenge}));
ws.pending_challenge = true;
}
/*
Information about the clients wallet version, Client command and supported epixbox protocol
@param {object} ws - Client socket
@param {json} message - Client message see epic wallet
*/
const clientdetails = (ws, message) => {
ws.client_details = message;
ws.send(JSON.stringify({type:"Ok"}));
}
/*
Subscribe
validate client address and send back a pending slate
@param {object} ws - Client socket
@param {json} message - Client message see epic wallet
*/
const subscribe = (ws, message) => {
try{
//set used epicbox protocol version
if(message.hasOwnProperty("ver")){
switch (message.ver) {
case "2.0.0":
ws.epicboxver = "2.0.0";
break;
default:
//new version is
ws.epicboxver = "3.0.0";
break;
}
}
// verify that client is the owner of the public key
let args = ["verifysignature", message.address, ws.challenge, message.signature];
const child = execFile(config.pathtoepicboxlib, args, (error, stdout, stderr) => {
if (error) throw error;
// if signature is OK
if(stdout === 'true'){
if(config.stats){
statistics.subscribeInHour++;
}
// client proved that he is the owner of the public address
ws.epicPublicAddress = message.address;
//add client listener for passthrough slates;
if(clients_publicaddress[ws.epicPublicAddress] == undefined && ws.client_details.wallet_mode == 'listener'){
clients_publicaddress[ws.epicPublicAddress] = ws;
}
ws.lastSubscriptionTime = getTimestamp();
ws.pending_challenge = false;
//if at some case a made request was not send back from client
//we set 'process_slate' back to false after 3 successfully subscriptions
//and let the client try to process not made slates again.
//max resets are limited to 3 rounds.
if(ws.sendslate_attempts >= 3 && ws.max_sendslate_attempts <= 3){
ws.sendslate_attempts = 0;
ws.max_sendslate_attempts++;
ws.process_slate = false;
}
//if it's not possible for client to process not made slates after 3 rounds (=9 attempts),
//then delete all not made slates from client in db
if(ws.max_sendslate_attempts >= 3){
collection.deleteMany({ queue: ws.epicPublicAddress, made: false});
ws.sendslate_attempts = 0;
ws.max_sendslate_attempts = 0;
ws.process_slate = false;
}
//get not processed tx for client
//prevent sending same slate multible times
if(ws.process_slate == false){
collection.find({ queue: ws.epicPublicAddress, made: false}).sort({ "createdat" : 1 }).limit(1).toArray().then( (res) => {
if(res && res.length > 0) {
if(config.stats){
statistics.slatesAttempt++;
}
let dbslate = res[0];
let payload = JSON.parse(dbslate.payload);
let slate = {
type: "Slate",
from: dbslate.replyto,
str: payload.str,
signature: payload.signature,
challenge: payload.challenge,
};
if(ws.epicboxver == "2.0.0" || ws.epicboxver == "3.0.0"){
slate.epicboxmsgid = dbslate.messageid;
slate.ver = ws.epicboxver;
}else{
collection.updateOne({ messageid:dbslate.messageid }, { $set: { made:true } });
}
//TODO: check if this was already send on previous interval to client but client does block
//if client blocks, this will end in multible made requests
//we must set a flag here if the slate to client was already send but client did not process yet for any reasons.
ws.send(JSON.stringify(slate));
ws.process_slate = true;
console.log("Sent slate to", ws.epicPublicAddress);
config.debugMessage ? console.log(slate) : null;
}else{
//no slate found but subscribe was ok
ws.send(JSON.stringify({type:"Ok"}));
}
//end if result > 0
});
}else{
//send back some response
ws.sendslate_attempts++;
ws.send(JSON.stringify({type:"Ok"}));
}
}else{
//client cannot prove that he is the owner of the public address
if(ws.client_details.wallet_mode == 'listener'){
delete clients_publicaddress[ws.epicPublicAddress];
}
ws.epicPublicAddress = null;
ws.send(JSON.stringify({type: "Error", kind: "signature error", description: "Invalid signature."}));
}
});
}catch(err){
console.log("Erro execute epicboxlib", err);
}
}
/*
Unsubscribe and close client connection
@param {object} ws - Client socket
*/
const unsubscribe = (ws) => {
if(ws.epicPublicAddress != null){
if(ws.client_details.wallet_mode == 'listener'){
delete clients_publicaddress[ws.epicPublicAddress];
}
ws.epicPublicAddress = null;
ws.close(1000, "Work complete.");
}
}
/*
client sends a new tx or a response to an tx
validate address format and signature
@param {object} ws - Client socket
@param {json} message - Client message see epic wallet
*/
const validatePostslate = (ws, message) => {
try {
console.log("postslate from ", message.from, "to ", message.to);
let publickey = message.from.split('@');
publickey = publickey[0];
// use epicboxlib to verify address format
let args = ['verifyaddress', message.from, message.to];
execFile(config.pathtoepicboxlib, args, (error, stdout, stderr) => {
if(error) throw error;
if(stdout === 'true') {
//verify that the message we receive was signed from publickey
let args = ["verifysignature", publickey, message.str, message.signature];
execFile(config.pathtoepicboxlib, args, (error, stdout, stderr) => {
if (error) throw error;
if(stdout === 'true') {
if(config.stats){
statistics.slatesReceivedInHour++;
}
postSlate(ws, message);
}else{
console.log("Error postslate signature", publickey);
ws.send(JSON.stringify({type: "Error", kind: "postslate error", description: "Invalid signature."}));
}
});
}else{
console.log("Error validate address format", message.from, message.to);
ws.send(JSON.stringify({type:"Error", kind:"postslate error", description: "Wrong address format."}));
}
});
}catch(err){
console.error("Error postslate", err);
}
}
/*
client sends made response if successfully processed slate
@param {object} ws - Client socket
@param {json} message - Client message see epic wallet
*/
const made = (ws, message) => {
if(ws.epicPublicAddress != null && message.hasOwnProperty("epicboxmsgid") && message.hasOwnProperty("ver") && (message.ver == "2.0.0" || message.ver == "3.0.0")){
let args = [];
if(message.ver == "3.0.0"){
args = ["verifysignature", ws.epicPublicAddress, message.epicboxmsgid, message.signature];
}else{
args = ["verifysignature", ws.epicPublicAddress, ws.challenge, message.signature];
}
const child = execFile(config.pathtoepicboxlib, args, (error, stdout, stderr) => {
if (error) throw error;
if(stdout === 'true') {
console.log("Update for ", message.epicboxmsgid);
collection.updateOne({queue: ws.epicPublicAddress, messageid: message.epicboxmsgid, made:false}, { $set: {made:true}}).then( (updateResult) => {
config.debugMessage ? console.log("DB update result", updateResult) : null;
ws.send(JSON.stringify({type:"Ok"}));
ws.process_slate = false;
ws.sendslate_attempts = 0;
//if this slate was processed then send the next slate to client via challenge->subscribe
challenge(ws);
});
}else{
ws.send(JSON.stringify({type: "Error", kind: "made error", description: "Invalid signature."}));
}
});
}
}
/*
store tx in db or forward to foreign epicbox
if domain does not match our epicbox domain
@param {object} ws - Client socket
@param {json} message - Client message see epic wallet
*/
const postSlate = (ws, json) => {
let str = {};
try{
str = JSON.parse(json.str);
}catch(err){
console.log("Error parsing message string", err);
return;
}
let addressto = {};
addressto.publicKey = str.destination.public_key;
addressto.domain = str.destination.domain;
addressto.port = str.destination.port != null ? str.destination.port : 443;
if(addressto.domain === config.epicbox_domain && addressto.port === config.epicbox_port){
//challenge is not required, we keep it for backward compatibility
let signed_payload = JSON.stringify({str: json.str, challenge: "", signature: json.signature});
let messageid = uid(32);
// insert slate to db
collection.insertOne({
queue: addressto.publicKey,
made: false,
payload: Buffer.from(signed_payload),
replyto: json.from,
createdat: new Date(),
expiration: 86400000,
messageid: messageid
}).catch((err)=>{
console.error("Error insert to db", err);
});
//check if receiver is online, then pass slate through for faster processing
let receiver = clients_publicaddress[addressto.publicKey];
if(receiver != undefined && receiver.process_slate == false && receiver.readyState === 1){
if(config.stats){
statistics.slatesAttempt++;
}
let slate = {
type: "Slate",
from: json.from,
str: json.str,
signature: json.signature,
challenge: "",
};
//TODO: cleanup version stuff, kick out old clients <2.0.0
if(receiver.epicboxver == "2.0.0" || receiver.epicboxver == "3.0.0"){
slate.epicboxmsgid = messageid;
slate.ver = receiver.epicboxver;
}else{
collection.updateOne({ messageid:messageid }, { $set: { made:true } });
}
ws.send(JSON.stringify({type:"Ok"}));
receiver.send(JSON.stringify(slate));
receiver.process_slate = true;
console.log("Passthrough slate to", receiver.epicPublicAddress);
config.debugMessage ? console.log(slate) : null;
}else{
ws.send(JSON.stringify({type:"Ok"}));
}
}else{
// forward tx to foreign epicbox
sock = new WebSocket("wss://" + addressto.domain +":"+ addressto.port);
sock.on('error', console.error);
sock.on('open', () => {
console.log("Connect "+ addressto.domain +":"+ addressto.port);
});
sock.on('message', (data) => {
try{
message = JSON.parse(data);
if(message.type === "Challenge") {
let slate = {type: "PostSlate", from: json.from, to: json.to, str: json.str, signature: json.signature};
sock.send(JSON.stringify(slate));
}
if( message.type === "Ok" ) {
if(config.stats){
statistics.slatesRelayedInHour++;
}
console.log("Sent to wss://"+ addressto.domain +":"+ addressto.port);
ws.send(JSON.stringify({type:"Ok"}));
}
}catch(err){
console.error("Error forward slate to foreign epicbox", err);
ws.send(JSON.stringify({type: "Error", kind: "foreign epicbox", description:"Error send Slate to foreign epicbox"}));
}
});
}
}
/*
send recurring challenge -> subscribe cycles to all clients
*/
const challengeInterval = () => {
wss.clients.forEach( (ws) => {
if (ws.readyState === 1
&& ws.epicPublicAddress !== null
//do not spam clients with challenge requests
//do not send new challenge if old challenge request was not subscribed (when client blocks)
&& (ws.pending_challenge == false || (getTimestamp() - ws.lastSubscriptionTime >= config.challenge_interval))
) {
try{
challenge(ws);
}catch(err){
console.log("Send Interval challenge error ", err);
}
}
});
}
/*
load config for epixbox custom settings
*/
const loadConfig = async(filePath) =>{
try{
let jsonData = fs.readFileSync(filePath, 'utf8');
let data = JSON.parse(jsonData);
config.mongourl = data.mongo_url != undefined ? data.mongo_url : config.mongourl;
config.epicbox_domain = data.epicbox_domain != undefined ? data.epicbox_domain : config.epicbox_domain;
config.epicbox_port = data.epicbox_port != undefined ? data.epicbox_port : config.epicbox_port;
config.localepicboxserviceport = data.local_epicbox_service_port != undefined ? data.local_epicbox_service_port: config.localepicboxserviceport;
config.pathtoepicboxlib = data.path_to_epicboxlib_exec_file != undefined ? data.path_to_epicboxlib_exec_file : config.pathtoepicboxlib;
config.db_name = data.mongo_dbName != undefined ? data.mongo_dbName : config.db_name;
config.collection_name = data.mongo_collection_name != undefined ? data.mongo_collection_name : config.collection_name;
config.challenge_interval = data.challenge_interval != undefined ? data.challenge_interval : config.challenge_interval;
config.debugMessage = data.debug != undefined ? data.debug : config.debugMessage;
config.stats = data.stats != undefined ? data.stats : config.stats;
} catch(err){
console.error(err);
}
}
const startEpicbox = async() => {
let configPath = customConfig != -1 && process.argv[customConfig+1] != undefined ? process.argv[customConfig+1] : './config.json';
console.log("Use config:", configPath);
await loadConfig(configPath);
mongoclient = new MongoClient(config.mongourl);
let db = mongoclient.db(config.db_name);
collection = db.collection(config.collection_name);
await mongoclient.connect();
console.log('Connected successfully to MongoDB');
server.listen(config.localepicboxserviceport);
setInterval(challengeInterval, config.challenge_interval);
console.log("Epicbox ready to work.");
}
// We are using this single function to handle multiple signals
const handle = (signal) => {
console.log(`So the signal which I have Received is: ${signal}`);
wss.clients.forEach(function each(client) {
client.close();
});
mongoclient.close();
process.exit()
}
process.on('SIGINT', handle);
process.on('SIGBREAK', handle);
//process.on("SIGTERM", handle);
//process.on("SIGKILL", handle);
startEpicbox();