This repository has been archived by the owner on Aug 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
CloakZK-RestAPI.js
511 lines (434 loc) · 14.4 KB
/
CloakZK-RestAPI.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
const express = require('express');
const https = require('https');
const fs = require('fs');
const { TipLink } = require('@tiplink/api');
const mysql = require('mysql2');
const cors = require('cors');
const allowedOrigins = ['http://localhost:8080', 'https://binaramics.com'];
const app = express();
app.use(express.json());
const port = process.env.PORT || 2222;
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
}));
const options = {
key: fs.readFileSync('/home/RLink/privkey.pem'),
cert: fs.readFileSync('/home/RLink/cert.pem'),
};
const connection = mysql.createConnection({
host: 'localhost',
user: '',
port: '3306',
password: '',
database: ''
});
let connected = false;
function handleDisconnect() {
const query = 'SELECT * FROM cloakTrades LIMIT 1';
connection.query(query, (err, result) => {
if (err) throw err;
});
connection.connect((err) => {
if (err) {
console.error(`Error connecting to database: ${err.message}`);
setTimeout(handleDisconnect, 2000);
return;
}
connected = true;
console.log(`MySQL connection state: ${connection.state}`);
});
connection.on('error', (err) => {
console.error(`MySQL connection error: ${err.message}`);
if (!connected) {
handleDisconnect();
}
});
}
setInterval(handleDisconnect, 3600000);
const { v4: uuidv4 } = require('uuid');
app.post('/checkTrade', async (req, res) => {
try {
const { tradeId } = req.body;
if(tradeId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const checkQuery = `
SELECT COUNT(*) AS count
FROM cloakTrades
WHERE TRADE_ID = ?;
`;
const [rows] = await connection.promise().query(checkQuery, [tradeId]);
const tradeExists = rows[0].count > 0;
res.status(200).json({ tradeExists });
} catch (err) {
console.error('Error checking trade existence:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/joinTrade', async (req, res) => {
try {
const { tradeId } = req.body;
if(tradeId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const checkQuery = `
SELECT *
FROM cloakTrades
WHERE
TRADE_ID = ? AND
TRADE_STATUS = 1 AND
ACCEPTOR_TOKEN IS NULL AND
TIPLINK_WALLET_ACCEPTOR IS NULL;
`;
const checkValues = [tradeId];
const [rows] = await connection.promise().query(checkQuery, checkValues);
if (rows.length === 1) {
// Conditions are met, execute the UPDATE query
const sessionId = uuidv4();
let tiplinkAcceptor = undefined;
let tiplinkWalletAcceptor = undefined;
try {
const tiplink = await TipLink.create();
tiplinkAcceptor = tiplink.url.toString();
tiplinkWalletAcceptor = tiplink.keypair.publicKey.toBase58();
} catch (err) {
console.error('Error creating TipLink:', err);
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const updateQuery = `
UPDATE cloakTrades
SET
TIPLINK_ACCEPTOR = ?,
TIPLINK_WALLET_ACCEPTOR = ?,
ACCEPTOR_TOKEN = ?
WHERE
TRADE_ID = ?;
`;
const updateValues = [
tiplinkAcceptor,
tiplinkWalletAcceptor,
sessionId,
tradeId
];
await connection.promise().query(updateQuery, updateValues);
// Return success
res.status(200).json({ sessionId, tiplinkWalletAcceptor, tradeId });
} else {
// Conditions not met, return failure
res.status(400).json({ error: 'Trade conditions not met' });
}
} catch (err) {
console.error('Error creating trade entry:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/newTrade', async (req, res) => {
try {
// const origin = req.header('Origin');
// if (origin !== 'https://binaramics.com') {
// return res.status(403).json({ error: 'Forbidden' });
// }
const tradeId = uuidv4();
const sessionId = uuidv4();
const creatorWallet = null;
const acceptorWallet = null;
const timestamp = Math.floor(Date.now() / 1000);
const tradeStatus = 1;
let tiplinkCreator = null;
const tiplinkAcceptor = null;
let tiplinkWalletCreator = null;
const tiplinkWalletAcceptor = null;
const creatorAccept = 0;
const acceptorAccept = 0;
const creatorToken = sessionId;
const acceptorToken = null;
const tradeSolAmount = 0.0;
const tiplink = await TipLink.create();
tiplinkCreator = tiplink.url.toString();
tiplinkWalletCreator = tiplink.keypair.publicKey.toBase58();
const query = `
INSERT INTO cloakTrades (
TRADE_ID,
TRADE_WALLET_CREATOR,
TRADE_WALLET_ACCEPTOR,
TIMESTAMP,
TRADE_STATUS,
TIPLINK_CREATOR,
TIPLINK_ACCEPTOR,
TIPLINK_WALLET_CREATOR,
TIPLINK_WALLET_ACCEPTOR,
CREATOR_ACCEPT,
ACCEPTOR_ACCEPT,
CREATOR_TOKEN,
ACCEPTOR_TOKEN,
TRADE_SOL_AMOUNT
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
`;
const values = [
tradeId,
creatorWallet,
acceptorWallet,
timestamp,
tradeStatus,
tiplinkCreator,
tiplinkAcceptor,
tiplinkWalletCreator,
tiplinkWalletAcceptor,
creatorAccept,
acceptorAccept,
creatorToken,
acceptorToken,
tradeSolAmount
];
await connection.promise().query(query, values);
res.status(200).json({ sessionId, tiplinkWalletCreator, tradeId });
} catch (err) {
console.error('Error creating trade entry:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/getCounterWallet', async (req, res) => {
try {
const { sessionId } = req.body;
if(sessionId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const checkQuery = `
SELECT
TIPLINK_WALLET_CREATOR,
TIPLINK_WALLET_ACCEPTOR,
CREATOR_TOKEN,
ACCEPTOR_TOKEN
FROM cloakTrades
WHERE CREATOR_TOKEN = ? OR ACCEPTOR_TOKEN = ?;
`;
const [rows] = await connection.promise().query(checkQuery, [sessionId, sessionId]);
if (rows.length === 1) {
const tradeInfo = rows[0];
const tradeData = {};
if (tradeInfo.CREATOR_TOKEN === sessionId) {
tradeData.wallet = tradeInfo.TIPLINK_WALLET_ACCEPTOR;
}
if (tradeInfo.ACCEPTOR_TOKEN === sessionId) {
tradeData.wallet = tradeInfo.TIPLINK_WALLET_CREATOR;
}
res.status(200).json(tradeData);
} else {
res.status(400).json({ error: 'Invalid sessionId' });
}
} catch (err) {
console.error('Error checking trade data:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/checkTradeStatus', async (req, res) => {
try {
const { tradeId } = req.body;
if(tradeId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const checkQuery = `
SELECT
CREATOR_ACCEPT,
ACCEPTOR_ACCEPT,
TRADE_STATUS,
CANCELED
FROM cloakTrades
WHERE TRADE_ID = ?;
`;
const [rows] = await connection.promise().query(checkQuery, [tradeId]);
if (rows.length === 1) {
const tradeInfo = rows[0];
if (tradeInfo.CANCELED) {
res.status(200).json({ status: 'Canceled' });
} else if (tradeInfo.CREATOR_ACCEPT && tradeInfo.ACCEPTOR_ACCEPT) {
if (tradeInfo.TRADE_STATUS) {
await connection.promise().query(
'UPDATE cloakTrades SET TRADE_STATUS = ? WHERE TRADE_ID = ?',
[false, tradeId]
);
}
res.status(200).json({ status: 'Approved' });
} else {
res.status(200).json({ status: 'Pending' });
}
} else {
res.status(400).json({ error: 'Invalid tradeId' });
}
} catch (err) {
console.error('Error checking trade acceptance:', err);
res.status(200).json({ status: 'Internal Error' });
}
});
app.post('/confirmTrade', async (req, res) => {
try {
const { sessionId, tradeId } = req.body;
if(tradeId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
if(sessionId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const checkQuery = `
SELECT
CREATOR_TOKEN,
ACCEPTOR_TOKEN,
CREATOR_ACCEPT,
ACCEPTOR_ACCEPT,
TRADE_STATUS
FROM cloakTrades
WHERE (CREATOR_TOKEN = ? OR ACCEPTOR_TOKEN = ?) AND TRADE_ID = ?;
`;
const [rows] = await connection.promise().query(checkQuery, [sessionId, sessionId, tradeId]);
if (rows.length === 1) {
const tradeInfo = rows[0];
if (tradeInfo.TRADE_STATUS) {
if (tradeInfo.CREATOR_TOKEN === sessionId) {
if (!tradeInfo.CREATOR_ACCEPT) {
await connection.promise().query(
'UPDATE cloakTrades SET CREATOR_ACCEPT = ? WHERE CREATOR_TOKEN = ? AND TRADE_ID = ?',
[true, sessionId, tradeId]
);
} else {
res.status(400).json({ error: 'Trade already accepted' });
return; // Return early to prevent further processing
}
}
if (tradeInfo.ACCEPTOR_TOKEN === sessionId) {
if (!tradeInfo.ACCEPTOR_ACCEPT) {
await connection.promise().query(
'UPDATE cloakTrades SET ACCEPTOR_ACCEPT = ? WHERE ACCEPTOR_TOKEN = ? AND TRADE_ID = ?',
[true, sessionId, tradeId]
);
} else {
res.status(400).json({ error: 'Trade already accepted' });
return; // Return early to prevent further processing
}
}
// Check if both parties have confirmed
if (tradeInfo.CREATOR_ACCEPT && tradeInfo.ACCEPTOR_ACCEPT) {
// Update TRADE_STATUS to false
await connection.promise().query(
'UPDATE cloakTrades SET TRADE_STATUS = ? WHERE TRADE_ID = ?',
[false, tradeId]
);
}
res.status(200).json({ status: 'Updated' });
} else {
res.status(400).json({ error: 'Invalid trade' });
}
} else {
res.status(400).json({ error: 'Invalid sessionId or tradeId' });
}
} catch (err) {
console.error('Error checking trade data:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/cancelTrade', async (req, res) => {
try {
const { sessionId, tradeId } = req.body;
if(sessionId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
if(tradeId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const updateQuery = `
UPDATE cloakTrades
SET
TRADE_STATUS = 0,
CREATOR_ACCEPT = 0,
ACCEPTOR_ACCEPT = 0,
CANCELED = 1
WHERE
(CREATOR_TOKEN = ? OR ACCEPTOR_TOKEN = ?) AND
TRADE_STATUS = 1 AND
TRADE_ID = ?;
`;
const result = await connection.promise().query(updateQuery, [sessionId, sessionId, tradeId]);
if (result[0].affectedRows > 0) {
res.status(200).json({ success: 'Trade canceled successfully' });
} else {
res.status(400).json({ error: 'Invalid sessionId or trade cannot be canceled' });
}
} catch (err) {
console.error('Error canceling trade:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/requestFunds', async (req, res) => {
try {
const { sessionId } = req.body;
if(sessionId === null) {
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const checkQuery = `
SELECT
CANCELED,
TIPLINK_CREATOR,
TIPLINK_ACCEPTOR,
CREATOR_TOKEN,
ACCEPTOR_TOKEN,
CREATOR_ACCEPT,
ACCEPTOR_ACCEPT,
TRADE_STATUS
FROM cloakTrades
WHERE CREATOR_TOKEN = ? OR ACCEPTOR_TOKEN = ?;
`;
const [rows] = await connection.promise().query(checkQuery, [sessionId, sessionId]);
if (rows.length === 1) {
const tradeInfo = rows[0];
const tradeData = {};
//handle if trade was canceled and user wants to get own deposit link back
if(tradeInfo.CANCELED) {
if (tradeInfo.CREATOR_TOKEN === sessionId) {
tradeData.link = tradeInfo.TIPLINK_CREATOR;
}
if (tradeInfo.ACCEPTOR_TOKEN === sessionId ) {
tradeData.link = tradeInfo.TIPLINK_ACCEPTOR;
}
res.status(200).json(tradeData);
}
if(!tradeInfo.CANCELED) {
if (tradeInfo.CREATOR_ACCEPT && tradeInfo.ACCEPTOR_ACCEPT) { // Check flags and status
if (tradeInfo.CREATOR_TOKEN === sessionId) {
tradeData.link = tradeInfo.TIPLINK_ACCEPTOR;
}
if (tradeInfo.ACCEPTOR_TOKEN === sessionId ) {
tradeData.link = tradeInfo.TIPLINK_CREATOR;
}
res.status(200).json(tradeData);
} else {
res.status(400).json({ error: 'Trade not fully accepted or not approved yet' });
}
}
} else {
res.status(400).json({ error: 'Invalid sessionId' });
}
} catch (err) {
console.error('Error checking trade data:', err);
res.status(500).json({ error: 'Internal Server Error' });
}
});
const server = https.createServer(options, app);
server.listen(port, () => {
console.log(`RLink API is running on port ${port}`);
});