From 2c35c545e8525a9551eba4820593bdf2e4b8df4f Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 25 Jan 2022 01:28:22 +0530 Subject: [PATCH] Bug fixes (client side) Fixed Client page bugs: - Fixed minor bugs in client side pages - client page to use floGlobals.js - moved KBucket.js to public (as its need by client page too). Fixed Server Bugs: - Added Access-Control-Allow-Origin to response headers - Fixed: trustedIDs not loaded - Fixed minor bugs (syntax errors) --- {src/backup => public}/KBucket.js | 9 +++++--- public/fn.js | 17 +++++++------- public/home.html | 37 +++++++++---------------------- src/app.js | 14 ++++++++++-- src/backup/head.js | 2 +- src/main.js | 4 +--- src/request.js | 13 ++++++----- 7 files changed, 45 insertions(+), 51 deletions(-) rename {src/backup => public}/KBucket.js (98%) diff --git a/src/backup/KBucket.js b/public/KBucket.js similarity index 98% rename from src/backup/KBucket.js rename to public/KBucket.js index 51932b7..247896a 100644 --- a/src/backup/KBucket.js +++ b/public/KBucket.js @@ -1,5 +1,6 @@ 'use strict'; +(function(){ /*Kademlia DHT K-bucket implementation as a binary tree.*/ /** * Implementation of a Kademlia DHT k-bucket used for storing @@ -7,7 +8,7 @@ * * @extends EventEmitter */ -function BuildKBucket(options = {}) { + function BuildKBucket(options = {}) { /** * `options`: * `distance`: Function @@ -401,7 +402,7 @@ function BuildKBucket(options = {}) { } } -module.exports = function K_Bucket(masterID, backupList) { +function K_Bucket(masterID, backupList) { const decodeID = function(floID) { let k = bitjs.Base58.decode(floID); k.shift(); @@ -457,4 +458,6 @@ module.exports = function K_Bucket(masterID, backupList) { return (N == 1 ? nNodes[0] : nNodes); }; -} \ No newline at end of file +}; +('object' === typeof module) ? module.exports = K_Bucket : window.K_Bucket = K_Bucket; +})(); \ No newline at end of file diff --git a/public/fn.js b/public/fn.js index 85b8678..1b59c26 100644 --- a/public/fn.js +++ b/public/fn.js @@ -6,10 +6,9 @@ function exchangeAPI(api, options) { let curPos = exchangeAPI.curPos || 0; if (curPos >= nodeList.length) return resolve('No Nodes online'); - let url = nodeURL[nodeList[curPos]]; + let url = "http://" + nodeURL[nodeList[curPos]]; (options ? fetch(url + api, options) : fetch(url + api)) .then(result => resolve(result)).catch(error => { - console.debug(error); console.warn(nodeList[curPos], 'is offline'); //try next node exchangeAPI.curPos = curPos + 1; @@ -102,7 +101,7 @@ function getAccount(floID, proxySecret) { }; request.sign = signRequest({ type: "get_account", - timestamp: data.timestamp + timestamp: request.timestamp }, proxySecret); console.debug(request); @@ -168,7 +167,7 @@ function signRequest(request, privKey) { function getLoginCode() { return new Promise((resolve, reject) => { - exchangeAPI('/list-buyorders') + exchangeAPI('/get-login-code') .then(result => responseParse(result) .then(result => resolve(result)) .catch(error => reject(error))) @@ -249,7 +248,7 @@ function logout(floID, proxySecret) { }; request.sign = signRequest({ type: "logout", - timestamp: data.timestamp + timestamp: request.timestamp }, proxySecret); console.debug(request); @@ -543,8 +542,8 @@ function refreshDataFromBlockchain() { return new Promise((resolve, reject) => { let nodes, lastTx; try { - nodes = JSON.parse(localStorage.getItems('exhange-nodes')); - if (typeof nodes !== 'object') + nodes = JSON.parse(localStorage.getItem('exchange-nodes')); + if (typeof nodes !== 'object' || nodes === null) throw Error('nodes must be an object') else lastTx = parseInt(localStorage.getItem('exchange-lastTx')) || 0; @@ -569,8 +568,8 @@ function refreshDataFromBlockchain() { nodes[n] = content.Nodes.add[n]; } }); - localStorage.setItem('exhange-lastTx', result.totalTxs); - localStorage.setItem('exhange-nodes', JSON.stringify(nodes)); + localStorage.setItem('exchange-lastTx', result.totalTxs); + localStorage.setItem('exchange-nodes', JSON.stringify(nodes)); nodeURL = nodes; nodeKBucket = new K_Bucket(floGlobals.adminID, Object.keys(nodeURL)); nodeList = nodeKBucket.order; diff --git a/public/home.html b/public/home.html index fbec54b..5a978f0 100644 --- a/public/home.html +++ b/public/home.html @@ -12,27 +12,10 @@ - + + @@ -1068,9 +1051,9 @@ showProcess('trade_button_wrapper') try { if (tradeType === 'buy') { - await buy(quantity, price, await proxy.secret) + await buy(quantity, price, proxy.userID, await proxy.secret) } else { - await sell(quantity, price, await proxy.secret) + await sell(quantity, price, proxy.userID, await proxy.secret) } getRef('trade_button_wrapper').append(getRef('success_template').content.cloneNode(true)) notify(`Placed ${tradeType} order`, 'success') @@ -1218,9 +1201,9 @@ showWalletResult('success', `Sent ${asset} deposit request`, 'This may take upto 30 mins to reflect in your wallet.') } else { if (asset === 'FLO') { - await withdrawFLO(quantity, proxySecret) + await withdrawFLO(quantity, proxy.userID, proxySecret) } else { - await withdrawRupee(quantity, proxySecret) + await withdrawRupee(quantity, proxy.userID, proxySecret) } showWalletResult('success', `Sent ${asset} withdraw request`, 'This may take upto 30 mins to reflect in your wallet.') } @@ -1363,7 +1346,7 @@ const target = e.target.closest('.order-card') const id = target.dataset.id const type = target.dataset.type - cancelOrder(type, id, await proxy.secret) + cancelOrder(type, id, proxy.userID, await proxy.secret) .then(() => { notify('Order cancelled', 'success') target.animate([ @@ -1415,7 +1398,7 @@ if (res) { try { const proxy_secret = await proxy.secret; - const promises = [...selectedOrders].map(([id, type]) => cancelOrder(type, id, proxy_secret)) + const promises = [...selectedOrders].map(([id, type]) => cancelOrder(type, id, proxy.userID, proxy_secret)) await Promise.all(promises) selectedOrders.clear() hideMyOrdersOptions() @@ -1687,7 +1670,7 @@ const balance = {} let accountDetails = {} - function account() { + async function account() { getAccount(proxy.userID, await proxy.secret).then(acc => { getRef("login_form").classList.add('hide-completely') getRef('home').classList.add('signed-in') @@ -1778,7 +1761,7 @@ refreshDataFromBlockchain().then(nodes => { console.log(nodes); refresh(true); - }).catch(error => reject(error)) + }).catch(error => console.error(error)) }) diff --git a/src/app.js b/src/app.js index 582a0f9..cc05e06 100644 --- a/src/app.js +++ b/src/app.js @@ -37,6 +37,16 @@ module.exports = function App(secret, DB) { })); */ + app.use(function(req, res, next) { + res.setHeader('Access-Control-Allow-Origin', "*"); + // Request methods you wish to allow + res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); + // Request headers you wish to allow + res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); + // Pass to next layer of middleware + next(); + }) + //get code for login or signup app.get('/get-login-code', Request.getLoginCode); @@ -47,7 +57,7 @@ module.exports = function App(secret, DB) { app.post('/login', Request.Login); //logout request - app.get('/logout', Request.Logout); + app.post('/logout', Request.Logout); //place sell or buy order app.post('/buy', Request.PlaceBuyOrder); @@ -65,7 +75,7 @@ module.exports = function App(secret, DB) { app.get('/get-rate', Request.getRate) //get account details - app.get('/account', Request.Account); + app.post('/account', Request.Account); //withdraw and deposit request app.post('/deposit-flo', Request.DepositFLO); diff --git a/src/backup/head.js b/src/backup/head.js index 7096bcf..4a70b02 100644 --- a/src/backup/head.js +++ b/src/backup/head.js @@ -1,6 +1,6 @@ 'use strict'; -const K_Bucket = require('./KBucket'); +const K_Bucket = require('../../public/KBucket'); const slave = require('./slave'); const WebSocket = require('ws'); const shareThreshold = 50 / 100; diff --git a/src/main.js b/src/main.js index f95ca20..42a2b73 100644 --- a/src/main.js +++ b/src/main.js @@ -27,7 +27,6 @@ function refreshDataFromBlockchain() { return new Promise((resolve, reject) => { DB.query("SELECT num FROM lastTx WHERE floID=?", [floGlobals.adminID]).then(result => { let lastTx = result.length ? result[0].num : 0; - console.debug('lastTx', lastTx); floBlockchainAPI.readData(floGlobals.adminID, { ignoreOld: lastTx, sentOnly: true, @@ -38,7 +37,6 @@ function refreshDataFromBlockchain() { trusted_change = false; result.data.reverse().forEach(data => { var content = JSON.parse(data)[floGlobals.application]; - console.debug(content); //Node List if (content.Nodes) { nodes_change = true; @@ -95,7 +93,7 @@ function loadDataFromDB(changes, startup) { if (startup || changes.nodes) promises.push(loadDataFromDB.nodeList()); if (startup || changes.trusted) - promises.push(loadDataFromDB.trustedIDs); + promises.push(loadDataFromDB.trustedIDs()); Promise.all(promises) .then(_ => resolve("Data load successful")) .catch(error => reject(error)) diff --git a/src/request.js b/src/request.js index 8d51727..5fcc6f8 100644 --- a/src/request.js +++ b/src/request.js @@ -29,12 +29,12 @@ function validateRequestFromFloID(request, sign, floID, proxy = true) { if (!serving) return reject(INVALID(INVALID_SERVER_MSG)); else if (!floCrypto.validateAddr(floID)) - return res.status(INVALID.e_code).send("Invalid floID"); + return reject(INVALID.e_code).send("Invalid floID"); DB.query("SELECT " + (proxy ? "session_time, proxyKey AS pubKey FROM Sessions" : "pubKey FROM Users") + " WHERE floID=?", [floID]).then(result => { if (result.length < 1) return reject(INVALID(proxy ? "Session not active" : "User not registered")); if (proxy && result[0].session_time + maxSessionTimeout < Date.now()) - return res.status(INVALID.e_code).send("Session Expired! Re-login required"); + return reject(INVALID.e_code).send("Session Expired! Re-login required"); let req_str = validateRequest(request, sign, result[0].pubKey); req_str instanceof INVALID ? reject(req_str) : resolve(req_str); }).catch(error => reject(error)); @@ -64,7 +64,7 @@ function storeRequest(floID, req_str, sign) { function getLoginCode(req, res) { let randID = floCrypto.randString(8, true) + Math.round(Date.now() / 1000); let hash = Crypto.SHA1(randID + secret); - res.status(INVALID.e_code).send({ + res.send({ code: randID, hash: hash }); @@ -111,9 +111,9 @@ function Login(req, res) { proxyKey: data.proxyKey, timestamp: data.timestamp }, data.sign, data.floID, false).then(req_str => { - DB.query("INSERT INTO Sessions (floID, proxyKey) VALUES (?, ?, ?) " + - "ON DUPLICATE KEY UPDATE session_time=DEFAULT, proxyKey=?", - [data.floID, data.code, data.proxyKey, data.code, data.proxyKey]).then(_ => { + DB.query("INSERT INTO Sessions (floID, proxyKey) VALUE (?, ?) AS new " + + "ON DUPLICATE KEY UPDATE session_time=DEFAULT, proxyKey=new.proxyKey", + [data.floID, data.proxyKey]).then(_ => { storeRequest(data.floID, req_str, data.sign); res.send("Login Successful"); }).catch(error => { @@ -131,6 +131,7 @@ function Login(req, res) { } function Logout(req, res) { + let data = req.body; validateRequestFromFloID({ type: "logout", timestamp: data.timestamp